@getopenpay/openpay-js 0.2.13 → 0.2.16-alpha.1b02bc3

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,15 +1,15 @@
1
- (function(ge,De){typeof exports=="object"&&typeof module<"u"?De(exports):typeof define=="function"&&define.amd?define(["exports"],De):(ge=typeof globalThis<"u"?globalThis:ge||self,De(ge.OpenPay={}))})(this,function(ge){"use strict";const De="https://cde.getopenpay.com";var R;(function(r){r.assertEqual=o=>o;function e(o){}r.assertIs=e;function t(o){throw new Error}r.assertNever=t,r.arrayToEnum=o=>{const s={};for(const i of o)s[i]=i;return s},r.getValidEnumValues=o=>{const s=r.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),i={};for(const c of s)i[c]=o[c];return r.objectValues(i)},r.objectValues=o=>r.objectKeys(o).map(function(s){return o[s]}),r.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},r.find=(o,s)=>{for(const i of o)if(s(i))return i},r.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}r.joinValues=n,r.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(R||(R={}));var ir;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ir||(ir={}));const v=R.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Pe=r=>{switch(typeof r){case"undefined":return v.undefined;case"string":return v.string;case"number":return isNaN(r)?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(r)?v.array:r===null?v.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?v.promise:typeof Map<"u"&&r instanceof Map?v.map:typeof Set<"u"&&r instanceof Set?v.set:typeof Date<"u"&&r instanceof Date?v.date:v.object;default:return v.unknown}},h=R.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"]),mo=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class J extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(s){return s.message},n={_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)n._errors.push(t(i));else{let c=n,l=0;for(;l<i.path.length;){const u=i.path[l];l===i.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(i))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};return o(this),n}static assert(e){if(!(e instanceof J))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,R.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const o of this.issues)o.path.length>0?(t[o.path[0]]=t[o.path[0]]||[],t[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}J.create=r=>new J(r);const ze=(r,e)=>{let t;switch(r.code){case h.invalid_type:r.received===v.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case h.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,R.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:t=`Unrecognized key(s) in object: ${R.joinValues(r.keys,", ")}`;break;case h.invalid_union:t="Invalid input";break;case h.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${R.joinValues(r.options)}`;break;case h.invalid_enum_value:t=`Invalid enum value. Expected ${R.joinValues(r.options)}, received '${r.received}'`;break;case h.invalid_arguments:t="Invalid function arguments";break;case h.invalid_return_type:t="Invalid function return type";break;case h.invalid_date:t="Invalid date";break;case h.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:R.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case h.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case h.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case h.custom:t="Invalid input";break;case h.invalid_intersection_types:t="Intersection results could not be merged";break;case h.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case h.not_finite:t="Number must be finite";break;default:t=e.defaultError,R.assertNever(r)}return{message:t}};let jr=ze;function yo(r){jr=r}function Ot(){return jr}const Nt=r=>{const{data:e,path:t,errorMaps:n,issueData:o}=r,s=[...t,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=n.filter(u=>!!u).slice().reverse();for(const u of l)c=u(i,{data:e,defaultError:c}).message;return{...o,path:s,message:c}},_o=[];function g(r,e){const t=Ot(),n=Nt({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===ze?void 0:ze].filter(o=>!!o)});r.common.issues.push(n)}class z{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const o of t){if(o.status==="aborted")return E;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const o of t){const s=await o.key,i=await o.value;n.push({key:s,value:i})}return z.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const o of t){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return E;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}}const E=Object.freeze({status:"aborted"}),Ge=r=>({status:"dirty",value:r}),q=r=>({status:"valid",value:r}),cr=r=>r.status==="aborted",lr=r=>r.status==="dirty",at=r=>r.status==="valid",it=r=>typeof Promise<"u"&&r instanceof Promise;function Mt(r,e,t,n){if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function Lr(r,e,t,n,o){if(typeof e=="function"?r!==e||!o:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}typeof SuppressedError=="function"&&SuppressedError;var b;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(b||(b={}));var ct,lt;class ie{constructor(e,t,n,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,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 Fr=(r,e)=>{if(at(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new J(r.common.issues);return this._error=t,this._error}}};function P(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:o}=r;if(e&&(t||n))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}=r;return i.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(l=d??n)!==null&&l!==void 0?l:c.defaultError}:i.code!=="invalid_type"?{message:c.defaultError}:{message:(u=d??t)!==null&&u!==void 0?u:c.defaultError}},description:o}}class x{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 Pe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Pe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new z,ctx:{common:e.parent.common,data:e.data,parsedType:Pe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(it(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;const o={common:{issues:[],async:(n=t==null?void 0:t.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pe(e)},s=this._parseSync({data:e,path:o.path,parent:o});return Fr(o,s)}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pe(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(it(o)?o:Promise.resolve(o));return Fr(n,s)}refine(e,t){const n=o=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(o):t;return this._refinement((o,s)=>{const i=e(o),c=()=>s.addIssue({code:h.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(c(),!1)):i?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof t=="function"?t(n,o):t),!1))}_refinement(e){return new te({schema:this,typeName:k.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return le.create(this,this._def)}nullable(){return Ie.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ee.create(this,this._def)}promise(){return We.create(this,this._def)}or(e){return ft.create([this,e],this._def)}and(e){return ht.create(this,e,this._def)}transform(e){return new te({...P(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new vt({...P(this._def),innerType:this,defaultValue:t,typeName:k.ZodDefault})}brand(){return new pr({typeName:k.ZodBranded,type:this,...P(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new wt({...P(this._def),innerType:this,catchValue:t,typeName:k.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return bt.create(this,e)}readonly(){return kt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const go=/^c[^\s-]{8,}$/i,vo=/^[0-9a-z]+$/,wo=/^[0-9A-HJKMNP-TV-Z]{26}$/,bo=/^[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,ko=/^[a-z0-9_-]{21}$/i,Eo=/^[-+]?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)?)??$/,Co=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,So="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ur;const Po=/^(?:(?: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])$/,Ao=/^(([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})))$/,xo=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ur="((\\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])))",To=new RegExp(`^${Ur}$`);function $r(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Io(r){return new RegExp(`^${$r(r)}$`)}function Zr(r){let e=`${Ur}T${$r(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ro(r,e){return!!((e==="v4"||!e)&&Po.test(r)||(e==="v6"||!e)&&Ao.test(r))}class X extends x{_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:h.invalid_type,expected:v.string,received:s.parsedType}),E}const n=new z;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:h.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:h.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.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:h.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&g(o,{code:h.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Co.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"email",code:h.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")ur||(ur=new RegExp(So,"u")),ur.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"emoji",code:h.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")bo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"uuid",code:h.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")ko.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"nanoid",code:h.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")go.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid",code:h.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")vo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid2",code:h.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")wo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ulid",code:h.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),g(o,{validation:"url",code:h.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"regex",code:h.invalid_string,message:s.message}),n.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:h.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.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:h.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:h.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Zr(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:h.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?To.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:h.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Io(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:h.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Eo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"duration",code:h.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Ro(e.data,s.version)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ip",code:h.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?xo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"base64",code:h.invalid_string,message:s.message}),n.dirty()):R.assertNever(s);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(o=>e.test(o),{validation:t,code:h.invalid_string,...b.errToObj(n)})}_addCheck(e){return new X({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...b.errToObj(e)})}url(e){return this._addCheck({kind:"url",...b.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...b.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...b.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...b.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...b.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...b.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...b.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...b.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...b.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...b.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...b.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...b.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...b.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...b.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...b.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...b.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...b.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...b.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...b.errToObj(t)})}nonempty(e){return this.min(1,b.errToObj(e))}trim(){return new X({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new X({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new X({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}X.create=r=>{var e;return new X({checks:[],typeName:k.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...P(r)})};function Oo(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=t>n?t:n,s=parseInt(r.toFixed(o).replace(".","")),i=parseInt(e.toFixed(o).replace(".",""));return s%i/Math.pow(10,o)}class Ae extends x{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:h.invalid_type,expected:v.number,received:s.parsedType}),E}let n;const o=new z;for(const s of this._def.checks)s.kind==="int"?R.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:h.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:h.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)&&(n=this._getOrReturnCtx(e,n),g(n,{code:h.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Oo(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),g(n,{code:h.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:h.not_finite,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,n,o){return new Ae({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:b.toString(o)}]})}_addCheck(e){return new Ae({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:b.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:b.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&R.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Ae.create=r=>new Ae({checks:[],typeName:k.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...P(r)});class xe extends x{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:h.invalid_type,expected:v.bigint,received:s.parsedType}),E}let n;const o=new z;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:h.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)&&(n=this._getOrReturnCtx(e,n),g(n,{code:h.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),g(n,{code:h.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,n,o){return new xe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:b.toString(o)}]})}_addCheck(e){return new xe({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}xe.create=r=>{var e;return new xe({checks:[],typeName:k.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...P(r)})};class ut extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==v.boolean){const n=this._getOrReturnCtx(e);return g(n,{code:h.invalid_type,expected:v.boolean,received:n.parsedType}),E}return q(e.data)}}ut.create=r=>new ut({typeName:k.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...P(r)});class je extends x{_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:h.invalid_type,expected:v.date,received:s.parsedType}),E}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return g(s,{code:h.invalid_date}),E}const n=new z;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:h.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:h.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):R.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new je({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:b.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:b.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}je.create=r=>new je({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:k.ZodDate,...P(r)});class Dt extends x{_parse(e){if(this._getType(e)!==v.symbol){const n=this._getOrReturnCtx(e);return g(n,{code:h.invalid_type,expected:v.symbol,received:n.parsedType}),E}return q(e.data)}}Dt.create=r=>new Dt({typeName:k.ZodSymbol,...P(r)});class dt extends x{_parse(e){if(this._getType(e)!==v.undefined){const n=this._getOrReturnCtx(e);return g(n,{code:h.invalid_type,expected:v.undefined,received:n.parsedType}),E}return q(e.data)}}dt.create=r=>new dt({typeName:k.ZodUndefined,...P(r)});class pt extends x{_parse(e){if(this._getType(e)!==v.null){const n=this._getOrReturnCtx(e);return g(n,{code:h.invalid_type,expected:v.null,received:n.parsedType}),E}return q(e.data)}}pt.create=r=>new pt({typeName:k.ZodNull,...P(r)});class Be extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return q(e.data)}}Be.create=r=>new Be({typeName:k.ZodAny,...P(r)});class Le extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return q(e.data)}}Le.create=r=>new Le({typeName:k.ZodUnknown,...P(r)});class ve extends x{_parse(e){const t=this._getOrReturnCtx(e);return g(t,{code:h.invalid_type,expected:v.never,received:t.parsedType}),E}}ve.create=r=>new ve({typeName:k.ZodNever,...P(r)});class jt extends x{_parse(e){if(this._getType(e)!==v.undefined){const n=this._getOrReturnCtx(e);return g(n,{code:h.invalid_type,expected:v.void,received:n.parsedType}),E}return q(e.data)}}jt.create=r=>new jt({typeName:k.ZodVoid,...P(r)});class ee extends x{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),o=this._def;if(t.parsedType!==v.array)return g(t,{code:h.invalid_type,expected:v.array,received:t.parsedType}),E;if(o.exactLength!==null){const i=t.data.length>o.exactLength.value,c=t.data.length<o.exactLength.value;(i||c)&&(g(t,{code:i?h.too_big:h.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}),n.dirty())}if(o.minLength!==null&&t.data.length<o.minLength.value&&(g(t,{code:h.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&t.data.length>o.maxLength.value&&(g(t,{code:h.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((i,c)=>o.type._parseAsync(new ie(t,i,t.path,c)))).then(i=>z.mergeArray(n,i));const s=[...t.data].map((i,c)=>o.type._parseSync(new ie(t,i,t.path,c)));return z.mergeArray(n,s)}get element(){return this._def.type}min(e,t){return new ee({...this._def,minLength:{value:e,message:b.toString(t)}})}max(e,t){return new ee({...this._def,maxLength:{value:e,message:b.toString(t)}})}length(e,t){return new ee({...this._def,exactLength:{value:e,message:b.toString(t)}})}nonempty(e){return this.min(1,e)}}ee.create=(r,e)=>new ee({type:r,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...P(e)});function qe(r){if(r instanceof N){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=le.create(qe(n))}return new N({...r._def,shape:()=>e})}else return r instanceof ee?new ee({...r._def,type:qe(r.element)}):r instanceof le?le.create(qe(r.unwrap())):r instanceof Ie?Ie.create(qe(r.unwrap())):r instanceof ce?ce.create(r.items.map(e=>qe(e))):r}class N extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=R.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==v.object){const u=this._getOrReturnCtx(e);return g(u,{code:h.invalid_type,expected:v.object,received:u.parsedType}),E}const{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof ve&&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 ie(o,f,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof ve){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:h.unrecognized_keys,keys:c}),n.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 ie(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,_=await d.value;u.push({key:f,value:_,alwaysSet:d.alwaysSet})}return u}).then(u=>z.mergeObjectSync(n,u)):z.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return b.errToObj,new N({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var o,s,i,c;const l=(i=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,t,n).message)!==null&&i!==void 0?i:n.defaultError;return t.code==="unrecognized_keys"?{message:(c=b.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new N({...this._def,unknownKeys:"strip"})}passthrough(){return new N({...this._def,unknownKeys:"passthrough"})}extend(e){return new N({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new N({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:k.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new N({...this._def,catchall:e})}pick(e){const t={};return R.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new N({...this._def,shape:()=>t})}omit(e){const t={};return R.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new N({...this._def,shape:()=>t})}deepPartial(){return qe(this)}partial(e){const t={};return R.objectKeys(this.shape).forEach(n=>{const o=this.shape[n];e&&!e[n]?t[n]=o:t[n]=o.optional()}),new N({...this._def,shape:()=>t})}required(e){const t={};return R.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof le;)s=s._def.innerType;t[n]=s}}),new N({...this._def,shape:()=>t})}keyof(){return Vr(R.objectKeys(this.shape))}}N.create=(r,e)=>new N({shape:()=>r,unknownKeys:"strip",catchall:ve.create(),typeName:k.ZodObject,...P(e)}),N.strictCreate=(r,e)=>new N({shape:()=>r,unknownKeys:"strict",catchall:ve.create(),typeName:k.ZodObject,...P(e)}),N.lazycreate=(r,e)=>new N({shape:r,unknownKeys:"strip",catchall:ve.create(),typeName:k.ZodObject,...P(e)});class ft extends x{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;const i=s.map(c=>new J(c.ctx.common.issues));return g(t,{code:h.invalid_union,unionErrors:i}),E}if(t.common.async)return Promise.all(n.map(async s=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(o);{let s;const i=[];for(const l of n){const u={...t,common:{...t.common,issues:[]},parent:null},d=l._parseSync({data:t.data,path:t.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;const c=i.map(l=>new J(l));return g(t,{code:h.invalid_union,unionErrors:c}),E}}get options(){return this._def.options}}ft.create=(r,e)=>new ft({options:r,typeName:k.ZodUnion,...P(e)});const we=r=>r instanceof yt?we(r.schema):r instanceof te?we(r.innerType()):r instanceof _t?[r.value]:r instanceof Te?r.options:r instanceof gt?R.objectValues(r.enum):r instanceof vt?we(r._def.innerType):r instanceof dt?[void 0]:r instanceof pt?[null]:r instanceof le?[void 0,...we(r.unwrap())]:r instanceof Ie?[null,...we(r.unwrap())]:r instanceof pr||r instanceof kt?we(r.unwrap()):r instanceof wt?we(r._def.innerType):[];class Lt extends x{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.object)return g(t,{code:h.invalid_type,expected:v.object,received:t.parsedType}),E;const n=this.discriminator,o=t.data[n],s=this.optionsMap.get(o);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(g(t,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),E)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const o=new Map;for(const s of t){const i=we(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 Lt({typeName:k.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...P(n)})}}function dr(r,e){const t=Pe(r),n=Pe(e);if(r===e)return{valid:!0,data:r};if(t===v.object&&n===v.object){const o=R.objectKeys(e),s=R.objectKeys(r).filter(c=>o.indexOf(c)!==-1),i={...r,...e};for(const c of s){const l=dr(r[c],e[c]);if(!l.valid)return{valid:!1};i[c]=l.data}return{valid:!0,data:i}}else if(t===v.array&&n===v.array){if(r.length!==e.length)return{valid:!1};const o=[];for(let s=0;s<r.length;s++){const i=r[s],c=e[s],l=dr(i,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return t===v.date&&n===v.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class ht extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(cr(s)||cr(i))return E;const c=dr(s.value,i.value);return c.valid?((lr(s)||lr(i))&&t.dirty(),{status:t.value,value:c.data}):(g(n,{code:h.invalid_intersection_types}),E)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}ht.create=(r,e,t)=>new ht({left:r,right:e,typeName:k.ZodIntersection,...P(t)});class ce extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.array)return g(n,{code:h.invalid_type,expected:v.array,received:n.parsedType}),E;if(n.data.length<this._def.items.length)return g(n,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),E;!this._def.rest&&n.data.length>this._def.items.length&&(g(n,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...n.data].map((i,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new ie(n,i,n.path,c)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>z.mergeArray(t,i)):z.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new ce({...this._def,rest:e})}}ce.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ce({items:r,typeName:k.ZodTuple,rest:null,...P(e)})};class mt extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.object)return g(n,{code:h.invalid_type,expected:v.object,received:n.parsedType}),E;const o=[],s=this._def.keyType,i=this._def.valueType;for(const c in n.data)o.push({key:s._parse(new ie(n,c,n.path,c)),value:i._parse(new ie(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?z.mergeObjectAsync(t,o):z.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof x?new mt({keyType:e,valueType:t,typeName:k.ZodRecord,...P(n)}):new mt({keyType:X.create(),valueType:e,typeName:k.ZodRecord,...P(t)})}}class Ft extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.map)return g(n,{code:h.invalid_type,expected:v.map,received:n.parsedType}),E;const o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([c,l],u)=>({key:o._parse(new ie(n,c,n.path,[u,"key"])),value:s._parse(new ie(n,l,n.path,[u,"value"]))}));if(n.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 E;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(u.value,d.value)}return{status:t.value,value:c}})}else{const c=new Map;for(const l of i){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return E;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(u.value,d.value)}return{status:t.value,value:c}}}}Ft.create=(r,e,t)=>new Ft({valueType:e,keyType:r,typeName:k.ZodMap,...P(t)});class Fe extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.set)return g(n,{code:h.invalid_type,expected:v.set,received:n.parsedType}),E;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(g(n,{code:h.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(g(n,{code:h.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty());const s=this._def.valueType;function i(l){const u=new Set;for(const d of l){if(d.status==="aborted")return E;d.status==="dirty"&&t.dirty(),u.add(d.value)}return{status:t.value,value:u}}const c=[...n.data.values()].map((l,u)=>s._parse(new ie(n,l,n.path,u)));return n.common.async?Promise.all(c).then(l=>i(l)):i(c)}min(e,t){return new Fe({...this._def,minSize:{value:e,message:b.toString(t)}})}max(e,t){return new Fe({...this._def,maxSize:{value:e,message:b.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Fe.create=(r,e)=>new Fe({valueType:r,minSize:null,maxSize:null,typeName:k.ZodSet,...P(e)});class Ye extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.function)return g(t,{code:h.invalid_type,expected:v.function,received:t.parsedType}),E;function n(c,l){return Nt({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ot(),ze].filter(u=>!!u),issueData:{code:h.invalid_arguments,argumentsError:l}})}function o(c,l){return Nt({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ot(),ze].filter(u=>!!u),issueData:{code:h.invalid_return_type,returnTypeError:l}})}const s={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof We){const c=this;return q(async function(...l){const u=new J([]),d=await c._def.args.parseAsync(l,s).catch(p=>{throw u.addIssue(n(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 J([n(l,u.error)]);const d=Reflect.apply(i,this,u.data),f=c._def.returns.safeParse(d,s);if(!f.success)throw new J([o(d,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ye({...this._def,args:ce.create(e).rest(Le.create())})}returns(e){return new Ye({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new Ye({args:e||ce.create([]).rest(Le.create()),returns:t||Le.create(),typeName:k.ZodFunction,...P(n)})}}class yt extends x{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}yt.create=(r,e)=>new yt({getter:r,typeName:k.ZodLazy,...P(e)});class _t extends x{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return g(t,{received:t.data,code:h.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:e.data}}get value(){return this._def.value}}_t.create=(r,e)=>new _t({value:r,typeName:k.ZodLiteral,...P(e)});function Vr(r,e){return new Te({values:r,typeName:k.ZodEnum,...P(e)})}class Te extends x{constructor(){super(...arguments),ct.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return g(t,{expected:R.joinValues(n),received:t.parsedType,code:h.invalid_type}),E}if(Mt(this,ct)||Lr(this,ct,new Set(this._def.values)),!Mt(this,ct).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return g(t,{received:t.data,code:h.invalid_enum_value,options:n}),E}return q(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Te.create(e,{...this._def,...t})}exclude(e,t=this._def){return Te.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}ct=new WeakMap,Te.create=Vr;class gt extends x{constructor(){super(...arguments),lt.set(this,void 0)}_parse(e){const t=R.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==v.string&&n.parsedType!==v.number){const o=R.objectValues(t);return g(n,{expected:R.joinValues(o),received:n.parsedType,code:h.invalid_type}),E}if(Mt(this,lt)||Lr(this,lt,new Set(R.getValidEnumValues(this._def.values))),!Mt(this,lt).has(e.data)){const o=R.objectValues(t);return g(n,{received:n.data,code:h.invalid_enum_value,options:o}),E}return q(e.data)}get enum(){return this._def.values}}lt=new WeakMap,gt.create=(r,e)=>new gt({values:r,typeName:k.ZodNativeEnum,...P(e)});class We extends x{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.promise&&t.common.async===!1)return g(t,{code:h.invalid_type,expected:v.promise,received:t.parsedType}),E;const n=t.parsedType===v.promise?t.data:Promise.resolve(t.data);return q(n.then(o=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}We.create=(r,e)=>new We({type:r,typeName:k.ZodPromise,...P(e)});class te extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===k.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{g(n,i),i.fatal?t.abort():t.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async c=>{if(t.value==="aborted")return E;const l=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return l.status==="aborted"?E:l.status==="dirty"||t.value==="dirty"?Ge(l.value):l});{if(t.value==="aborted")return E;const c=this._def.schema._parseSync({data:i,path:n.path,parent:n});return c.status==="aborted"?E:c.status==="dirty"||t.value==="dirty"?Ge(c.value):c}}if(o.type==="refinement"){const i=c=>{const l=o.refinement(c,s);if(n.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(n.common.async===!1){const c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?E:(c.status==="dirty"&&t.dirty(),i(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?E:(c.status==="dirty"&&t.dirty(),i(c.value).then(()=>({status:t.value,value:c.value}))))}if(o.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!at(i))return i;const c=o.transform(i.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>at(i)?Promise.resolve(o.transform(i.value,s)).then(c=>({status:t.value,value:c})):i);R.assertNever(o)}}te.create=(r,e,t)=>new te({schema:r,typeName:k.ZodEffects,effect:e,...P(t)}),te.createWithPreprocess=(r,e,t)=>new te({schema:e,effect:{type:"preprocess",transform:r},typeName:k.ZodEffects,...P(t)});class le extends x{_parse(e){return this._getType(e)===v.undefined?q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}le.create=(r,e)=>new le({innerType:r,typeName:k.ZodOptional,...P(e)});class Ie extends x{_parse(e){return this._getType(e)===v.null?q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(r,e)=>new Ie({innerType:r,typeName:k.ZodNullable,...P(e)});class vt extends x{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===v.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}vt.create=(r,e)=>new vt({innerType:r,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...P(e)});class wt extends x{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return it(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new J(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new J(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}wt.create=(r,e)=>new wt({innerType:r,typeName:k.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...P(e)});class Ut extends x{_parse(e){if(this._getType(e)!==v.nan){const n=this._getOrReturnCtx(e);return g(n,{code:h.invalid_type,expected:v.nan,received:n.parsedType}),E}return{status:"valid",value:e.data}}}Ut.create=r=>new Ut({typeName:k.ZodNaN,...P(r)});const No=Symbol("zod_brand");class pr extends x{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class bt extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?E:s.status==="dirty"?(t.dirty(),Ge(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?E:o.status==="dirty"?(t.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,t){return new bt({in:e,out:t,typeName:k.ZodPipeline})}}class kt extends x{_parse(e){const t=this._def.innerType._parse(e),n=o=>(at(o)&&(o.value=Object.freeze(o.value)),o);return it(t)?t.then(o=>n(o)):n(t)}unwrap(){return this._def.innerType}}kt.create=(r,e)=>new kt({innerType:r,typeName:k.ZodReadonly,...P(e)});function zr(r,e={},t){return r?Be.create().superRefine((n,o)=>{var s,i;if(!r(n)){const c=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,l=(i=(s=c.fatal)!==null&&s!==void 0?s:t)!==null&&i!==void 0?i:!0,u=typeof c=="string"?{message:c}:c;o.addIssue({code:"custom",...u,fatal:l})}}):Be.create()}const Mo={object:N.lazycreate};var k;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(k||(k={}));const Do=(r,e={message:`Input not instance of ${r.name}`})=>zr(t=>t instanceof r,e),Gr=X.create,Br=Ae.create,jo=Ut.create,Lo=xe.create,qr=ut.create,Fo=je.create,Uo=Dt.create,$o=dt.create,Zo=pt.create,Vo=Be.create,zo=Le.create,Go=ve.create,Bo=jt.create,qo=ee.create,Yo=N.create,Wo=N.strictCreate,Ko=ft.create,Ho=Lt.create,Jo=ht.create,Qo=ce.create,Xo=mt.create,es=Ft.create,ts=Fe.create,rs=Ye.create,ns=yt.create,os=_t.create,ss=Te.create,as=gt.create,is=We.create,Yr=te.create,cs=le.create,ls=Ie.create,us=te.createWithPreprocess,ds=bt.create;var a=Object.freeze({__proto__:null,defaultErrorMap:ze,setErrorMap:yo,getErrorMap:Ot,makeIssue:Nt,EMPTY_PATH:_o,addIssueToContext:g,ParseStatus:z,INVALID:E,DIRTY:Ge,OK:q,isAborted:cr,isDirty:lr,isValid:at,isAsync:it,get util(){return R},get objectUtil(){return ir},ZodParsedType:v,getParsedType:Pe,ZodType:x,datetimeRegex:Zr,ZodString:X,ZodNumber:Ae,ZodBigInt:xe,ZodBoolean:ut,ZodDate:je,ZodSymbol:Dt,ZodUndefined:dt,ZodNull:pt,ZodAny:Be,ZodUnknown:Le,ZodNever:ve,ZodVoid:jt,ZodArray:ee,ZodObject:N,ZodUnion:ft,ZodDiscriminatedUnion:Lt,ZodIntersection:ht,ZodTuple:ce,ZodRecord:mt,ZodMap:Ft,ZodSet:Fe,ZodFunction:Ye,ZodLazy:yt,ZodLiteral:_t,ZodEnum:Te,ZodNativeEnum:gt,ZodPromise:We,ZodEffects:te,ZodTransformer:te,ZodOptional:le,ZodNullable:Ie,ZodDefault:vt,ZodCatch:wt,ZodNaN:Ut,BRAND:No,ZodBranded:pr,ZodPipeline:bt,ZodReadonly:kt,custom:zr,Schema:x,ZodSchema:x,late:Mo,get ZodFirstPartyTypeKind(){return k},coerce:{string:r=>X.create({...r,coerce:!0}),number:r=>Ae.create({...r,coerce:!0}),boolean:r=>ut.create({...r,coerce:!0}),bigint:r=>xe.create({...r,coerce:!0}),date:r=>je.create({...r,coerce:!0})},any:Vo,array:qo,bigint:Lo,boolean:qr,date:Fo,discriminatedUnion:Ho,effect:Yr,enum:ss,function:rs,instanceof:Do,intersection:Jo,lazy:ns,literal:os,map:es,nan:jo,nativeEnum:as,never:Go,null:Zo,nullable:ls,number:Br,object:Yo,oboolean:()=>qr().optional(),onumber:()=>Br().optional(),optional:cs,ostring:()=>Gr().optional(),pipeline:ds,preprocess:us,promise:is,record:Xo,set:ts,strictObject:Wo,string:Gr,symbol:Uo,transformer:Yr,tuple:Qo,undefined:$o,union:Ko,unknown:zo,void:Bo,NEVER:E,ZodIssueCode:h,quotelessJson:mo,ZodError:J});const ps=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()}),fs=a.array(ps),hs=a.object({code:a.string(),message:a.string(),path:a.array(a.string())}),ms=a.array(hs),ys={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},fr=r=>{const e=r.toLowerCase().trim();return ys[e]??r},_s=r=>{try{return typeof JSON.parse(r)=="object"}catch{return!1}},gs=r=>r.length===1?fr(r[0].msg):`Please fix the following errors:
2
- ${r.map(t=>`• ${fr(t.msg)}`).join(`
3
- `)}`,vs=r=>`Encountered the following errors:
1
+ (function(we,je){typeof exports=="object"&&typeof module<"u"?je(exports):typeof define=="function"&&define.amd?define(["exports"],je):(we=typeof globalThis<"u"?globalThis:we||self,je(we.OpenPay={}))})(this,function(we){"use strict";const je="https://cde.getopenpay.com";var R;(function(r){r.assertEqual=o=>o;function e(o){}r.assertIs=e;function t(o){throw new Error}r.assertNever=t,r.arrayToEnum=o=>{const s={};for(const i of o)s[i]=i;return s},r.getValidEnumValues=o=>{const s=r.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),i={};for(const c of s)i[c]=o[c];return r.objectValues(i)},r.objectValues=o=>r.objectKeys(o).map(function(s){return o[s]}),r.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},r.find=(o,s)=>{for(const i of o)if(s(i))return i},r.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}r.joinValues=n,r.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(R||(R={}));var dr;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(dr||(dr={}));const v=R.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xe=r=>{switch(typeof r){case"undefined":return v.undefined;case"string":return v.string;case"number":return isNaN(r)?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(r)?v.array:r===null?v.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?v.promise:typeof Map<"u"&&r instanceof Map?v.map:typeof Set<"u"&&r instanceof Set?v.set:typeof Date<"u"&&r instanceof Date?v.date:v.object;default:return v.unknown}},m=R.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"]),bo=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class X extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(s){return s.message},n={_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)n._errors.push(t(i));else{let c=n,l=0;for(;l<i.path.length;){const u=i.path[l];l===i.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(i))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};return o(this),n}static assert(e){if(!(e instanceof X))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,R.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const o of this.issues)o.path.length>0?(t[o.path[0]]=t[o.path[0]]||[],t[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}X.create=r=>new X(r);const qe=(r,e)=>{let t;switch(r.code){case m.invalid_type:r.received===v.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case m.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,R.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:t=`Unrecognized key(s) in object: ${R.joinValues(r.keys,", ")}`;break;case m.invalid_union:t="Invalid input";break;case m.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${R.joinValues(r.options)}`;break;case m.invalid_enum_value:t=`Invalid enum value. Expected ${R.joinValues(r.options)}, received '${r.received}'`;break;case m.invalid_arguments:t="Invalid function arguments";break;case m.invalid_return_type:t="Invalid function return type";break;case m.invalid_date:t="Invalid date";break;case m.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:R.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case m.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case m.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case m.custom:t="Invalid input";break;case m.invalid_intersection_types:t="Intersection results could not be merged";break;case m.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case m.not_finite:t="Number must be finite";break;default:t=e.defaultError,R.assertNever(r)}return{message:t}};let Zr=qe;function ko(r){Zr=r}function jt(){return Zr}const Lt=r=>{const{data:e,path:t,errorMaps:n,issueData:o}=r,s=[...t,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=n.filter(u=>!!u).slice().reverse();for(const u of l)c=u(i,{data:e,defaultError:c}).message;return{...o,path:s,message:c}},Eo=[];function g(r,e){const t=jt(),n=Lt({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===qe?void 0:qe].filter(o=>!!o)});r.common.issues.push(n)}class q{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const o of t){if(o.status==="aborted")return E;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const o of t){const s=await o.key,i=await o.value;n.push({key:s,value:i})}return q.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const o of t){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return E;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}}const E=Object.freeze({status:"aborted"}),Ye=r=>({status:"dirty",value:r}),W=r=>({status:"valid",value:r}),pr=r=>r.status==="aborted",fr=r=>r.status==="dirty",ct=r=>r.status==="valid",lt=r=>typeof Promise<"u"&&r instanceof Promise;function Ft(r,e,t,n){if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function Vr(r,e,t,n,o){if(typeof e=="function"?r!==e||!o:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}typeof SuppressedError=="function"&&SuppressedError;var b;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(b||(b={}));var ut,dt;class ue{constructor(e,t,n,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,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 zr=(r,e)=>{if(ct(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new X(r.common.issues);return this._error=t,this._error}}};function P(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:o}=r;if(e&&(t||n))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}=r;return i.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(l=d??n)!==null&&l!==void 0?l:c.defaultError}:i.code!=="invalid_type"?{message:c.defaultError}:{message:(u=d??t)!==null&&u!==void 0?u:c.defaultError}},description:o}}class I{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return xe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new q,ctx:{common:e.parent.common,data:e.data,parsedType:xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(lt(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;const o={common:{issues:[],async:(n=t==null?void 0:t.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xe(e)},s=this._parseSync({data:e,path:o.path,parent:o});return zr(o,s)}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xe(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(lt(o)?o:Promise.resolve(o));return zr(n,s)}refine(e,t){const n=o=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(o):t;return this._refinement((o,s)=>{const i=e(o),c=()=>s.addIssue({code:m.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(c(),!1)):i?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof t=="function"?t(n,o):t),!1))}_refinement(e){return new ne({schema:this,typeName:k.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return pe.create(this,this._def)}nullable(){return Oe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return re.create(this,this._def)}promise(){return Je.create(this,this._def)}or(e){return mt.create([this,e],this._def)}and(e){return yt.create(this,e,this._def)}transform(e){return new ne({...P(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new bt({...P(this._def),innerType:this,defaultValue:t,typeName:k.ZodDefault})}brand(){return new yr({typeName:k.ZodBranded,type:this,...P(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new kt({...P(this._def),innerType:this,catchValue:t,typeName:k.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Et.create(this,e)}readonly(){return Ct.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Co=/^c[^\s-]{8,}$/i,So=/^[0-9a-z]+$/,Po=/^[0-9A-HJKMNP-TV-Z]{26}$/,Ao=/^[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,xo=/^[a-z0-9_-]{21}$/i,Io=/^[-+]?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)?)??$/,To=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ro="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let hr;const Oo=/^(?:(?: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])$/,No=/^(([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})))$/,Mo=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gr="((\\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])))",Do=new RegExp(`^${Gr}$`);function Br(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function jo(r){return new RegExp(`^${Br(r)}$`)}function qr(r){let e=`${Gr}T${Br(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Lo(r,e){return!!((e==="v4"||!e)&&Oo.test(r)||(e==="v6"||!e)&&No.test(r))}class te extends I{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==v.string){const s=this._getOrReturnCtx(e);return g(s,{code:m.invalid_type,expected:v.string,received:s.parsedType}),E}const n=new q;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:m.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:m.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.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:m.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&g(o,{code:m.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")To.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"email",code:m.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")hr||(hr=new RegExp(Ro,"u")),hr.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"emoji",code:m.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Ao.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"uuid",code:m.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")xo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"nanoid",code:m.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Co.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid",code:m.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")So.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid2",code:m.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Po.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ulid",code:m.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),g(o,{validation:"url",code:m.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"regex",code:m.invalid_string,message:s.message}),n.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:m.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.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:m.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:m.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?qr(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:m.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Do.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:m.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?jo(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:m.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Io.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"duration",code:m.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Lo(e.data,s.version)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ip",code:m.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Mo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"base64",code:m.invalid_string,message:s.message}),n.dirty()):R.assertNever(s);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(o=>e.test(o),{validation:t,code:m.invalid_string,...b.errToObj(n)})}_addCheck(e){return new te({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...b.errToObj(e)})}url(e){return this._addCheck({kind:"url",...b.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...b.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...b.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...b.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...b.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...b.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...b.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...b.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...b.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...b.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...b.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...b.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...b.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...b.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...b.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...b.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...b.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...b.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...b.errToObj(t)})}nonempty(e){return this.min(1,b.errToObj(e))}trim(){return new te({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new te({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new te({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}te.create=r=>{var e;return new te({checks:[],typeName:k.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...P(r)})};function Fo(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=t>n?t:n,s=parseInt(r.toFixed(o).replace(".","")),i=parseInt(e.toFixed(o).replace(".",""));return s%i/Math.pow(10,o)}class Ie extends I{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==v.number){const s=this._getOrReturnCtx(e);return g(s,{code:m.invalid_type,expected:v.number,received:s.parsedType}),E}let n;const o=new q;for(const s of this._def.checks)s.kind==="int"?R.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:m.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:m.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)&&(n=this._getOrReturnCtx(e,n),g(n,{code:m.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Fo(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),g(n,{code:m.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:m.not_finite,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,n,o){return new Ie({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:b.toString(o)}]})}_addCheck(e){return new Ie({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:b.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:b.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&R.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Ie.create=r=>new Ie({checks:[],typeName:k.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...P(r)});class Te extends I{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==v.bigint){const s=this._getOrReturnCtx(e);return g(s,{code:m.invalid_type,expected:v.bigint,received:s.parsedType}),E}let n;const o=new q;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:m.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)&&(n=this._getOrReturnCtx(e,n),g(n,{code:m.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),g(n,{code:m.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,n,o){return new Te({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:b.toString(o)}]})}_addCheck(e){return new Te({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Te.create=r=>{var e;return new Te({checks:[],typeName:k.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...P(r)})};class pt extends I{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==v.boolean){const n=this._getOrReturnCtx(e);return g(n,{code:m.invalid_type,expected:v.boolean,received:n.parsedType}),E}return W(e.data)}}pt.create=r=>new pt({typeName:k.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...P(r)});class Le extends I{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==v.date){const s=this._getOrReturnCtx(e);return g(s,{code:m.invalid_type,expected:v.date,received:s.parsedType}),E}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return g(s,{code:m.invalid_date}),E}const n=new q;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:m.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:m.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):R.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Le({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:b.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:b.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Le.create=r=>new Le({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:k.ZodDate,...P(r)});class Ut extends I{_parse(e){if(this._getType(e)!==v.symbol){const n=this._getOrReturnCtx(e);return g(n,{code:m.invalid_type,expected:v.symbol,received:n.parsedType}),E}return W(e.data)}}Ut.create=r=>new Ut({typeName:k.ZodSymbol,...P(r)});class ft extends I{_parse(e){if(this._getType(e)!==v.undefined){const n=this._getOrReturnCtx(e);return g(n,{code:m.invalid_type,expected:v.undefined,received:n.parsedType}),E}return W(e.data)}}ft.create=r=>new ft({typeName:k.ZodUndefined,...P(r)});class ht extends I{_parse(e){if(this._getType(e)!==v.null){const n=this._getOrReturnCtx(e);return g(n,{code:m.invalid_type,expected:v.null,received:n.parsedType}),E}return W(e.data)}}ht.create=r=>new ht({typeName:k.ZodNull,...P(r)});class We extends I{constructor(){super(...arguments),this._any=!0}_parse(e){return W(e.data)}}We.create=r=>new We({typeName:k.ZodAny,...P(r)});class Fe extends I{constructor(){super(...arguments),this._unknown=!0}_parse(e){return W(e.data)}}Fe.create=r=>new Fe({typeName:k.ZodUnknown,...P(r)});class be extends I{_parse(e){const t=this._getOrReturnCtx(e);return g(t,{code:m.invalid_type,expected:v.never,received:t.parsedType}),E}}be.create=r=>new be({typeName:k.ZodNever,...P(r)});class $t extends I{_parse(e){if(this._getType(e)!==v.undefined){const n=this._getOrReturnCtx(e);return g(n,{code:m.invalid_type,expected:v.void,received:n.parsedType}),E}return W(e.data)}}$t.create=r=>new $t({typeName:k.ZodVoid,...P(r)});class re extends I{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),o=this._def;if(t.parsedType!==v.array)return g(t,{code:m.invalid_type,expected:v.array,received:t.parsedType}),E;if(o.exactLength!==null){const i=t.data.length>o.exactLength.value,c=t.data.length<o.exactLength.value;(i||c)&&(g(t,{code:i?m.too_big:m.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}),n.dirty())}if(o.minLength!==null&&t.data.length<o.minLength.value&&(g(t,{code:m.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&t.data.length>o.maxLength.value&&(g(t,{code:m.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((i,c)=>o.type._parseAsync(new ue(t,i,t.path,c)))).then(i=>q.mergeArray(n,i));const s=[...t.data].map((i,c)=>o.type._parseSync(new ue(t,i,t.path,c)));return q.mergeArray(n,s)}get element(){return this._def.type}min(e,t){return new re({...this._def,minLength:{value:e,message:b.toString(t)}})}max(e,t){return new re({...this._def,maxLength:{value:e,message:b.toString(t)}})}length(e,t){return new re({...this._def,exactLength:{value:e,message:b.toString(t)}})}nonempty(e){return this.min(1,e)}}re.create=(r,e)=>new re({type:r,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...P(e)});function Ke(r){if(r instanceof M){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=pe.create(Ke(n))}return new M({...r._def,shape:()=>e})}else return r instanceof re?new re({...r._def,type:Ke(r.element)}):r instanceof pe?pe.create(Ke(r.unwrap())):r instanceof Oe?Oe.create(Ke(r.unwrap())):r instanceof de?de.create(r.items.map(e=>Ke(e))):r}class M extends I{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=R.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==v.object){const u=this._getOrReturnCtx(e);return g(u,{code:m.invalid_type,expected:v.object,received:u.parsedType}),E}const{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof be&&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 ue(o,p,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof be){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:m.unrecognized_keys,keys:c}),n.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 ue(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,_=await d.value;u.push({key:p,value:_,alwaysSet:d.alwaysSet})}return u}).then(u=>q.mergeObjectSync(n,u)):q.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return b.errToObj,new M({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var o,s,i,c;const l=(i=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,t,n).message)!==null&&i!==void 0?i:n.defaultError;return t.code==="unrecognized_keys"?{message:(c=b.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new M({...this._def,unknownKeys:"strip"})}passthrough(){return new M({...this._def,unknownKeys:"passthrough"})}extend(e){return new M({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new M({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:k.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new M({...this._def,catchall:e})}pick(e){const t={};return R.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new M({...this._def,shape:()=>t})}omit(e){const t={};return R.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new M({...this._def,shape:()=>t})}deepPartial(){return Ke(this)}partial(e){const t={};return R.objectKeys(this.shape).forEach(n=>{const o=this.shape[n];e&&!e[n]?t[n]=o:t[n]=o.optional()}),new M({...this._def,shape:()=>t})}required(e){const t={};return R.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof pe;)s=s._def.innerType;t[n]=s}}),new M({...this._def,shape:()=>t})}keyof(){return Yr(R.objectKeys(this.shape))}}M.create=(r,e)=>new M({shape:()=>r,unknownKeys:"strip",catchall:be.create(),typeName:k.ZodObject,...P(e)}),M.strictCreate=(r,e)=>new M({shape:()=>r,unknownKeys:"strict",catchall:be.create(),typeName:k.ZodObject,...P(e)}),M.lazycreate=(r,e)=>new M({shape:r,unknownKeys:"strip",catchall:be.create(),typeName:k.ZodObject,...P(e)});class mt extends I{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;const i=s.map(c=>new X(c.ctx.common.issues));return g(t,{code:m.invalid_union,unionErrors:i}),E}if(t.common.async)return Promise.all(n.map(async s=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(o);{let s;const i=[];for(const l of n){const u={...t,common:{...t.common,issues:[]},parent:null},d=l._parseSync({data:t.data,path:t.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;const c=i.map(l=>new X(l));return g(t,{code:m.invalid_union,unionErrors:c}),E}}get options(){return this._def.options}}mt.create=(r,e)=>new mt({options:r,typeName:k.ZodUnion,...P(e)});const ke=r=>r instanceof gt?ke(r.schema):r instanceof ne?ke(r.innerType()):r instanceof vt?[r.value]:r instanceof Re?r.options:r instanceof wt?R.objectValues(r.enum):r instanceof bt?ke(r._def.innerType):r instanceof ft?[void 0]:r instanceof ht?[null]:r instanceof pe?[void 0,...ke(r.unwrap())]:r instanceof Oe?[null,...ke(r.unwrap())]:r instanceof yr||r instanceof Ct?ke(r.unwrap()):r instanceof kt?ke(r._def.innerType):[];class Zt extends I{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.object)return g(t,{code:m.invalid_type,expected:v.object,received:t.parsedType}),E;const n=this.discriminator,o=t.data[n],s=this.optionsMap.get(o);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(g(t,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),E)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const o=new Map;for(const s of t){const i=ke(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 Zt({typeName:k.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...P(n)})}}function mr(r,e){const t=xe(r),n=xe(e);if(r===e)return{valid:!0,data:r};if(t===v.object&&n===v.object){const o=R.objectKeys(e),s=R.objectKeys(r).filter(c=>o.indexOf(c)!==-1),i={...r,...e};for(const c of s){const l=mr(r[c],e[c]);if(!l.valid)return{valid:!1};i[c]=l.data}return{valid:!0,data:i}}else if(t===v.array&&n===v.array){if(r.length!==e.length)return{valid:!1};const o=[];for(let s=0;s<r.length;s++){const i=r[s],c=e[s],l=mr(i,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return t===v.date&&n===v.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class yt extends I{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(pr(s)||pr(i))return E;const c=mr(s.value,i.value);return c.valid?((fr(s)||fr(i))&&t.dirty(),{status:t.value,value:c.data}):(g(n,{code:m.invalid_intersection_types}),E)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}yt.create=(r,e,t)=>new yt({left:r,right:e,typeName:k.ZodIntersection,...P(t)});class de extends I{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.array)return g(n,{code:m.invalid_type,expected:v.array,received:n.parsedType}),E;if(n.data.length<this._def.items.length)return g(n,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),E;!this._def.rest&&n.data.length>this._def.items.length&&(g(n,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...n.data].map((i,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new ue(n,i,n.path,c)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>q.mergeArray(t,i)):q.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new de({...this._def,rest:e})}}de.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new de({items:r,typeName:k.ZodTuple,rest:null,...P(e)})};class _t extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.object)return g(n,{code:m.invalid_type,expected:v.object,received:n.parsedType}),E;const o=[],s=this._def.keyType,i=this._def.valueType;for(const c in n.data)o.push({key:s._parse(new ue(n,c,n.path,c)),value:i._parse(new ue(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?q.mergeObjectAsync(t,o):q.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof I?new _t({keyType:e,valueType:t,typeName:k.ZodRecord,...P(n)}):new _t({keyType:te.create(),valueType:e,typeName:k.ZodRecord,...P(t)})}}class Vt extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.map)return g(n,{code:m.invalid_type,expected:v.map,received:n.parsedType}),E;const o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([c,l],u)=>({key:o._parse(new ue(n,c,n.path,[u,"key"])),value:s._parse(new ue(n,l,n.path,[u,"value"]))}));if(n.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 E;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(u.value,d.value)}return{status:t.value,value:c}})}else{const c=new Map;for(const l of i){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return E;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(u.value,d.value)}return{status:t.value,value:c}}}}Vt.create=(r,e,t)=>new Vt({valueType:e,keyType:r,typeName:k.ZodMap,...P(t)});class Ue extends I{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.set)return g(n,{code:m.invalid_type,expected:v.set,received:n.parsedType}),E;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(g(n,{code:m.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(g(n,{code:m.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty());const s=this._def.valueType;function i(l){const u=new Set;for(const d of l){if(d.status==="aborted")return E;d.status==="dirty"&&t.dirty(),u.add(d.value)}return{status:t.value,value:u}}const c=[...n.data.values()].map((l,u)=>s._parse(new ue(n,l,n.path,u)));return n.common.async?Promise.all(c).then(l=>i(l)):i(c)}min(e,t){return new Ue({...this._def,minSize:{value:e,message:b.toString(t)}})}max(e,t){return new Ue({...this._def,maxSize:{value:e,message:b.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ue.create=(r,e)=>new Ue({valueType:r,minSize:null,maxSize:null,typeName:k.ZodSet,...P(e)});class He extends I{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.function)return g(t,{code:m.invalid_type,expected:v.function,received:t.parsedType}),E;function n(c,l){return Lt({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,jt(),qe].filter(u=>!!u),issueData:{code:m.invalid_arguments,argumentsError:l}})}function o(c,l){return Lt({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,jt(),qe].filter(u=>!!u),issueData:{code:m.invalid_return_type,returnTypeError:l}})}const s={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Je){const c=this;return W(async function(...l){const u=new X([]),d=await c._def.args.parseAsync(l,s).catch(f=>{throw u.addIssue(n(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 W(function(...l){const u=c._def.args.safeParse(l,s);if(!u.success)throw new X([n(l,u.error)]);const d=Reflect.apply(i,this,u.data),p=c._def.returns.safeParse(d,s);if(!p.success)throw new X([o(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new He({...this._def,args:de.create(e).rest(Fe.create())})}returns(e){return new He({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new He({args:e||de.create([]).rest(Fe.create()),returns:t||Fe.create(),typeName:k.ZodFunction,...P(n)})}}class gt extends I{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}gt.create=(r,e)=>new gt({getter:r,typeName:k.ZodLazy,...P(e)});class vt extends I{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return g(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:e.data}}get value(){return this._def.value}}vt.create=(r,e)=>new vt({value:r,typeName:k.ZodLiteral,...P(e)});function Yr(r,e){return new Re({values:r,typeName:k.ZodEnum,...P(e)})}class Re extends I{constructor(){super(...arguments),ut.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return g(t,{expected:R.joinValues(n),received:t.parsedType,code:m.invalid_type}),E}if(Ft(this,ut)||Vr(this,ut,new Set(this._def.values)),!Ft(this,ut).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return g(t,{received:t.data,code:m.invalid_enum_value,options:n}),E}return W(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Re.create(e,{...this._def,...t})}exclude(e,t=this._def){return Re.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}ut=new WeakMap,Re.create=Yr;class wt extends I{constructor(){super(...arguments),dt.set(this,void 0)}_parse(e){const t=R.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==v.string&&n.parsedType!==v.number){const o=R.objectValues(t);return g(n,{expected:R.joinValues(o),received:n.parsedType,code:m.invalid_type}),E}if(Ft(this,dt)||Vr(this,dt,new Set(R.getValidEnumValues(this._def.values))),!Ft(this,dt).has(e.data)){const o=R.objectValues(t);return g(n,{received:n.data,code:m.invalid_enum_value,options:o}),E}return W(e.data)}get enum(){return this._def.values}}dt=new WeakMap,wt.create=(r,e)=>new wt({values:r,typeName:k.ZodNativeEnum,...P(e)});class Je extends I{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.promise&&t.common.async===!1)return g(t,{code:m.invalid_type,expected:v.promise,received:t.parsedType}),E;const n=t.parsedType===v.promise?t.data:Promise.resolve(t.data);return W(n.then(o=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Je.create=(r,e)=>new Je({type:r,typeName:k.ZodPromise,...P(e)});class ne extends I{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===k.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{g(n,i),i.fatal?t.abort():t.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async c=>{if(t.value==="aborted")return E;const l=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return l.status==="aborted"?E:l.status==="dirty"||t.value==="dirty"?Ye(l.value):l});{if(t.value==="aborted")return E;const c=this._def.schema._parseSync({data:i,path:n.path,parent:n});return c.status==="aborted"?E:c.status==="dirty"||t.value==="dirty"?Ye(c.value):c}}if(o.type==="refinement"){const i=c=>{const l=o.refinement(c,s);if(n.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(n.common.async===!1){const c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?E:(c.status==="dirty"&&t.dirty(),i(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?E:(c.status==="dirty"&&t.dirty(),i(c.value).then(()=>({status:t.value,value:c.value}))))}if(o.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ct(i))return i;const c=o.transform(i.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>ct(i)?Promise.resolve(o.transform(i.value,s)).then(c=>({status:t.value,value:c})):i);R.assertNever(o)}}ne.create=(r,e,t)=>new ne({schema:r,typeName:k.ZodEffects,effect:e,...P(t)}),ne.createWithPreprocess=(r,e,t)=>new ne({schema:e,effect:{type:"preprocess",transform:r},typeName:k.ZodEffects,...P(t)});class pe extends I{_parse(e){return this._getType(e)===v.undefined?W(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pe.create=(r,e)=>new pe({innerType:r,typeName:k.ZodOptional,...P(e)});class Oe extends I{_parse(e){return this._getType(e)===v.null?W(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Oe.create=(r,e)=>new Oe({innerType:r,typeName:k.ZodNullable,...P(e)});class bt extends I{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===v.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}bt.create=(r,e)=>new bt({innerType:r,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...P(e)});class kt extends I{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return lt(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new X(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new X(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}kt.create=(r,e)=>new kt({innerType:r,typeName:k.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...P(e)});class zt extends I{_parse(e){if(this._getType(e)!==v.nan){const n=this._getOrReturnCtx(e);return g(n,{code:m.invalid_type,expected:v.nan,received:n.parsedType}),E}return{status:"valid",value:e.data}}}zt.create=r=>new zt({typeName:k.ZodNaN,...P(r)});const Uo=Symbol("zod_brand");class yr extends I{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class Et extends I{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?E:s.status==="dirty"?(t.dirty(),Ye(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?E:o.status==="dirty"?(t.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,t){return new Et({in:e,out:t,typeName:k.ZodPipeline})}}class Ct extends I{_parse(e){const t=this._def.innerType._parse(e),n=o=>(ct(o)&&(o.value=Object.freeze(o.value)),o);return lt(t)?t.then(o=>n(o)):n(t)}unwrap(){return this._def.innerType}}Ct.create=(r,e)=>new Ct({innerType:r,typeName:k.ZodReadonly,...P(e)});function Wr(r,e={},t){return r?We.create().superRefine((n,o)=>{var s,i;if(!r(n)){const c=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,l=(i=(s=c.fatal)!==null&&s!==void 0?s:t)!==null&&i!==void 0?i:!0,u=typeof c=="string"?{message:c}:c;o.addIssue({code:"custom",...u,fatal:l})}}):We.create()}const $o={object:M.lazycreate};var k;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(k||(k={}));const Zo=(r,e={message:`Input not instance of ${r.name}`})=>Wr(t=>t instanceof r,e),Kr=te.create,Hr=Ie.create,Vo=zt.create,zo=Te.create,Jr=pt.create,Go=Le.create,Bo=Ut.create,qo=ft.create,Yo=ht.create,Wo=We.create,Ko=Fe.create,Ho=be.create,Jo=$t.create,Qo=re.create,Xo=M.create,es=M.strictCreate,ts=mt.create,rs=Zt.create,ns=yt.create,os=de.create,ss=_t.create,as=Vt.create,is=Ue.create,cs=He.create,ls=gt.create,us=vt.create,ds=Re.create,ps=wt.create,fs=Je.create,Qr=ne.create,hs=pe.create,ms=Oe.create,ys=ne.createWithPreprocess,_s=Et.create;var a=Object.freeze({__proto__:null,defaultErrorMap:qe,setErrorMap:ko,getErrorMap:jt,makeIssue:Lt,EMPTY_PATH:Eo,addIssueToContext:g,ParseStatus:q,INVALID:E,DIRTY:Ye,OK:W,isAborted:pr,isDirty:fr,isValid:ct,isAsync:lt,get util(){return R},get objectUtil(){return dr},ZodParsedType:v,getParsedType:xe,ZodType:I,datetimeRegex:qr,ZodString:te,ZodNumber:Ie,ZodBigInt:Te,ZodBoolean:pt,ZodDate:Le,ZodSymbol:Ut,ZodUndefined:ft,ZodNull:ht,ZodAny:We,ZodUnknown:Fe,ZodNever:be,ZodVoid:$t,ZodArray:re,ZodObject:M,ZodUnion:mt,ZodDiscriminatedUnion:Zt,ZodIntersection:yt,ZodTuple:de,ZodRecord:_t,ZodMap:Vt,ZodSet:Ue,ZodFunction:He,ZodLazy:gt,ZodLiteral:vt,ZodEnum:Re,ZodNativeEnum:wt,ZodPromise:Je,ZodEffects:ne,ZodTransformer:ne,ZodOptional:pe,ZodNullable:Oe,ZodDefault:bt,ZodCatch:kt,ZodNaN:zt,BRAND:Uo,ZodBranded:yr,ZodPipeline:Et,ZodReadonly:Ct,custom:Wr,Schema:I,ZodSchema:I,late:$o,get ZodFirstPartyTypeKind(){return k},coerce:{string:r=>te.create({...r,coerce:!0}),number:r=>Ie.create({...r,coerce:!0}),boolean:r=>pt.create({...r,coerce:!0}),bigint:r=>Te.create({...r,coerce:!0}),date:r=>Le.create({...r,coerce:!0})},any:Wo,array:Qo,bigint:zo,boolean:Jr,date:Go,discriminatedUnion:rs,effect:Qr,enum:ds,function:cs,instanceof:Zo,intersection:ns,lazy:ls,literal:us,map:as,nan:Vo,nativeEnum:ps,never:Ho,null:Yo,nullable:ms,number:Hr,object:Xo,oboolean:()=>Jr().optional(),onumber:()=>Hr().optional(),optional:hs,ostring:()=>Kr().optional(),pipeline:_s,preprocess:ys,promise:fs,record:ss,set:is,strictObject:es,string:Kr,symbol:Bo,transformer:Qr,tuple:os,undefined:qo,union:ts,unknown:Ko,void:Jo,NEVER:E,ZodIssueCode:m,quotelessJson:bo,ZodError:X});const gs=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()}),vs=a.array(gs),ws=a.object({code:a.string(),message:a.string(),path:a.array(a.string())}),bs=a.array(ws),ks={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},_r=r=>{const e=r.toLowerCase().trim();return ks[e]??r},Es=r=>{try{return typeof JSON.parse(r)=="object"}catch{return!1}},Cs=r=>r.length===1?_r(r[0].msg):`Please fix the following errors:
2
+ ${r.map(t=>`• ${_r(t.msg)}`).join(`
3
+ `)}`,Ss=r=>`Encountered the following errors:
4
4
  ${r.map(t=>`- ${t.path.join("/")}: ${t.message}`).join(`
5
- `)}`,ue=r=>{if(r instanceof Error)if(_s(r.message)){const e=JSON.parse(r.message);return fs.safeParse(e).success?gs(e):ms.safeParse(e).success?vs(e):(console.warn(`Encountered unknown stringified JSON object:
6
- ${r.message}`),r.message)}else return fr(r.message);if(typeof r=="object")try{return JSON.stringify(r)}catch(e){return e+""}else return r+""},ws=(r,e,t)=>(...n)=>{try{return e(...n)}catch(o){t(`[form] Error running callback (${r}):`,o);return}};var Q=(r=>(r.pockytPaypal="pockyt-paypal",r.airwallexGooglePay="airwallex-google-pay",r.airwallexApplePay="airwallex-apple-pay",r.authorizenetGooglePay="authorizenet-google-pay",r.authorizenetApplePay="authorizenet-apple-pay",r))(Q||{});const bs=a.nativeEnum(Q),G=a.string().trim().min(1,{message:"Cannot be blank"}),j=a.string().trim().optional(),H=r=>a.nullable(r.optional());var m=(r=>(r.FIRST_NAME="firstName",r.LAST_NAME="lastName",r.EMAIL="email",r.ZIP_CODE="zipCode",r.CITY="city",r.STATE="state",r.COUNTRY="country",r.ADDRESS="address",r.PHONE="phone",r.PROMOTION_CODE="promotionCode",r))(m||{});const Wr=a.nativeEnum(m);var Kr=(r=>(r.CARD_NUMBER="cardNumber",r.CARD_EXPIRY="cardExpiry",r.CARD_CVC="cardCvc",r))(Kr||{});const Hr=a.nativeEnum(Kr),Jr=a.union([Wr,Hr]);var Ke=(r=>(r.CARD="card",r.CARD_NUMBER="card-number",r.CARD_EXPIRY="card-expiry",r.CARD_CVC="card-cvc",r))(Ke||{});const ks=a.nativeEnum(Ke),$t=a.object({provider:a.string(),processor_name:H(a.string()),metadata:H(a.record(a.string(),a.any()))}),Es=a.object({id:a.string()});a.object({cardNumber:j,expiry:j,cvc:j}),a.object({backgroundColor:j,color:j,fontFamily:j,fontSize:j,fontWeight:j,margin:j,padding:j,letterSpacing:j,lineHeight:j,hideIcon:j});const re=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"]),Cs=re.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),Ss=a.object({type:Cs}),Ps=re.extract(["BLUR","FOCUS","CHANGE"]),As=a.object({type:Ps,elementType:Hr,errors:a.array(a.string()).optional()}),xs=re.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),Ts=a.object({type:xs,message:G,headers:a.record(a.string(),a.string()).optional()}),Is=re.extract(["VALIDATION_ERROR"]),Rs=a.object({type:Is,elementType:Jr,errors:a.array(a.string())}),Os=a.object({type:a.literal(re.enum.LAYOUT),height:G}),Ns=a.object({type:a.literal(re.enum.LOADED),sessionId:G,totalAmountAtoms:a.number(),currency:j,checkoutPaymentMethods:a.array($t)}),Ms=a.object({type:a.literal(re.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:a.record(a.string(),a.any()),paymentFlowMetadata:a.any().optional(),startPFMetadata:a.optional(a.record(a.string(),a.any()))}),Ds=a.object({type:a.literal(re.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:a.string()}),Et=a.object({firstName:G,lastName:G,email:G,zipCode:G,country:G,promotionCode:j}),js=a.object({firstName:j,lastName:j,email:G,zipCode:G,country:G,promotionCode:j,address:j,city:j,state:j}),Ls=re.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),Fs=a.object({type:Ls,sessionId:G,checkoutPaymentMethod:$t,paymentFlowMetadata:a.any().optional(),doNotUseLegacyCCFlow:a.boolean().optional(),existingCCPMId:j}).extend(Et.shape),Us=a.object({type:a.literal(re.enum.TOKENIZE_SUCCESS),isReadyForCheckout:a.boolean()}),$s=a.object({type:a.literal(re.enum.CHECKOUT_SUCCESS),invoiceUrls:a.array(a.string()),subscriptionIds:a.array(a.string()),customerId:a.string()}),Zs=a.discriminatedUnion("type",[Ss,As,Ts,Rs,Os,Ns,Fs,Us,$s,Ms,Ds]),Vs=a.object({payload:Zs,nonce:G,formId:G,elementId:G});a.object({amountAtom:a.number(),currency:G}),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:H(a.string()),their_pm_id:H(a.string()),checkout_attempt_id:H(a.string()),processor_specific_metadata:H(a.record(a.string(),a.any()))});const hr=a.object({invoice_urls:a.array(a.string()),subscription_ids:a.array(a.string()),customer_id:a.string()}),zs=a.object({elementType:a.string(),errors:a.array(a.string())});a.object({session_id:a.string()});const Gs=a.object({success:a.literal(!1),error_type:a.literal("validation_error"),errors:a.array(zs)}),Bs=a.discriminatedUnion("success",[a.object({success:a.literal(!0)}),Gs]);a.object({session_id:a.string(),checkout_payment_method:$t,non_cde_form_fields:Et,do_not_use_legacy_cc_flow:a.boolean().optional(),existing_cc_pm_id:H(a.string())}),a.object({session_id:a.string(),checkout_payment_method:$t,non_cde_form_fields:Et,extra_metadata:a.record(a.string(),a.any()).optional()});var ne=(r=>(r.SUCCESS="success",r.FAILURE="failure",r.CANCELLED="cancelled",r))(ne||{});const qs=a.object({status:a.enum(["success","failure","cancelled"]),href:a.string().optional().nullable()});a.object({href:a.string().optional().nullable()});const Ys=a.object({type:a.string(),redirect_url:a.string(),initial_intent_id:a.string(),consent_id:a.string(),their_pm_id:a.string().optional()}),Qr=a.object({type:a.string(),redirect_url:H(a.string()),initial_intent_id:H(a.string()),consent_id:H(a.string()),their_pm_id:H(a.string()),payment_session:H(a.record(a.string(),a.any()))}),Ws=a.discriminatedUnion("present",[a.object({present:a.literal(!0),href:a.string()}),a.object({present:a.literal(!1)})]),Ks=a.object({payment_methods:a.array(Es),pay_first_success_response:H(hr),required_user_actions:H(a.array(Qr))}),Hs=r=>{const e={};return Object.entries(r).forEach(([t,n])=>{try{const o=Wr.parse(t);Array.isArray(n)?e[o]=n:Array.isArray(n._errors)&&(e[o]=n._errors)}catch{return}}),e},Js=a.object({stripe_pk:a.string(),client_secret:a.string(),stripe_pm_id:a.string()}),Qs=a.object({type:a.string(),client_secret:a.string(),stripe_pk:a.string()}),Xs={usd:"usd",brl:"brl"},Zt=async r=>{for(let t=0;t<10;t++)en()||await Xr(500);if(!en())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(r)},ea=async(r,e)=>{const t=await Zt(r);return{elements:t.elements(e),stripe:t}},ta=async(r,e,t,n,o)=>{const s=await Zt(r),i=Xs[t.toLowerCase().trim()];return s.paymentRequest({country:"US",currency:i,total:{label:"Total",amount:e,pending:n},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},Xr=r=>new Promise(e=>{setTimeout(e,r)}),en=()=>"Stripe"in window,ra=async r=>new Promise((e,t)=>{try{r.on("paymentmethod",async n=>{console.log("paymentmethod EVT:: ",n),e(n)}),r.on("token",async n=>{console.log("token EVT:: ",n)}),r.on("cancel",()=>{t(new Error("Payment cancelled, please click Submit again to pay"))})}catch(n){t(n)}}),na=async(r,e)=>{if(!r.stripe_pk||!r.client_secret)throw new Error(`Invalid next action metadata format: ${JSON.stringify(r)}`);const n=await(await Zt(r.stripe_pk)).confirmCardSetup(r.client_secret,{payment_method:e.paymentMethod.id});if(n.error)throw e.complete("fail"),new Error(`Payment failed: ${n.error.message??"unknown"}`);return e.complete("success"),n},oa=async r=>{var o,s,i,c;const t=await(await Zt(r.stripe_pk)).confirmCardSetup(r.client_secret,{payment_method:r.stripe_pm_id}),n=(o=t.setupIntent)==null?void 0:o.status;if(n==="succeeded")console.log("[3DS] CONFIRMING PM:",r.stripe_pm_id),console.log("[3DS] Setup intent created:",t.setupIntent);else throw n==="canceled"?new Error("Payment cancelled, please click Submit again to pay"):new Error(`${((s=t.error)==null?void 0:s.message)??((c=(i=t.setupIntent)==null?void 0:i.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},sa=r=>JSON.stringify(r);for(var $=[],mr=0;mr<256;++mr)$.push((mr+256).toString(16).slice(1));function aa(r,e=0){return($[r[e+0]]+$[r[e+1]]+$[r[e+2]]+$[r[e+3]]+"-"+$[r[e+4]]+$[r[e+5]]+"-"+$[r[e+6]]+$[r[e+7]]+"-"+$[r[e+8]]+$[r[e+9]]+"-"+$[r[e+10]]+$[r[e+11]]+$[r[e+12]]+$[r[e+13]]+$[r[e+14]]+$[r[e+15]]).toLowerCase()}var Vt,ia=new Uint8Array(16);function ca(){if(!Vt&&(Vt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Vt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Vt(ia)}var la=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const tn={randomUUID:la};function rn(r,e,t){if(tn.randomUUID&&!e&&!r)return tn.randomUUID();r=r||{};var n=r.random||(r.rng||ca)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,aa(n)}const be=(r,e)=>Array.from(r.querySelectorAll("[data-opid]")??[]).reduce((o,s)=>{const i=s.getAttribute("data-opid");return i?{...o,[i]:s.value}:o},{}),ua=r=>{try{return Vs.parse(r)}catch(e){throw console.error("Error parsing event payload:",r,e),e}};var de;(function(r){r.Call="call",r.Reply="reply",r.Syn="syn",r.SynAck="synAck",r.Ack="ack"})(de||(de={}));var Ue;(function(r){r.Fulfilled="fulfilled",r.Rejected="rejected"})(Ue||(Ue={}));var Ct;(function(r){r.ConnectionDestroyed="ConnectionDestroyed",r.ConnectionTimeout="ConnectionTimeout",r.NoIframeSrc="NoIframeSrc"})(Ct||(Ct={}));var yr;(function(r){r.DataCloneError="DataCloneError"})(yr||(yr={}));var Re;(function(r){r.Message="message"})(Re||(Re={}));const da=(r,e)=>{const t=[];let n=!1;return{destroy(o){n||(n=!0,e(`${r}: Destroying connection`),t.forEach(s=>{s(o)}))},onDestroy(o){n?o():t.push(o)}}},pa=r=>(...e)=>{r&&console.log("[Penpal]",...e)},fa={"http:":"80","https:":"443"},ha=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,ma=["file:","data:"],ya=r=>{if(r&&ma.find(c=>r.startsWith(c)))return"null";const e=document.location,t=ha.exec(r);let n,o,s;t?(n=t[1]?t[1]:e.protocol,o=t[2],s=t[4]):(n=e.protocol,o=e.hostname,s=e.port);const i=s&&s!==fa[n]?`:${s}`:"";return`${n}//${o}${i}`},nn=({name:r,message:e,stack:t})=>({name:r,message:e,stack:t}),_a=r=>{const e=new Error;return Object.keys(r).forEach(t=>e[t]=r[t]),e},ga=(r,e,t)=>{const{localName:n,local:o,remote:s,originForSending:i,originForReceiving:c}=r;let l=!1;const u=d=>{if(d.source!==s||d.data.penpal!==de.Call)return;if(c!=="*"&&d.origin!==c){t(`${n} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const f=d.data,{methodName:_,args:p,id:y}=f;t(`${n}: Received ${_}() call`);const w=C=>I=>{if(t(`${n}: Sending ${_}() reply`),l){t(`${n}: Unable to send ${_}() reply due to destroyed connection`);return}const T={penpal:de.Reply,id:y,resolution:C,returnValue:I};C===Ue.Rejected&&I instanceof Error&&(T.returnValue=nn(I),T.returnValueIsError=!0);try{s.postMessage(T,i)}catch(S){if(S.name===yr.DataCloneError){const D={penpal:de.Reply,id:y,resolution:Ue.Rejected,returnValue:nn(S),returnValueIsError:!0};s.postMessage(D,i)}throw S}};new Promise(C=>C(e[_].apply(e,p))).then(w(Ue.Fulfilled),w(Ue.Rejected))};return o.addEventListener(Re.Message,u),()=>{l=!0,o.removeEventListener(Re.Message,u)}};let va=0;const wa=()=>++va,on=".",sn=r=>r?r.split(on):[],ba=r=>r.join(on),ka=(r,e)=>{const t=sn(e||"");return t.push(r),ba(t)},Ea=(r,e,t)=>{const n=sn(e);return n.reduce((o,s,i)=>(typeof o[s]>"u"&&(o[s]={}),i===n.length-1&&(o[s]=t),o[s]),r),r},an=(r,e)=>{const t={};return Object.keys(r).forEach(n=>{const o=r[n],s=ka(n,e);typeof o=="object"&&Object.assign(t,an(o,s)),typeof o=="function"&&(t[s]=o)}),t},Ca=r=>{const e={};for(const t in r)Ea(e,t,r[t]);return e},Sa=(r,e,t,n,o)=>{const{localName:s,local:i,remote:c,originForSending:l,originForReceiving:u}=e;let d=!1;o(`${s}: Connecting call sender`);const f=p=>(...y)=>{o(`${s}: Sending ${p}() call`);let w;try{c.closed&&(w=!0)}catch{w=!0}if(w&&n(),d){const C=new Error(`Unable to send ${p}() call due to destroyed connection`);throw C.code=Ct.ConnectionDestroyed,C}return new Promise((C,I)=>{const T=wa(),S=L=>{if(L.source!==c||L.data.penpal!==de.Reply||L.data.id!==T)return;if(u!=="*"&&L.origin!==u){o(`${s} received message from origin ${L.origin} which did not match expected origin ${u}`);return}const F=L.data;o(`${s}: Received ${p}() reply`),i.removeEventListener(Re.Message,S);let _e=F.returnValue;F.returnValueIsError&&(_e=_a(_e)),(F.resolution===Ue.Fulfilled?C:I)(_e)};i.addEventListener(Re.Message,S);const D={penpal:de.Call,id:T,methodName:p,args:y};c.postMessage(D,l)})},_=t.reduce((p,y)=>(p[y]=f(y),p),{});return Object.assign(r,Ca(_)),()=>{d=!0}},Pa=(r,e,t,n,o)=>{const{destroy:s,onDestroy:i}=n;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:t,originForReceiving:e};c&&c(),c=ga(f,r,o),i(c),l&&l.forEach(p=>{delete u[p]}),l=d.data.methodNames;const _=Sa(u,f,l,s,o);return i(_),u}},Aa=(r,e,t,n)=>o=>{if(!o.source)return;if(t!=="*"&&o.origin!==t){r(`Parent: Handshake - Received SYN message from origin ${o.origin} which did not match expected origin ${t}`);return}r("Parent: Handshake - Received SYN, responding with SYN-ACK");const s={penpal:de.SynAck,methodNames:Object.keys(e)};o.source.postMessage(s,n)},xa=6e4,Ta=(r,e)=>{const{destroy:t,onDestroy:n}=e,o=setInterval(()=>{r.isConnected||(clearInterval(o),t())},xa);n(()=>{clearInterval(o)})},Ia=(r,e)=>{let t;return r!==void 0&&(t=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${r}ms`);n.code=Ct.ConnectionTimeout,e(n)},r)),()=>{clearTimeout(t)}},Ra=r=>{if(!r.src&&!r.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=Ct.NoIframeSrc,e}},cn=r=>{let{iframe:e,methods:t={},childOrigin:n,timeout:o,debug:s=!1}=r;const i=pa(s),c=da("Parent",i),{onDestroy:l,destroy:u}=c;n||(Ra(e),n=ya(e.src));const d=n==="null"?"*":n,f=an(t),_=Aa(i,f,n,d),p=Pa(f,n,d,c,i);return{promise:new Promise((w,C)=>{const I=Ia(o,u),T=S=>{if(!(S.source!==e.contentWindow||!S.data)){if(S.data.penpal===de.Syn){_(S);return}if(S.data.penpal===de.Ack){const D=p(S);D&&(I(),w(D));return}}};window.addEventListener(Re.Message,T),i("Parent: Awaiting handshake"),Ta(e,c),l(S=>{window.removeEventListener(Re.Message,T),S&&C(S)})}),destroy(){u()}}},Oa=async r=>{if(typeof r!="object"||!r)return!1;try{const e={type:"ping"},t=await r.send(e);if(t!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(t)}`);return!0}catch(e){return console.error("Invalid CDE connection check:",e),!1}},Na=(r,e)=>!!r&&e,A=r=>a.nullable(r.optional());a.string().trim().min(1,{message:"Cannot be blank"});const Ma=a.object({cde_response_type:a.literal("error"),message:a.string(),headers:a.record(a.string(),a.string()).optional()});a.enum(["usd","brl"]);const ln=a.object({name:a.string(),amount_atom_off:A(a.number()),percent_off:A(a.number()),currency:A(a.string()),duration:a.string(),duration_in_months:A(a.number())}),un=a.object({amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),currency:a.string(),description:A(a.string()),price_id:a.string(),billing_interval:A(a.string()),billing_interval_count:A(a.number().int()),quantity:a.number().int()}),Da=a.record(a.string(),a.any()),ja=a.object({name:a.string(),settings:A(Da)}),He=a.object({provider:a.string(),processor_name:A(a.string()),metadata:A(a.record(a.string(),a.any()))}),La=a.object({quantity:a.number()}),Fa=a.object({id:A(a.string()),billing_interval:A(a.string()),billing_interval_count:A(a.number().int()),subscription_items:a.array(La),trial_start:A(a.string()),trial_end:A(a.string())}),dn=a.object({amount_atom:a.number()}),Ua=a.object({amount_atom:a.number(),amount_atom_considering_discount_applied:a.number(),currency:a.string(),discount_amount_atoms:a.array(dn),subscription_item_id:a.string()}),$a=a.object({coupon:ln}),Za=a.object({currency:a.string(),discounts:a.array($a),hosted_invoice_url:A(a.string()),lines:a.array(Ua),remaining_amount_atom:a.number(),tax_amount_atom:a.number(),total_amount_atom:a.number(),total_discount_amount_atoms:a.array(dn)}),pn=a.object({created:a.array(Fa),invoices:a.array(Za)}),fn=a.object({preview:pn,preview_post_trial:A(pn),coupons:a.array(ln)}),hn=a.object({status:a.literal("open"),token:a.string(),email:A(a.string()),line_items:a.array(un),amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),brand:ja,subs_preview:A(fn),methods_available:a.array(He)}),mn=a.discriminatedUnion("mode",[a.object({mode:a.literal("setup"),currency:a.nullable(a.undefined())}).extend(hn.shape),a.object({mode:a.enum(["payment","subscription"]),currency:a.string()}).extend(hn.shape)]),Va=a.object({status:a.literal("complete")}),za=a.object({status:a.literal("expired")});a.union([mn,Va,za]),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(un),total_amount_atom:a.number().int(),cancel_at_end:a.boolean(),checkout_payment_method:He,promotion_code:a.string().optional(),do_not_use_legacy_cc_flow:a.boolean().optional(),use_confirmed_pm_id:A(a.string())});const yn=a.object({payment_method_id:a.string()});a.object({id:a.string(),return_url:a.string()});const Ga=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()});a.array(Ga);const Ba=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()}),qa=a.object({price_id:a.string(),quantity:a.number().int()}),Ya=a.object({line_items:a.array(qa),promotion_code:a.string().optional(),displayed_total_amount_atom:a.number().int()}),Wa=a.object({processor_specific_metadata:A(a.record(a.string(),a.any()))});a.object({payment_provider:a.string(),checkout_payment_method:He,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:Ya.optional()}).extend(Ba.shape).extend(Wa.shape);const _n=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),checkout_attempt_id:A(a.string())});a.object({fields:js,checkoutPaymentMethod:He}),a.object({session_id:a.string(),non_cde_form_fields:Et,checkout_payment_method:He,extra_metadata:a.record(a.string(),a.any())});const Ka=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:A(a.string()),last_name:A(a.string()),line1:A(a.string()),line2:A(a.string()),line3:A(a.string()),city:A(a.string()),state:A(a.string()),country:A(a.string()),zip_code:A(a.string()),email:A(a.string()),billing_email:A(a.string()),phone_number:A(a.string()),update_processor_customer:A(a.boolean())}),a.object({id:a.string(),email:A(a.string()),first_name:A(a.string()),last_name:A(a.string()),phone_number:A(a.string()),billing_email:A(a.string()),address:A(a.record(a.string(),a.any()))}),a.object({message:a.string()});const Ha=a.object({error_code:a.string()});a.object({checkout_payment_method:He,processor_specific_metadata:a.record(a.any()).optional()});const Ja=a.object({next_action_metadata:A(a.record(a.any()))}),Qa=r=>r.reduce((e,t)=>e+t,0);function Xa(r,e){var t=Object.setPrototypeOf;t?t(r,e):r.__proto__=e}function ei(r,e){e===void 0&&(e=r.constructor);var t=Error.captureStackTrace;t&&t(r,e)}var ti=function(){var r=function(t,n){return r=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])},r(t,n)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ri=function(r){ti(e,r);function e(t,n){var o=this.constructor,s=r.call(this,t,n)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1,configurable:!0}),Xa(s,o.prototype),ei(s),s}return e}(Error);class gn extends ri{constructor(e){const t=`${e.message}`;super(t),this.response=e}get originalErrorMessage(){return this.response.message}}const Y=async(r,e,t)=>{const n=await r.send(e);if(oi(n))throw new gn(n);if(!ni(n,t)){const o=t.safeParse(n);throw o.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",t,"Actual:",n),o.error)}return n},ni=(r,e)=>e.safeParse(r).success,oi=r=>Ma.safeParse(r).success,si=async(r,e)=>await Y(r,{type:"get_checkout_preview",payload:e},fn),W=async r=>await Y(r,{type:"get_prefill",payload:{}},mn),St=async(r,e)=>await Y(r,{type:"v2_start_payment_flow",payload:e},_n),ai=async(r,e)=>await Y(r,{type:"start_payment_flow_for_cc",payload:e},Ka),ii=async(r,e)=>await Y(r,{type:"start_payment_flow_for_pr",payload:e},_n),pe=async(r,e)=>await Y(r,{type:"confirm_payment_flow",payload:e},Ks),ci=async(r,e)=>await Y(r,{type:"finalize_setup_payment_method",payload:e},yn),li=async(r,e)=>await Y(r,{type:"check_if_popup_window_verified",payload:e},Ws),ui=async(r,e,t)=>{const n=await si(r,{secure_token:e,promotion_code:t}),o=new Set(n.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=Qa(n.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:s,amountAtom:i}},Je=async(r,e,t,n)=>{if(t)return{amountAtom:0,currency:"usd"};{n=n||void 0;const o=await ui(r,e,n);return{amountAtom:o.amountAtom,currency:o.currency}}},di=async(r,e)=>{if(r.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(r.values()).map(n=>Y(n,{type:"tokenize_card",payload:e},Bs)))},vn=async(r,e)=>{try{return await Y(r,{type:"checkout_card_elements",payload:e},hr)}catch(t){throw console.error("[cde-client] Error during checkoutCardElements:",t,JSON.stringify(t)),t}},pi=async(r,e)=>await Y(r,{type:"setup_payment_method",payload:e},yn),_r=async(r,e)=>await Y(r,{type:"checkout",payload:e},hr),wn=1e3,fi=async(r,e)=>{console.log(e);const n=await cn({iframe:r,debug:!0,timeout:wn,childOrigin:"*"}).promise,o=await Y(n,{type:"ping-3ds-status"},qs);return console.log("🟢 CDE connection successful! Stopping polling... Result:",o),o},bn=async(r,e)=>await Y(r,{type:"prepare_payment_flow",payload:e},Ja),kn=async(r,e)=>{try{return(await Y(r,{type:"get_standardized_error_code",payload:{message:e}},Ha)).error_code}catch(t){return console.error("[cde-client] Error during getStandardizedErrorCode:",ue(t)),"PAYMENT_FAILED_GENERIC"}};function gr(r){throw new Error(`Unhandled case: ${r}`)}const vr=10,En=(r=0)=>e=>`\x1B[${e+r}m`,Cn=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,Sn=(r=0)=>(e,t,n)=>`\x1B[${38+r};2;${e};${t};${n}m`,O={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(O.modifier);const hi=Object.keys(O.color),mi=Object.keys(O.bgColor);[...hi,...mi];function yi(){const r=new Map;for(const[e,t]of Object.entries(O)){for(const[n,o]of Object.entries(t))O[n]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},t[n]=O[n],r.set(o[0],o[1]);Object.defineProperty(O,e,{value:t,enumerable:!1})}return Object.defineProperty(O,"codes",{value:r,enumerable:!1}),O.color.close="\x1B[39m",O.bgColor.close="\x1B[49m",O.color.ansi=En(),O.color.ansi256=Cn(),O.color.ansi16m=Sn(),O.bgColor.ansi=En(vr),O.bgColor.ansi256=Cn(vr),O.bgColor.ansi16m=Sn(vr),Object.defineProperties(O,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(s=>s+s).join(""));const o=Number.parseInt(n,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:e=>O.rgbToAnsi256(...O.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,o;if(e>=232)t=((e-232)*10+8)/255,n=t,o=t;else{e-=16;const c=e%36;t=Math.floor(e/36)/5,n=Math.floor(c/6)/5,o=c%6/5}const s=Math.max(t,n,o)*2;if(s===0)return 30;let i=30+(Math.round(o)<<2|Math.round(n)<<1|Math.round(t));return s===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>O.ansi256ToAnsi(O.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>O.ansi256ToAnsi(O.hexToAnsi256(e)),enumerable:!1}}),O}const fe=yi(),zt=(()=>{if(navigator.userAgentData){const r=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(r&&r.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),Pn=zt!==0&&{level:zt,hasBasic:!0,has256:zt>=2,has16m:zt>=3},_i={stdout:Pn,stderr:Pn};function gi(r,e,t){let n=r.indexOf(e);if(n===-1)return r;const o=e.length;let s=0,i="";do i+=r.slice(s,n)+e+t,s=n+o,n=r.indexOf(e,s);while(n!==-1);return i+=r.slice(s),i}function vi(r,e,t,n){let o=0,s="";do{const i=r[n-1]==="\r";s+=r.slice(o,i?n-1:n)+e+(i?`\r
5
+ `)}`,fe=r=>{if(r instanceof Error)if(Es(r.message)){const e=JSON.parse(r.message);return vs.safeParse(e).success?Cs(e):bs.safeParse(e).success?Ss(e):(console.warn(`Encountered unknown stringified JSON object:
6
+ ${r.message}`),r.message)}else return _r(r.message);if(typeof r=="object")try{return JSON.stringify(r)}catch(e){return e+""}else return r+""},Ps=(r,e,t)=>(...n)=>{try{return e(...n)}catch(o){t(`[form] Error running callback (${r}):`,o);return}};var ee=(r=>(r.pockytPaypal="pockyt-paypal",r.airwallexGooglePay="airwallex-google-pay",r.airwallexApplePay="airwallex-apple-pay",r.authorizenetGooglePay="authorizenet-google-pay",r.authorizenetApplePay="authorizenet-apple-pay",r.loopCrypto="loop-crypto",r))(ee||{});const As=a.nativeEnum(ee),Y=a.string().trim().min(1,{message:"Cannot be blank"}),j=a.string().trim().optional(),Q=r=>a.nullable(r.optional());var y=(r=>(r.FIRST_NAME="firstName",r.LAST_NAME="lastName",r.EMAIL="email",r.ZIP_CODE="zipCode",r.CITY="city",r.STATE="state",r.COUNTRY="country",r.ADDRESS="address",r.PHONE="phone",r.PROMOTION_CODE="promotionCode",r))(y||{});const Xr=a.nativeEnum(y);var en=(r=>(r.CARD_NUMBER="cardNumber",r.CARD_EXPIRY="cardExpiry",r.CARD_CVC="cardCvc",r))(en||{});const tn=a.nativeEnum(en),rn=a.union([Xr,tn]);var Qe=(r=>(r.CARD="card",r.CARD_NUMBER="card-number",r.CARD_EXPIRY="card-expiry",r.CARD_CVC="card-cvc",r))(Qe||{});const xs=a.nativeEnum(Qe),Gt=a.object({provider:a.string(),processor_name:Q(a.string()),metadata:Q(a.record(a.string(),a.any()))}),Is=a.object({id:a.string()});a.object({cardNumber:j,expiry:j,cvc:j}),a.object({backgroundColor:j,color:j,fontFamily:j,fontSize:j,fontWeight:j,margin:j,padding:j,letterSpacing:j,lineHeight:j,hideIcon:j});const oe=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"]),Ts=oe.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),Rs=a.object({type:Ts}),Os=oe.extract(["BLUR","FOCUS","CHANGE"]),Ns=a.object({type:Os,elementType:tn,errors:a.array(a.string()).optional()}),Ms=oe.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),Ds=a.object({type:Ms,message:Y,headers:a.record(a.string(),a.string()).optional()}),js=oe.extract(["VALIDATION_ERROR"]),Ls=a.object({type:js,elementType:rn,errors:a.array(a.string())}),Fs=a.object({type:a.literal(oe.enum.LAYOUT),height:Y}),Us=a.object({type:a.literal(oe.enum.LOADED),sessionId:Y,totalAmountAtoms:a.number(),currency:j,checkoutPaymentMethods:a.array(Gt)}),$s=a.object({type:a.literal(oe.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:a.record(a.string(),a.any()),paymentFlowMetadata:a.any().optional(),startPFMetadata:a.optional(a.record(a.string(),a.any()))}),Zs=a.object({type:a.literal(oe.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:a.string()}),St=a.object({firstName:Y,lastName:Y,email:Y,zipCode:Y,country:Y,promotionCode:j}),Vs=a.object({firstName:j,lastName:j,email:Y,zipCode:Y,country:Y,promotionCode:j,address:j,city:j,state:j}),zs=oe.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),Gs=a.object({type:zs,sessionId:Y,checkoutPaymentMethod:Gt,paymentFlowMetadata:a.any().optional(),doNotUseLegacyCCFlow:a.boolean().optional(),existingCCPMId:j}).extend(St.shape),Bs=a.object({type:a.literal(oe.enum.TOKENIZE_SUCCESS),isReadyForCheckout:a.boolean()}),qs=a.object({type:a.literal(oe.enum.CHECKOUT_SUCCESS),invoiceUrls:a.array(a.string()),subscriptionIds:a.array(a.string()),customerId:a.string()}),Ys=a.discriminatedUnion("type",[Rs,Ns,Ds,Ls,Fs,Us,Gs,Bs,qs,$s,Zs]),Ws=a.object({payload:Ys,nonce:Y,formId:Y,elementId:Y});a.object({amountAtom:a.number(),currency:Y}),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 gr=a.object({invoice_urls:a.array(a.string()),subscription_ids:a.array(a.string()),customer_id:a.string()}),Ks=a.object({elementType:a.string(),errors:a.array(a.string())});a.object({session_id:a.string()});const Hs=a.object({success:a.literal(!1),error_type:a.literal("validation_error"),errors:a.array(Ks)}),Js=a.discriminatedUnion("success",[a.object({success:a.literal(!0)}),Hs]);a.object({session_id:a.string(),checkout_payment_method:Gt,non_cde_form_fields:St,do_not_use_legacy_cc_flow:a.boolean().optional(),existing_cc_pm_id:Q(a.string()),extra_metadata:a.record(a.string(),a.any())}),a.object({session_id:a.string(),checkout_payment_method:Gt,non_cde_form_fields:St,extra_metadata:a.record(a.string(),a.any()).optional()});var $=(r=>(r.SUCCESS="success",r.FAILURE="failure",r.CANCELLED="cancelled",r))($||{});const Qs=a.object({status:a.enum(["success","failure","cancelled"]),href:a.string().optional().nullable()});a.object({href:a.string().optional().nullable()});const Xs=a.object({type:a.string(),redirect_url:a.string(),initial_intent_id:a.string(),consent_id:a.string(),their_pm_id:a.string().optional()}),nn=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()))}),ea=a.discriminatedUnion("present",[a.object({present:a.literal(!0),href:a.string()}),a.object({present:a.literal(!1)})]),ta=a.object({payment_methods:a.array(Is),pay_first_success_response:Q(gr),required_user_actions:Q(a.array(nn))}),ra=r=>{const e={};return Object.entries(r).forEach(([t,n])=>{try{const o=Xr.parse(t);Array.isArray(n)?e[o]=n:Array.isArray(n._errors)&&(e[o]=n._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()}),sa={usd:"usd",brl:"brl"},Bt=async r=>{for(let t=0;t<10;t++)on()||await vr(500);if(!on())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(r)},aa=async(r,e)=>{const t=await Bt(r);return{elements:t.elements(e),stripe:t}},ia=async(r,e,t,n,o)=>{const s=await Bt(r),i=sa[t.toLowerCase().trim()];return s.paymentRequest({country:"US",currency:i,total:{label:"Total",amount:e,pending:n},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},vr=r=>new Promise(e=>{setTimeout(e,r)}),on=()=>"Stripe"in window,ca=async r=>new Promise((e,t)=>{try{r.on("paymentmethod",async n=>{console.log("paymentmethod EVT:: ",n),e(n)}),r.on("token",async n=>{console.log("token EVT:: ",n)}),r.on("cancel",()=>{t(new Error("Payment cancelled, please click Submit again to pay"))})}catch(n){t(n)}}),la=async(r,e)=>{if(!r.stripe_pk||!r.client_secret)throw new Error(`Invalid next action metadata format: ${JSON.stringify(r)}`);const n=await(await Bt(r.stripe_pk)).confirmCardSetup(r.client_secret,{payment_method:e.paymentMethod.id});if(n.error)throw e.complete("fail"),new Error(`Payment failed: ${n.error.message??"unknown"}`);return e.complete("success"),n},ua=async r=>{var o,s,i,c;const t=await(await Bt(r.stripe_pk)).confirmCardSetup(r.client_secret,{payment_method:r.stripe_pm_id}),n=(o=t.setupIntent)==null?void 0:o.status;if(n==="succeeded")console.log("[3DS] CONFIRMING PM:",r.stripe_pm_id),console.log("[3DS] Setup intent created:",t.setupIntent);else throw n==="canceled"?new Error("Payment cancelled, please click Submit again to pay"):new Error(`${((s=t.error)==null?void 0:s.message)??((c=(i=t.setupIntent)==null?void 0:i.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},da=r=>JSON.stringify(r);for(var V=[],wr=0;wr<256;++wr)V.push((wr+256).toString(16).slice(1));function pa(r,e=0){return(V[r[e+0]]+V[r[e+1]]+V[r[e+2]]+V[r[e+3]]+"-"+V[r[e+4]]+V[r[e+5]]+"-"+V[r[e+6]]+V[r[e+7]]+"-"+V[r[e+8]]+V[r[e+9]]+"-"+V[r[e+10]]+V[r[e+11]]+V[r[e+12]]+V[r[e+13]]+V[r[e+14]]+V[r[e+15]]).toLowerCase()}var qt,fa=new Uint8Array(16);function ha(){if(!qt&&(qt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!qt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return qt(fa)}var ma=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const sn={randomUUID:ma};function br(r,e,t){if(sn.randomUUID&&!e&&!r)return sn.randomUUID();r=r||{};var n=r.random||(r.rng||ha)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,pa(n)}const he=(r,e)=>Array.from(r.querySelectorAll("[data-opid]")??[]).reduce((o,s)=>{const i=s.getAttribute("data-opid");return i?{...o,[i]:s.value}:o},{}),ya=r=>{try{return Ws.parse(r)}catch(e){throw console.error("Error parsing event payload:",r,e),e}};var me;(function(r){r.Call="call",r.Reply="reply",r.Syn="syn",r.SynAck="synAck",r.Ack="ack"})(me||(me={}));var $e;(function(r){r.Fulfilled="fulfilled",r.Rejected="rejected"})($e||($e={}));var Pt;(function(r){r.ConnectionDestroyed="ConnectionDestroyed",r.ConnectionTimeout="ConnectionTimeout",r.NoIframeSrc="NoIframeSrc"})(Pt||(Pt={}));var kr;(function(r){r.DataCloneError="DataCloneError"})(kr||(kr={}));var Ne;(function(r){r.Message="message"})(Ne||(Ne={}));const _a=(r,e)=>{const t=[];let n=!1;return{destroy(o){n||(n=!0,e(`${r}: Destroying connection`),t.forEach(s=>{s(o)}))},onDestroy(o){n?o():t.push(o)}}},ga=r=>(...e)=>{r&&console.log("[Penpal]",...e)},va={"http:":"80","https:":"443"},wa=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,ba=["file:","data:"],ka=r=>{if(r&&ba.find(c=>r.startsWith(c)))return"null";const e=document.location,t=wa.exec(r);let n,o,s;t?(n=t[1]?t[1]:e.protocol,o=t[2],s=t[4]):(n=e.protocol,o=e.hostname,s=e.port);const i=s&&s!==va[n]?`:${s}`:"";return`${n}//${o}${i}`},an=({name:r,message:e,stack:t})=>({name:r,message:e,stack:t}),Ea=r=>{const e=new Error;return Object.keys(r).forEach(t=>e[t]=r[t]),e},Ca=(r,e,t)=>{const{localName:n,local:o,remote:s,originForSending:i,originForReceiving:c}=r;let l=!1;const u=d=>{if(d.source!==s||d.data.penpal!==me.Call)return;if(c!=="*"&&d.origin!==c){t(`${n} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const p=d.data,{methodName:_,args:f,id:h}=p;t(`${n}: Received ${_}() call`);const w=x=>C=>{if(t(`${n}: Sending ${_}() reply`),l){t(`${n}: Unable to send ${_}() reply due to destroyed connection`);return}const T={penpal:me.Reply,id:h,resolution:x,returnValue:C};x===$e.Rejected&&C instanceof Error&&(T.returnValue=an(C),T.returnValueIsError=!0);try{s.postMessage(T,i)}catch(S){if(S.name===kr.DataCloneError){const D={penpal:me.Reply,id:h,resolution:$e.Rejected,returnValue:an(S),returnValueIsError:!0};s.postMessage(D,i)}throw S}};new Promise(x=>x(e[_].apply(e,f))).then(w($e.Fulfilled),w($e.Rejected))};return o.addEventListener(Ne.Message,u),()=>{l=!0,o.removeEventListener(Ne.Message,u)}};let Sa=0;const Pa=()=>++Sa,cn=".",ln=r=>r?r.split(cn):[],Aa=r=>r.join(cn),xa=(r,e)=>{const t=ln(e||"");return t.push(r),Aa(t)},Ia=(r,e,t)=>{const n=ln(e);return n.reduce((o,s,i)=>(typeof o[s]>"u"&&(o[s]={}),i===n.length-1&&(o[s]=t),o[s]),r),r},un=(r,e)=>{const t={};return Object.keys(r).forEach(n=>{const o=r[n],s=xa(n,e);typeof o=="object"&&Object.assign(t,un(o,s)),typeof o=="function"&&(t[s]=o)}),t},Ta=r=>{const e={};for(const t in r)Ia(e,t,r[t]);return e},Ra=(r,e,t,n,o)=>{const{localName:s,local:i,remote:c,originForSending:l,originForReceiving:u}=e;let d=!1;o(`${s}: Connecting call sender`);const p=f=>(...h)=>{o(`${s}: Sending ${f}() call`);let w;try{c.closed&&(w=!0)}catch{w=!0}if(w&&n(),d){const x=new Error(`Unable to send ${f}() call due to destroyed connection`);throw x.code=Pt.ConnectionDestroyed,x}return new Promise((x,C)=>{const T=Pa(),S=F=>{if(F.source!==c||F.data.penpal!==me.Reply||F.data.id!==T)return;if(u!=="*"&&F.origin!==u){o(`${s} received message from origin ${F.origin} which did not match expected origin ${u}`);return}const U=F.data;o(`${s}: Received ${f}() reply`),i.removeEventListener(Ne.Message,S);let ve=U.returnValue;U.returnValueIsError&&(ve=Ea(ve)),(U.resolution===$e.Fulfilled?x:C)(ve)};i.addEventListener(Ne.Message,S);const D={penpal:me.Call,id:T,methodName:f,args:h};c.postMessage(D,l)})},_=t.reduce((f,h)=>(f[h]=p(h),f),{});return Object.assign(r,Ta(_)),()=>{d=!0}},Oa=(r,e,t,n,o)=>{const{destroy:s,onDestroy:i}=n;let c,l;const u={};return d=>{if(e!=="*"&&d.origin!==e){o(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}o("Parent: Handshake - Received ACK");const p={localName:"Parent",local:window,remote:d.source,originForSending:t,originForReceiving:e};c&&c(),c=Ca(p,r,o),i(c),l&&l.forEach(f=>{delete u[f]}),l=d.data.methodNames;const _=Ra(u,p,l,s,o);return i(_),u}},Na=(r,e,t,n)=>o=>{if(!o.source)return;if(t!=="*"&&o.origin!==t){r(`Parent: Handshake - Received SYN message from origin ${o.origin} which did not match expected origin ${t}`);return}r("Parent: Handshake - Received SYN, responding with SYN-ACK");const s={penpal:me.SynAck,methodNames:Object.keys(e)};o.source.postMessage(s,n)},Ma=6e4,Da=(r,e)=>{const{destroy:t,onDestroy:n}=e,o=setInterval(()=>{r.isConnected||(clearInterval(o),t())},Ma);n(()=>{clearInterval(o)})},ja=(r,e)=>{let t;return r!==void 0&&(t=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${r}ms`);n.code=Pt.ConnectionTimeout,e(n)},r)),()=>{clearTimeout(t)}},La=r=>{if(!r.src&&!r.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=Pt.NoIframeSrc,e}},dn=r=>{let{iframe:e,methods:t={},childOrigin:n,timeout:o,debug:s=!1}=r;const i=ga(s),c=_a("Parent",i),{onDestroy:l,destroy:u}=c;n||(La(e),n=ka(e.src));const d=n==="null"?"*":n,p=un(t),_=Na(i,p,n,d),f=Oa(p,n,d,c,i);return{promise:new Promise((w,x)=>{const C=ja(o,u),T=S=>{if(!(S.source!==e.contentWindow||!S.data)){if(S.data.penpal===me.Syn){_(S);return}if(S.data.penpal===me.Ack){const D=f(S);D&&(C(),w(D));return}}};window.addEventListener(Ne.Message,T),i("Parent: Awaiting handshake"),Da(e,c),l(S=>{window.removeEventListener(Ne.Message,T),S&&x(S)})}),destroy(){u()}}},Fa=async r=>{if(typeof r!="object"||!r)return!1;try{const e={type:"ping"},t=await r.send(e);if(t!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(t)}`);return!0}catch(e){return console.error("Invalid CDE connection check:",e),!1}},Ua=(r,e)=>!!r&&e,A=r=>a.nullable(r.optional());a.string().trim().min(1,{message:"Cannot be blank"});const $a=a.object({cde_response_type:a.literal("error"),message:a.string(),headers:a.record(a.string(),a.string()).optional()});a.enum(["usd","brl"]);const pn=a.object({name:a.string(),amount_atom_off:A(a.number()),percent_off:A(a.number()),currency:A(a.string()),duration:a.string(),duration_in_months:A(a.number())}),fn=a.object({amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),currency:a.string(),description:A(a.string()),price_id:a.string(),billing_interval:A(a.string()),billing_interval_count:A(a.number().int()),quantity:a.number().int()}),Za=a.record(a.string(),a.any()),Va=a.object({name:a.string(),settings:A(Za)}),Xe=a.object({provider:a.string(),processor_name:A(a.string()),metadata:A(a.record(a.string(),a.any()))}),za=a.object({quantity:a.number()}),Ga=a.object({id:A(a.string()),billing_interval:A(a.string()),billing_interval_count:A(a.number().int()),subscription_items:a.array(za),trial_start:A(a.string()),trial_end:A(a.string())}),hn=a.object({amount_atom:a.number()}),Ba=a.object({amount_atom:a.number(),amount_atom_considering_discount_applied:a.number(),currency:a.string(),discount_amount_atoms:a.array(hn),subscription_item_id:a.string()}),qa=a.object({coupon:pn}),Ya=a.object({currency:a.string(),discounts:a.array(qa),hosted_invoice_url:A(a.string()),lines:a.array(Ba),remaining_amount_atom:a.number(),tax_amount_atom:a.number(),total_amount_atom:a.number(),total_discount_amount_atoms:a.array(hn)}),mn=a.object({created:a.array(Ga),invoices:a.array(Ya)}),yn=a.object({preview:mn,preview_post_trial:A(mn),coupons:a.array(pn)}),_n=a.object({status:a.literal("open"),locale:a.string(),token:a.string(),email:A(a.string()),line_items:a.array(fn),amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),brand:Va,subs_preview:A(yn),methods_available:a.array(Xe)}),gn=a.discriminatedUnion("mode",[a.object({mode:a.literal("setup"),currency:a.nullable(a.undefined())}).extend(_n.shape),a.object({mode:a.enum(["payment","subscription"]),currency:a.string()}).extend(_n.shape)]),Wa=a.object({status:a.literal("complete")}),Ka=a.object({status:a.literal("expired")});a.union([gn,Wa,Ka]),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(fn),total_amount_atom:a.number().int(),cancel_at_end:a.boolean(),checkout_payment_method:Xe,promotion_code:a.string().optional(),do_not_use_legacy_cc_flow:a.boolean().optional(),use_confirmed_pm_id:A(a.string())});const vn=a.object({payment_method_id:a.string()});a.object({id:a.string(),return_url:a.string()});const Ha=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()});a.array(Ha);const Ja=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()}),Qa=a.object({price_id:a.string(),quantity:a.number().int()}),Xa=a.object({line_items:a.array(Qa),promotion_code:a.string().optional(),displayed_total_amount_atom:a.number().int()}),ei=a.object({processor_specific_metadata:A(a.record(a.string(),a.any()))});a.object({payment_provider:a.string(),checkout_payment_method:Xe,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:Xa.optional()}).extend(Ja.shape).extend(ei.shape);const wn=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),checkout_attempt_id:A(a.string())});a.object({fields:Vs,checkoutPaymentMethod:Xe}),a.object({session_id:a.string(),non_cde_form_fields:St,checkout_payment_method:Xe,extra_metadata:a.record(a.string(),a.any())});const ti=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:A(a.string()),last_name:A(a.string()),line1:A(a.string()),line2:A(a.string()),line3:A(a.string()),city:A(a.string()),state:A(a.string()),country:A(a.string()),zip_code:A(a.string()),email:A(a.string()),billing_email:A(a.string()),phone_number:A(a.string()),update_processor_customer:A(a.boolean())}),a.object({id:a.string(),email:A(a.string()),first_name:A(a.string()),last_name:A(a.string()),phone_number:A(a.string()),billing_email:A(a.string()),address:A(a.record(a.string(),a.any()))}),a.object({message:a.string()});const ri=a.object({error_code:a.string()});a.object({checkout_payment_method:Xe,processor_specific_metadata:a.record(a.any()).optional()});const ni=a.object({next_action_metadata:A(a.record(a.any()))}),oi=r=>r.reduce((e,t)=>e+t,0);function si(r,e){var t=Object.setPrototypeOf;t?t(r,e):r.__proto__=e}function ai(r,e){e===void 0&&(e=r.constructor);var t=Error.captureStackTrace;t&&t(r,e)}var ii=function(){var r=function(t,n){return r=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])},r(t,n)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ci=function(r){ii(e,r);function e(t,n){var o=this.constructor,s=r.call(this,t,n)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1,configurable:!0}),si(s,o.prototype),ai(s),s}return e}(Error);class bn extends ci{constructor(e){const t=`${e.message}`;super(t),this.response=e}get originalErrorMessage(){return this.response.message}}const K=async(r,e,t)=>{const n=await r.send(e);if(ui(n))throw new bn(n);if(!li(n,t)){const o=t.safeParse(n);throw o.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",t,"Actual:",n),o.error)}return n},li=(r,e)=>e.safeParse(r).success,ui=r=>$a.safeParse(r).success,di=async(r,e)=>await K(r,{type:"get_checkout_preview",payload:e},yn),z=async r=>await K(r,{type:"get_prefill",payload:{}},gn),et=async(r,e)=>await K(r,{type:"v2_start_payment_flow",payload:e},wn),pi=async(r,e)=>await K(r,{type:"start_payment_flow_for_cc",payload:e},ti),fi=async(r,e)=>await K(r,{type:"start_payment_flow_for_pr",payload:e},wn),se=async(r,e)=>await K(r,{type:"confirm_payment_flow",payload:e},ta),hi=async(r,e)=>await K(r,{type:"finalize_setup_payment_method",payload:e},vn),mi=async(r,e)=>await K(r,{type:"check_if_popup_window_verified",payload:e},ea),yi=async(r,e,t)=>{const n=await di(r,{secure_token:e,promotion_code:t}),o=new Set(n.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(n.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:s,amountAtom:i}},tt=async(r,e,t,n)=>{if(t)return{amountAtom:0,currency:"usd"};{n=n||void 0;const o=await yi(r,e,n);return{amountAtom:o.amountAtom,currency:o.currency}}},_i=async(r,e)=>{if(r.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(r.values()).map(n=>K(n,{type:"tokenize_card",payload:e},Js)))},kn=async(r,e)=>{try{return await K(r,{type:"checkout_card_elements",payload:e},gr)}catch(t){throw console.error("[cde-client] Error during checkoutCardElements:",t,JSON.stringify(t)),t}},gi=async(r,e)=>await K(r,{type:"setup_payment_method",payload:e},vn),Er=async(r,e)=>await K(r,{type:"checkout",payload:e},gr),En=1e3,vi=async(r,e)=>{console.log(e);const n=await dn({iframe:r,debug:!0,timeout:En,childOrigin:"*"}).promise,o=await K(n,{type:"ping-3ds-status"},Qs);return console.log("🟢 CDE connection successful! Stopping polling... Result:",o),o},Cn=async(r,e)=>await K(r,{type:"prepare_payment_flow",payload:e},ni),Sn=async(r,e)=>{try{return(await K(r,{type:"get_standardized_error_code",payload:{message:e}},ri)).error_code}catch(t){return console.error("[cde-client] Error during getStandardizedErrorCode:",fe(t)),"PAYMENT_FAILED_GENERIC"}};function Yt(r){throw new Error(`Unhandled case: ${r}`)}const Cr=10,Pn=(r=0)=>e=>`\x1B[${e+r}m`,An=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,xn=(r=0)=>(e,t,n)=>`\x1B[${38+r};2;${e};${t};${n}m`,O={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(O.modifier);const wi=Object.keys(O.color),bi=Object.keys(O.bgColor);[...wi,...bi];function ki(){const r=new Map;for(const[e,t]of Object.entries(O)){for(const[n,o]of Object.entries(t))O[n]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},t[n]=O[n],r.set(o[0],o[1]);Object.defineProperty(O,e,{value:t,enumerable:!1})}return Object.defineProperty(O,"codes",{value:r,enumerable:!1}),O.color.close="\x1B[39m",O.bgColor.close="\x1B[49m",O.color.ansi=Pn(),O.color.ansi256=An(),O.color.ansi16m=xn(),O.bgColor.ansi=Pn(Cr),O.bgColor.ansi256=An(Cr),O.bgColor.ansi16m=xn(Cr),Object.defineProperties(O,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(s=>s+s).join(""));const o=Number.parseInt(n,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:e=>O.rgbToAnsi256(...O.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,o;if(e>=232)t=((e-232)*10+8)/255,n=t,o=t;else{e-=16;const c=e%36;t=Math.floor(e/36)/5,n=Math.floor(c/6)/5,o=c%6/5}const s=Math.max(t,n,o)*2;if(s===0)return 30;let i=30+(Math.round(o)<<2|Math.round(n)<<1|Math.round(t));return s===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>O.ansi256ToAnsi(O.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>O.ansi256ToAnsi(O.hexToAnsi256(e)),enumerable:!1}}),O}const ye=ki(),Wt=(()=>{if(navigator.userAgentData){const r=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(r&&r.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),In=Wt!==0&&{level:Wt,hasBasic:!0,has256:Wt>=2,has16m:Wt>=3},Ei={stdout:In,stderr:In};function Ci(r,e,t){let n=r.indexOf(e);if(n===-1)return r;const o=e.length;let s=0,i="";do i+=r.slice(s,n)+e+t,s=n+o,n=r.indexOf(e,s);while(n!==-1);return i+=r.slice(s),i}function Si(r,e,t,n){let o=0,s="";do{const i=r[n-1]==="\r";s+=r.slice(o,i?n-1:n)+e+(i?`\r
7
7
  `:`
8
8
  `)+t,o=n+1,n=r.indexOf(`
9
- `,o)}while(n!==-1);return s+=r.slice(o),s}const{stdout:An,stderr:xn}=_i,wr=Symbol("GENERATOR"),Qe=Symbol("STYLER"),Pt=Symbol("IS_EMPTY"),Tn=["ansi","ansi","ansi256","ansi16m"],Xe=Object.create(null),wi=(r,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 t=An?An.level:0;r.level=e.level===void 0?t:e.level},bi=r=>{const e=(...t)=>t.join(" ");return wi(e,r),Object.setPrototypeOf(e,At.prototype),e};function At(r){return bi(r)}Object.setPrototypeOf(At.prototype,Function.prototype);for(const[r,e]of Object.entries(fe))Xe[r]={get(){const t=Gt(this,kr(e.open,e.close,this[Qe]),this[Pt]);return Object.defineProperty(this,r,{value:t}),t}};Xe.visible={get(){const r=Gt(this,this[Qe],!0);return Object.defineProperty(this,"visible",{value:r}),r}};const br=(r,e,t,...n)=>r==="rgb"?e==="ansi16m"?fe[t].ansi16m(...n):e==="ansi256"?fe[t].ansi256(fe.rgbToAnsi256(...n)):fe[t].ansi(fe.rgbToAnsi(...n)):r==="hex"?br("rgb",e,t,...fe.hexToRgb(...n)):fe[t][r](...n),ki=["rgb","hex","ansi256"];for(const r of ki){Xe[r]={get(){const{level:t}=this;return function(...n){const o=kr(br(r,Tn[t],"color",...n),fe.color.close,this[Qe]);return Gt(this,o,this[Pt])}}};const e="bg"+r[0].toUpperCase()+r.slice(1);Xe[e]={get(){const{level:t}=this;return function(...n){const o=kr(br(r,Tn[t],"bgColor",...n),fe.bgColor.close,this[Qe]);return Gt(this,o,this[Pt])}}}}const Ei=Object.defineProperties(()=>{},{...Xe,level:{enumerable:!0,get(){return this[wr].level},set(r){this[wr].level=r}}}),kr=(r,e,t)=>{let n,o;return t===void 0?(n=r,o=e):(n=t.openAll+r,o=e+t.closeAll),{open:r,close:e,openAll:n,closeAll:o,parent:t}},Gt=(r,e,t)=>{const n=(...o)=>Ci(n,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(n,Ei),n[wr]=r,n[Qe]=e,n[Pt]=t,n},Ci=(r,e)=>{if(r.level<=0||!e)return r[Pt]?"":e;let t=r[Qe];if(t===void 0)return e;const{openAll:n,closeAll:o}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=gi(e,t.close,t.open),t=t.parent;const s=e.indexOf(`
10
- `);return s!==-1&&(e=vi(e,o,n,s)),n+e+o};Object.defineProperties(At.prototype,Xe);const Bt=At();At({level:xn?xn.level:0});const Oe=r=>async e=>{var t,n;try{(n=(t=e.formCallbacks.get).onCheckoutStarted)==null||n.call(t);const o=await r(e);if(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);else throw new Error(`Unhandled mode: ${o}`)}catch(o){const s=ue(o),i=await kn(e.context.anyCdeConnection,s);e.formCallbacks.get.onCheckoutError(s,i)}},et=r=>async e=>{try{return await r(e)}catch(t){const{err__:n}=U("init-error-catcher"),o=ue(t),s=await kn(e.context.anyCdeConnection,o);return n(s,o,t),{isAvailable:!1,reason:o,errorCode:s}}},U=r=>{const e=(...n)=>{window.console.log(`${Bt.green.bold("ojs/")}${Bt.bold.gray(`${r}`)} `,...n)},t=(...n)=>{window.console.warn(`${Bt.red.bold("ojs/")}${Bt.bold.gray(`${r}`)} `,...n)};return{log:e,err:t,log__:e,err__:t}},{log__:Ll,err__:Si}=U("common"),qt=r=>{if(r.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${r.payment_methods.length}`);return{payment_method_id:r.payment_methods[0].id}},he=(r,e)=>{const t=r.find(n=>e.safeParse(n).success);if(!t)throw Si("No CPMs found for model. All models:",r),new Error("No CPMs found for model");return e.parse(t)},Pi=r=>({new_customer_email:r.email,new_customer_address:{zip_code:r.zipCode,country:r.country},new_customer_first_name:r.firstName,new_customer_last_name:r.lastName}),Yt=async r=>{const{log__:e}=U(r.logPrefix),t=await W(r.anyCdeConnection),n=qt(r.confirmResult);if(t.mode==="setup")return e("Setting up payment method..."),{mode:"setup",result:await ci(r.anyCdeConnection,{secure_token:t.token,pm_id:n.payment_method_id})};{e("Doing checkout...");const o={secure_token:t.token,payment_input:{provider_type:r.checkoutPaymentMethod.provider},customer_email:r.requiredFormFields[m.EMAIL],customer_zip_code:r.requiredFormFields[m.ZIP_CODE],customer_country:r.requiredFormFields[m.COUNTRY],promotion_code:r.requiredFormFields[m.PROMOTION_CODE],line_items:t.line_items,total_amount_atom:t.amount_total_atom,cancel_at_end:!1,checkout_payment_method:r.checkoutPaymentMethod,use_confirmed_pm_id:n.payment_method_id};return{mode:"checkout",result:await _r(r.anyCdeConnection,o)}}},{log__:In,err__:Rn}=U("common-cc"),Ne=(r,e,t)=>{if(t){In(`Received default field values: ${JSON.stringify(t)}`);for(const[o,s]of Object.entries(t))r[o]||(r[o]=s)}const n=Et.safeParse(r);if(!n.success){const o=n.error.format(),s=Hs(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw Rn("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return n.data},Ai=(r,e)=>{for(const t of r)if(t.success===!1)throw t.errors.forEach(n=>{const o=Jr.safeParse(n.elementType);if(!o.success)Rn(`Unknown field name in onValidationError: ${n.elementType}. Error object:`,n);else{const s=o.data;e(s,n.errors)}}),In(`Error tokenizing card: got validation errors: ${JSON.stringify(t.errors)}`),new Error("Got validation errors while tokenizing card")},On="ojs-stripe-link-btn",{log__:Z,err__:xi}=U("stripe-link"),Ti=a.object({provider:a.literal("stripe_link"),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),Ii=a.array(a.object({our_existing_pm_id:a.string()})).length(1),Ri=et(async({context:r,formCallbacks:e})=>{const t=r.customInitParams.stripeLink;Z("Checking if there are any CPMs for Stripe Link...");const n=he(r.checkoutPaymentMethods,Ti);Z("Starting stripe link flow...");const o=r.anyCdeConnection,s=await W(o),i=s.mode==="setup";Z("Creating stripe elements...");const c=await Je(o,s.token,i,void 0),{elements:l,stripe:u}=await ea(n.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});Z("Creating express checkout...");const d=l.create("expressCheckout",{buttonHeight:t==null?void 0:t.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),f=()=>{d.mount(`#${On}`)},_=()=>{d.unmount()};return t!=null&&t.doNotMountOnInit?Z("NOT mounting stripe link button (doNotMountOnInit is true)"):(Z("Mounting stripe link button..."),f()),d.on("click",async p=>{if(Z("Stripe Link button clicked"),t!=null&&t.overrideLinkSubmit&&!await t.overrideLinkSubmit()){Z("Stripe Link submit aborted by overrideLinkSubmit");return}p.resolve()}),d.on("confirm",async p=>{Z("Stripe Link window confirmed",p);const y=await u.createPaymentMethod({elements:l,params:{billing_details:p.billingDetails}});y.error?(xi("error",y.error),e.get.onCheckoutError(y.error.message??"Stripe Link unknown error")):(Z("paymentMethod",y.paymentMethod),B.stripeLink.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:be(r.formDiv),formCallbacks:e,customParams:{stripePM:y.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:f,dismountButton:_,waitForButtonToMount:async()=>await Mi(On)}}}),Oi=Oe(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{Z("Running Stripe Link flow...");const s=r.anyCdeConnection;Z("Merging PM fields with form fields...");const i=Ni(t,o.stripePM),c=Ne(i,n.get.onValidationError);Z("Starting payment flow...");const l=await St(s,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:o.stripePM.id,new_customer_email:c[m.EMAIL],new_customer_first_name:c[m.FIRST_NAME],new_customer_last_name:c[m.LAST_NAME],new_customer_address:{zip_code:c[m.ZIP_CODE],country:c[m.COUNTRY]}});Z("Start payment flow response",l);const d=Ii.parse(l.required_user_actions)[0].our_existing_pm_id,f=await W(s);if(f.mode==="setup"){Z("Doing payment setup...");const _=await pe(s,{secure_token:f.token,existing_cc_pm_id:d});return{mode:"setup",result:qt(_)}}else{Z("Doing checkout...");const _={secure_token:f.token,payment_input:{provider_type:e.provider},customer_email:c[m.EMAIL],customer_zip_code:c[m.ZIP_CODE],customer_country:c[m.COUNTRY],promotion_code:c[m.PROMOTION_CODE],line_items:f.line_items,total_amount_atom:f.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await _r(s,_)}}}),Ni=(r,e)=>{var i,c,l,u,d;const t={...r},[n,...o]=((c=(i=e.billing_details.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],s=o.join(" ")||void 0;return t[m.FIRST_NAME]=t[m.FIRST_NAME]||n||"_OP_UNKNOWN",t[m.LAST_NAME]=t[m.LAST_NAME]||s||"_OP_UNKNOWN",t[m.EMAIL]=t[m.EMAIL]||((l=e.link)==null?void 0:l.email)||e.billing_details.email||"op_unfilled@getopenpay.com",t[m.ZIP_CODE]=t[m.ZIP_CODE]||((u=e.billing_details.address)==null?void 0:u.postal_code)||"00000",t[m.COUNTRY]=t[m.COUNTRY]||((d=e.billing_details.address)==null?void 0:d.country)||"US",Z("Final form inputs:",t),t},Mi=r=>new Promise(e=>{const t=()=>{const n=document.getElementById(r);n?e(n):requestAnimationFrame(t)};t()}),Di="@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{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}",ji=r=>{const e=document.createElement("template");e.innerHTML=`
9
+ `,o)}while(n!==-1);return s+=r.slice(o),s}const{stdout:Tn,stderr:Rn}=Ei,Sr=Symbol("GENERATOR"),rt=Symbol("STYLER"),At=Symbol("IS_EMPTY"),On=["ansi","ansi","ansi256","ansi16m"],nt=Object.create(null),Pi=(r,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 t=Tn?Tn.level:0;r.level=e.level===void 0?t:e.level},Ai=r=>{const e=(...t)=>t.join(" ");return Pi(e,r),Object.setPrototypeOf(e,xt.prototype),e};function xt(r){return Ai(r)}Object.setPrototypeOf(xt.prototype,Function.prototype);for(const[r,e]of Object.entries(ye))nt[r]={get(){const t=Kt(this,Ar(e.open,e.close,this[rt]),this[At]);return Object.defineProperty(this,r,{value:t}),t}};nt.visible={get(){const r=Kt(this,this[rt],!0);return Object.defineProperty(this,"visible",{value:r}),r}};const Pr=(r,e,t,...n)=>r==="rgb"?e==="ansi16m"?ye[t].ansi16m(...n):e==="ansi256"?ye[t].ansi256(ye.rgbToAnsi256(...n)):ye[t].ansi(ye.rgbToAnsi(...n)):r==="hex"?Pr("rgb",e,t,...ye.hexToRgb(...n)):ye[t][r](...n),xi=["rgb","hex","ansi256"];for(const r of xi){nt[r]={get(){const{level:t}=this;return function(...n){const o=Ar(Pr(r,On[t],"color",...n),ye.color.close,this[rt]);return Kt(this,o,this[At])}}};const e="bg"+r[0].toUpperCase()+r.slice(1);nt[e]={get(){const{level:t}=this;return function(...n){const o=Ar(Pr(r,On[t],"bgColor",...n),ye.bgColor.close,this[rt]);return Kt(this,o,this[At])}}}}const Ii=Object.defineProperties(()=>{},{...nt,level:{enumerable:!0,get(){return this[Sr].level},set(r){this[Sr].level=r}}}),Ar=(r,e,t)=>{let n,o;return t===void 0?(n=r,o=e):(n=t.openAll+r,o=e+t.closeAll),{open:r,close:e,openAll:n,closeAll:o,parent:t}},Kt=(r,e,t)=>{const n=(...o)=>Ti(n,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(n,Ii),n[Sr]=r,n[rt]=e,n[At]=t,n},Ti=(r,e)=>{if(r.level<=0||!e)return r[At]?"":e;let t=r[rt];if(t===void 0)return e;const{openAll:n,closeAll:o}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Ci(e,t.close,t.open),t=t.parent;const s=e.indexOf(`
10
+ `);return s!==-1&&(e=Si(e,o,n,s)),n+e+o};Object.defineProperties(xt.prototype,nt);const Ht=xt();xt({level:Rn?Rn.level:0});const Ee=r=>async e=>{var t,n;try{(n=(t=e.formCallbacks.get).onCheckoutStarted)==null||n.call(t);const o=await r(e);if(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);else throw new Error(`Unhandled mode: ${o}`)}catch(o){const s=fe(o),i=await Sn(e.context.anyCdeConnection,s);e.formCallbacks.get.onCheckoutError(s,i)}},Ze=r=>async e=>{try{return await r(e)}catch(t){const{err__:n}=L("init-error-catcher"),o=fe(t),s=await Sn(e.context.anyCdeConnection,o);return n(s,o,t),{isAvailable:!1,reason:o,errorCode:s}}},L=r=>{const e=(...n)=>{window.console.log(`${Ht.green.bold("ojs/")}${Ht.bold.gray(`${r}`)} `,...n)},t=(...n)=>{window.console.warn(`${Ht.red.bold("ojs/")}${Ht.bold.gray(`${r}`)} `,...n)};return{log:e,err:t,log__:e,err__:t}},{log__:ru,err__:Ri}=L("common"),It=r=>{if(r.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${r.payment_methods.length}`);return{payment_method_id:r.payment_methods[0].id}},ae=(r,e)=>{const t=r.find(n=>e.safeParse(n).success);if(!t)throw Ri("No CPMs found for model. All models:",r),new Error("No CPMs found for model");return e.parse(t)},Oi=r=>({new_customer_email:r.email,new_customer_address:{zip_code:r.zipCode,country:r.country},new_customer_first_name:r.firstName,new_customer_last_name:r.lastName}),Jt=async r=>{const{log__:e}=L(r.logPrefix),t=await z(r.anyCdeConnection),n=It(r.confirmResult);if(t.mode==="setup")return e("Setting up payment method..."),{mode:"setup",result:await hi(r.anyCdeConnection,{secure_token:t.token,pm_id:n.payment_method_id})};{e("Doing checkout...");const o={secure_token:t.token,payment_input:{provider_type:r.checkoutPaymentMethod.provider},customer_email:r.requiredFormFields[y.EMAIL],customer_zip_code:r.requiredFormFields[y.ZIP_CODE],customer_country:r.requiredFormFields[y.COUNTRY],promotion_code:r.requiredFormFields[y.PROMOTION_CODE],line_items:t.line_items,total_amount_atom:t.amount_total_atom,cancel_at_end:!1,checkout_payment_method:r.checkoutPaymentMethod,use_confirmed_pm_id:n.payment_method_id};return{mode:"checkout",result:await Er(r.anyCdeConnection,o)}}},{log__:Nn,err__:Mn}=L("common-cc"),Me=(r,e,t)=>{if(t){Nn(`Received default field values: ${JSON.stringify(t)}`);for(const[o,s]of Object.entries(t))r[o]||(r[o]=s)}const n=St.safeParse(r);if(!n.success){const o=n.error.format(),s=ra(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw Mn("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return n.data},Ni=(r,e)=>{for(const t of r)if(t.success===!1)throw t.errors.forEach(n=>{const o=rn.safeParse(n.elementType);if(!o.success)Mn(`Unknown field name in onValidationError: ${n.elementType}. Error object:`,n);else{const s=o.data;e(s,n.errors)}}),Nn(`Error tokenizing card: got validation errors: ${JSON.stringify(t.errors)}`),new Error("Got validation errors while tokenizing card")},Dn="ojs-stripe-link-btn",{log__:G,err__:Mi}=L("stripe-link"),Di=a.object({provider:a.literal("stripe_link"),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),ji=a.array(a.object({our_existing_pm_id:a.string()})).length(1),Li=Ze(async({context:r,formCallbacks:e})=>{const t=r.customInitParams.stripeLink;G("Checking if there are any CPMs for Stripe Link...");const n=ae(r.checkoutPaymentMethods,Di);G("Starting stripe link flow...");const o=r.anyCdeConnection,s=await z(o),i=s.mode==="setup";G("Creating stripe elements...");const c=await tt(o,s.token,i,void 0),{elements:l,stripe:u}=await aa(n.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});G("Creating express checkout...");const d=l.create("expressCheckout",{buttonHeight:t==null?void 0:t.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),p=()=>{d.mount(`#${Dn}`)},_=()=>{d.unmount()};return t!=null&&t.doNotMountOnInit?G("NOT mounting stripe link button (doNotMountOnInit is true)"):(G("Mounting stripe link button..."),p()),d.on("click",async f=>{if(G("Stripe Link button clicked"),t!=null&&t.overrideLinkSubmit&&!await t.overrideLinkSubmit()){G("Stripe Link submit aborted by overrideLinkSubmit");return}f.resolve()}),d.on("confirm",async f=>{G("Stripe Link window confirmed",f);const h=await u.createPaymentMethod({elements:l,params:{billing_details:f.billingDetails}});h.error?(Mi("error",h.error),e.get.onCheckoutError(h.error.message??"Stripe Link unknown error")):(G("paymentMethod",h.paymentMethod),Z.stripeLink.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:he(r.formDiv),formCallbacks:e,customParams:{stripePM:h.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:p,dismountButton:_,waitForButtonToMount:async()=>await $i(Dn)}}}),Fi=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{G("Running Stripe Link flow...");const s=r.anyCdeConnection;G("Merging PM fields with form fields...");const i=Ui(t,o.stripePM),c=Me(i,n.get.onValidationError);G("Starting payment flow...");const l=await et(s,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:o.stripePM.id,new_customer_email:c[y.EMAIL],new_customer_first_name:c[y.FIRST_NAME],new_customer_last_name:c[y.LAST_NAME],new_customer_address:{zip_code:c[y.ZIP_CODE],country:c[y.COUNTRY]}});G("Start payment flow response",l);const d=ji.parse(l.required_user_actions)[0].our_existing_pm_id,p=await z(s);if(p.mode==="setup"){G("Doing payment setup...");const _=await se(s,{secure_token:p.token,existing_cc_pm_id:d});return{mode:"setup",result:It(_)}}else{G("Doing checkout...");const _={secure_token:p.token,payment_input:{provider_type:e.provider},customer_email:c[y.EMAIL],customer_zip_code:c[y.ZIP_CODE],customer_country:c[y.COUNTRY],promotion_code:c[y.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 Er(s,_)}}}),Ui=(r,e)=>{var i,c,l,u,d;const t={...r},[n,...o]=((c=(i=e.billing_details.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],s=o.join(" ")||void 0;return t[y.FIRST_NAME]=t[y.FIRST_NAME]||n||"_OP_UNKNOWN",t[y.LAST_NAME]=t[y.LAST_NAME]||s||"_OP_UNKNOWN",t[y.EMAIL]=t[y.EMAIL]||((l=e.link)==null?void 0:l.email)||e.billing_details.email||"op_unfilled@getopenpay.com",t[y.ZIP_CODE]=t[y.ZIP_CODE]||((u=e.billing_details.address)==null?void 0:u.postal_code)||"00000",t[y.COUNTRY]=t[y.COUNTRY]||((d=e.billing_details.address)==null?void 0:d.country)||"US",G("Final form inputs:",t),t},$i=r=>new Promise(e=>{const t=()=>{const n=document.getElementById(r);n?e(n):requestAnimationFrame(t)};t()}),Zi="@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}",jn=r=>{const e=document.createElement("template");e.innerHTML=`
11
11
  <style>
12
- ${Di}
12
+ ${Zi}
13
13
  </style>
14
14
  <div class="overlay">
15
15
  <div class="container">
@@ -17,9 +17,9 @@ ${r.message}`),r.message)}else return fr(r.message);if(typeof r=="object")try{re
17
17
  <iframe src="${r}" class="frame" id="three-ds-iframe" title="3D Secure verification" allow="payment"></iframe>
18
18
  </div>
19
19
  </div>
20
- `;const t=document.createElement("div"),n=t.attachShadow({mode:"open"});n.appendChild(e.content.cloneNode(!0));const o=n.querySelector("#three-ds-iframe"),s=n.querySelector(".cancel-button");return document.body.appendChild(t),{host:t,iframe:o,cancelButton:s}};function Li(r,e,t){const n=async()=>{try{const s=await fi(r,t);s&&(clearInterval(o),e(s))}catch{}};n();const o=setInterval(n,wn);return o}function Fi({elements:r,pollingInterval:e,resolve:t}){const n=()=>{clearInterval(e),r.host.remove(),t({status:ne.CANCELLED})};return r.cancelButton.addEventListener("click",n),()=>{r.cancelButton.removeEventListener("click",n)}}async function Wt(r){const{url:e,baseUrl:t}=r,n=ji(e);return new Promise(o=>{const s=l=>{setTimeout(()=>{n.host.remove()},1e3),o(l),c==null||c()},i=Li(n.iframe,s,new URL(t).origin),c=Fi({elements:n,pollingInterval:i,resolve:o})})}const Nn=async r=>{const e=await Wt(r);if(e.status===ne.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===ne.FAILURE)throw new Error("3DS verification failed");return e.status!==ne.SUCCESS&&gr(e.status),{href:e.href}},Ui=(r,e)=>{const t=window.open(e,"_blank");if(!t)throw new Error(`${r} popup window blocked. Please allow popups for this site.`);return t},$i=async(r,e,t,n)=>{const{err__:o}=U("popup-verify");return new Promise((s,i)=>{const c=Ui(r,n),l=setInterval(async()=>{try{const u=await li(e,t);if(u.present)clearInterval(l),c.close(),s({href:u.href});else if(c.closed)throw new Error(`${r} payment cancelled`)}catch(u){o(ue(u)),clearInterval(l),i(ue(u))}},1e3)})},{log__:Zi,err__:Mn}=U("pockyt-cc"),Vi=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),zi=r=>{const e=Vi.safeParse(r);if(!e.success){const t="Unable to process your credit card. Please contact support for assistance.",n=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`;throw Mn(n),new Error(t)}return e.data},Dn=r=>{try{const e=new URL(r??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return Zi(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const t="Error verifying 3DS verification result.";throw Mn(t,`Resulting URL: ${r}.
21
- Error: ${ue(e)}`),new Error(t)}},Gi=(r,e)=>new URL(r).searchParams.get(e),Bi=r=>(r==null?void 0:r["op-pockyt-3ds-url"])!==void 0,qi=async(r,e)=>{const t=zi(e),n=await Nn({url:t["op-pockyt-3ds-url"],baseUrl:r});return{existing_cc:{vault_id:Dn(n.href??""),transaction_no:t["op-pockyt-txn-no"],reference_no:t["op-pockyt-ref-no"]}}},{log__:Yi,err__:Er}=U("airwallex-cc"),Wi=a.object({"op-airwallex-3ds-url":a.string(),"op-airwallex-initial-intent-id":a.string(),"op-airwallex-consent-id":a.string()}),Ki=r=>{const e=Wi.safeParse(r);if(!e.success){const t="Unable to process your credit card. Please contact support for assistance.",n=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`;throw Er(n),new Error(t)}return e.data},Hi=r=>(r==null?void 0:r["op-airwallex-3ds-url"])!==void 0,Ji=r=>{try{const e=new URL(r??"").searchParams.get("payment_intent_id");if(!e)throw new Error("No intent ID found in Airwallex 3DS verification result");return Yi(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const t="Error verifying Airwallex 3DS verification result.";throw Er(t,`Resulting URL: ${r}.
22
- Error: ${ue(e)}`),new Error(t)}},Qi=async(r,e)=>{const t=Ki(e),n=await Nn({url:t["op-airwallex-3ds-url"],baseUrl:r}),o=Ji(n.href??""),s=t["op-airwallex-initial-intent-id"];if(s!==o){const c="Unable to process your credit card. Please contact support for assistance.",l=`Intent ID from callback (${o}) does not match the initial intent ID (${s}).`;throw Er(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:t["op-airwallex-consent-id"]}}},jn=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()})}),Ln=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__:M,err__:Fn}=U("common-cc"),{log__:Un}=U("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const Xi=Oe(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var u;M("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=r.anyCdeConnection,i=await W(s);M(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=Ne(t,n.get.onValidationError),l={session_id:r.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{}};try{M(`├ Tokenizing card info in CDE [Session: ${r.elementsSessionId}]`);const d=await di(o.currentCdeConnections,{session_id:r.elementsSessionId});if(Ai(d,n.get.onValidationError),i.mode==="setup"){M(`├ Setting up payment method in CDE [Token: ${i.token}]`);const f=await pi(s,l);return M(`╰ Setup completed successfully [PM ID: ${f.payment_method_id}]`),{mode:"setup",result:f}}else{M(`├ Initial checkout flow. Checking out card info in CDE [Session: ${r.elementsSessionId}]`);const f=await vn(s,l);return M("╰ Checkout completed successfully."),{mode:"checkout",result:f}}}catch(d){if(d instanceof gn&&d.originalErrorMessage.includes("3DS_REQUIRED")){M("├ Card requires 3DS, starting non-legacy payment flow"),M("Received 3DS error response headers:",d.response.headers);const f=Bi(d.response.headers);if(f){M("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const C=await qi(r.baseUrl,d.response.headers);l.extra_metadata.pockyt=C}if(Hi(d.response.headers)){M("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const C=await Qi(r.baseUrl,d.response.headers);l.extra_metadata.airwallex=C}const p=await ai(s,l);M("├ Payment flow result:",p);const y=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";f?M("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):y?(M("├ Using stripe 3DS flow"),await nc(p)):(M("├ Using common 3DS flow"),await rc(p,r.baseUrl));const w=p.cc_pm_id;if(i.mode==="setup"){M(`├ Confirming payment flow [cc_pm_id: ${w}]`);const C=await pe(s,{secure_token:i.token,existing_cc_pm_id:w});M("├ Confirm payment flow result received Result:",C);const I=qt(C);return M(`╰ Setup completed successfully [PM ID: ${I.payment_method_id}]`),{mode:"setup",result:I}}else{M(`├ Checking out after 3DS flow [Flow: ${y?"legacy":"new"}]`);const C=await vn(s,{...l,existing_cc_pm_id:w,do_not_use_legacy_cc_flow:y});return M("╰ Checkout completed successfully."),{mode:"checkout",result:C}}}throw Fn("╰ Error checking out card info in CDE"),Fn(d),d}}),ec=r=>{const e=r.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Js.parse(e)},tc=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");if(!e)throw new Error("No common 3DS action found");return Ys.parse(e)},rc=async(r,e)=>{const t=tc(r);if(t.type==="airwallex_payment_consent"&&t.redirect_url==="3DS_COMPLETE"){M("├ Airwallex 3DS flow completed successfully");return}M(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const{status:n}=await Wt({url:t.redirect_url,baseUrl:e});if(M(`╰ 3DS verification completed [Status: ${n}]`),n===ne.CANCELLED)throw new Error("3DS verification cancelled");if(n===ne.FAILURE)throw new Error("3DS verification failed")},nc=async r=>{const e=ec(r);Un(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await oa(e),Un("╰ Stripe 3DS flow completed successfully")},oe=a.enum(["stripe","airwallex","authorize_net"]);oe.Enum.stripe;const{log__:K,err__:oc}=U("stripe-pr"),sc=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()})}),ac=et(async({context:r,formCallbacks:e})=>{K("Checking if there are any CPMs for Stripe PR...");const t=he(r.checkoutPaymentMethods,sc);K("Initializing Stripe PR flow...");const n=r.anyCdeConnection,o=await W(n),s=o.mode==="setup";K("Getting initial preview amount");const i=await Je(n,o.token,s,void 0),c=await ta(t.metadata.stripe_pk,i.amountAtom,i.currency,s);K("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return oc("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};K("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,f)=>B.stripePR.run({context:r,checkoutPaymentMethod:Qt(r.checkoutPaymentMethods,d),nonCdeFormInputs:be(r.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:f==null?void 0:f.overridePaymentRequest},initResult:{processor:oe.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:oe.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),ic=Oe(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o,initResult:s})=>{if(K("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=r.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const y=o.overridePaymentRequest;K("Overriding PR amount with",y),lc(c,y.amount,y.pending,y.applePayPaymentRequest)}K("Showing PR dialog..."),c.show();const l=await ra(c);K("Stripe PM added event:",l),K("Merging PM fields with form fields...");const u=cc(t,l),d=Ne(u,n.get.onValidationError);K("PR dialog finished. Starting payment flow...",d);const f=await ii(i,{fields:d,checkoutPaymentMethod:e}),_=uc(f);K("Confirming PR with Stripe..."),await na(_,l);const p=await W(i);if(p.mode==="setup"){K("Confirming payment flow for setup...");const y=await pe(i,{secure_token:p.token});return{mode:"setup",result:qt(y)}}else{K("Performing checkout...");const y={secure_token:p.token,payment_input:{provider_type:e.provider},customer_first_name:d[m.FIRST_NAME],customer_last_name:d[m.LAST_NAME],customer_email:d[m.EMAIL],customer_zip_code:d[m.ZIP_CODE],customer_country:d[m.COUNTRY],promotion_code:d[m.PROMOTION_CODE],line_items:p.line_items,total_amount_atom:p.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await _r(i,y)}}}),cc=(r,e)=>{var l,u,d,f;const t={...r},[n,...o]=((u=(l=e.payerName)==null?void 0:l.trim())==null?void 0:u.split(/\s+/))??[],s=o.join(" ")||void 0,i=(f=(d=e.paymentMethod)==null?void 0:d.billing_details)==null?void 0:f.address,c=e.shippingAddress;return t[m.FIRST_NAME]=t[m.FIRST_NAME]||n||"_OP_UNKNOWN",t[m.LAST_NAME]=t[m.LAST_NAME]||s||"_OP_UNKNOWN",t[m.EMAIL]=t[m.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[m.ZIP_CODE]=t[m.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",t[m.COUNTRY]=t[m.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US",K("Final form inputs:",t),t},lc=(r,e,t,n)=>{r.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency,applePay:n})},uc=r=>{if(r.required_user_actions.length!==1)throw new Error(`Error occurred.
23
- Details: got ${r.required_user_actions.length} required user actions`);return Qs.parse(r.required_user_actions[0])},{log__:me,err__:$n}=U("pockyt-paypal"),dc=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 pc=Oe(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var F,_e;me("Running Pockyt Paypal flow...");const s=r.anyCdeConnection,i=await W(s);me("Verifying CPM...");const c=dc.parse(e);me("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=Ne(t,n.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=Pi(u);me(`Starting payment flow... Mode: ${i.mode}`);const f=rn(),_=i.mode!=="setup",p={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:_,pay_first_flow_cart_info:_?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((F=o==null?void 0:o.settings)!=null&&F.useRedirectFlow),frontend_token_for_redirect_flow:f},...d},y=new URL("/app/pre-action/start/",r.baseUrl).toString(),w=btoa(JSON.stringify(p)),C=new URLSearchParams({st:i.token,r:w}),I=`${y}?${C.toString()}`;if((_e=o==null?void 0:o.settings)!=null&&_e.useRedirectFlow)throw me("Starting redirect mode for PayPal..."),window.location.href=I,await Xr(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");me("Starting popup mode for PayPal..."),me("Opening paypal iframe...");const T=await $i("PayPal",s,f,I);me("Paypal flow result",T);const S=Dn(T.href),D=Gi(T.href,"catt");if(!D)throw $n("Checkout attempt ID not found in redirect URL:",T.href),new Error("Checkout attempt ID not found in redirect URL");me(`Confirming payment flow using vault ID ${S}`);const L=await pe(s,{secure_token:i.token,their_pm_id:S,checkout_attempt_id:_?D:void 0});if(me("Confirm payment flow result",L),i.mode==="setup")return{mode:"setup",result:{payment_method_id:L.payment_methods[0].id}};if(!L.pay_first_success_response)throw $n("Checkout failed, no pay-first success response:",L),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:L.pay_first_success_response}}),Kt=({gateway:r,gatewayMerchantId:e,merchantName:t,merchantId:n,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var f,_;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=(((_=s==null?void 0:s.amount)==null?void 0:_.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:r,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:n??"",merchantName:t},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?{...d,...s.googlePayPaymentRequest}:d},Zn=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://pay.google.com/gp/p/js/pay.js",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Google Pay SDK")),document.body.appendChild(t)});let Cr=null;const Vn=r=>r===De||r===window.location.origin?"PRODUCTION":"TEST",Ht=(r,e)=>{const t=Vn(r);return Cr===null&&(Cr=new window.google.payments.api.PaymentsClient({environment:t,merchantInfo:e.merchantInfo})),Cr},fc=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");return e?Qr.parse(e):null},zn=(r,e)=>{var o,s,i,c;const t={...r},n=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(n){const[l,...u]=((c=(i=n.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;t[m.EMAIL]=t[m.EMAIL]||e.email||"op_unfilled@getopenpay.com",t[m.COUNTRY]=t[m.COUNTRY]||n.countryCode||"US",t[m.ADDRESS]=t[m.ADDRESS]||n.address1||"",t[m.CITY]=t[m.CITY]||n.locality||"",t[m.ZIP_CODE]=t[m.ZIP_CODE]||n.postalCode||"00000",t[m.STATE]=t[m.STATE]||n.administrativeArea||"",t[m.FIRST_NAME]=t[m.FIRST_NAME]||l||"_OP_UNKNOWN",t[m.LAST_NAME]=t[m.LAST_NAME]||d||"_OP_UNKNOWN"}return t},{log__:se,err__:tt}=U("awx-google-pay"),hc=et(async({context:r,formCallbacks:e})=>{var f,_;const t={processor:oe.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=he(r.checkoutPaymentMethods,Ln);if(!n)return t;se("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return tt("No gateway merchant ID found in processor account"),t;if(se("Loading Google Pay SDK..."),await Zn(),!((_=(f=window.google)==null?void 0:f.payments)!=null&&_.api))return tt("Google Pay SDK not loaded properly"),t;if(Vn(r.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return tt("Google Pay merchant ID is required for production environment"),t;se("Google Pay SDK loaded",window.google.payments);try{const p=Kt({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:y}=await Ht(r.baseUrl,p).isReadyToPay(p);if(!y)return se("Google Pay is not available for this user"),t}catch(p){return tt("Error checking Google Pay availability",p),t}const i=r.anyCdeConnection,c=await W(i),l=c.mode==="setup",u=await Je(i,c.token,l,void 0),d=async p=>{try{B.airwallexGooglePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:be(r.formDiv),formCallbacks:e,initResult:void 0,customParams:{...p,initialPreview:u}})}catch(y){tt("Google Pay payment error",y),e.get.onCheckoutError((y==null?void 0:y.message)??"Unknown error")}};return{processor:oe.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),mc=Oe(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var f,_,p,y,w,C,I;se("Starting Google Pay flow...");const s=he(r.checkoutPaymentMethods,Ln),{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=Kt({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=Ht(r.baseUrl,u);try{const T=await d.loadPaymentData(u);se("Google Pay Payment data",T);const S=r.anyCdeConnection,D=await W(S),L=zn(t,T),F=Ne(L,n.get.onValidationError,o==null?void 0:o.defaultFieldValues),_e=(_=(f=T.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:_.token;if(!_e)throw new Error("No payment token received from Google Pay");const Rl=await St(S,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:F[m.EMAIL],new_customer_first_name:F[m.FIRST_NAME],new_customer_last_name:F[m.LAST_NAME],new_customer_address:{zip_code:F[m.ZIP_CODE],country:F[m.COUNTRY]}}),ar=fc(Rl);se("Start flow next actions",ar);let Ze=await pe(S,{secure_token:D.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:ar==null?void 0:ar.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:_e}}}});se("[1st] Confirm payment flow response",Ze);let Dr=(y=(p=Ze.payment_methods)==null?void 0:p[0])==null?void 0:y.id;const Ve=(w=Ze.required_user_actions)==null?void 0:w.find(Rt=>Rt.type==="airwallex_payment_consent");if(Ve&&Ve.redirect_url){se("3DS Required, starting verification...",Ve);const{status:Rt}=await Wt({url:Ve.redirect_url,baseUrl:r.baseUrl});if(se(`╰ 3DS verification completed [Status: ${Rt}]`),Rt===ne.CANCELLED)throw new Error("3DS verification cancelled");if(Rt===ne.FAILURE)throw new Error("3DS verification failed")}if(Ve&&!Dr&&(Ze=await pe(S,{secure_token:D.token,their_pm_id:Ve.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Ve.consent_id}}),se("[2nd] Confirm payment flow response",Ze),Dr=(I=(C=Ze.payment_methods)==null?void 0:C[0])==null?void 0:I.id),!Dr)throw new Error("No PM ID found");return Yt({logPrefix:"awx-googlepay",anyCdeConnection:S,checkoutPaymentMethod:e,requiredFormFields:F,confirmResult:Ze,usePayFirstFlow:!1})}catch(T){throw tt("Google Pay payment error",T),new Error((T==null?void 0:T.message)??"Unknown error")}}),Gn=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",t.crossOrigin="anonymous",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Apple Pay SDK")),document.body.appendChild(t)}),Bn=(r,e)=>{const t=e.token.paymentMethod.billingContact,n=e.billingContact,o=e.shippingContact,s={...r};return(t||n||o)&&(s[m.EMAIL]=s[m.EMAIL]||(t==null?void 0:t.emailAddress)||(n==null?void 0:n.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[m.COUNTRY]=s[m.COUNTRY]||(t==null?void 0:t.countryCode)||(n==null?void 0:n.countryCode)||(o==null?void 0:o.countryCode)||"US",s[m.ZIP_CODE]=s[m.ZIP_CODE]||(t==null?void 0:t.postalCode)||(n==null?void 0:n.postalCode)||(o==null?void 0:o.postalCode)||"00000",s[m.FIRST_NAME]=s[m.FIRST_NAME]||(t==null?void 0:t.givenName)||(n==null?void 0:n.givenName)||(o==null?void 0:o.givenName)||"_OP_UNKNOWN",s[m.LAST_NAME]=s[m.LAST_NAME]||(t==null?void 0:t.familyName)||(n==null?void 0:n.familyName)||(o==null?void 0:o.familyName)||"_OP_UNKNOWN"),s},yc=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")}),_c=r=>yc.safeParse(r).data,gc=r=>{const e=new AbortController;return window.addEventListener("message",t=>{var o;const n=_c(t);((o=n==null?void 0:n.data)==null?void 0:o.messageType)==="windowclosing"&&(r(),e.abort())},{signal:e.signal}),{cleanupCancelListener:()=>e.abort()}},qn=({total:r,prefill:e})=>{var n;if(e.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:r.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${e.token}`,De).toString()};const t=(n=e.line_items)==null?void 0:n[0];if(t)return{paymentDescription:(t==null?void 0:t.description)??"",regularBilling:{amount:r.amount,label:(t==null?void 0:t.description)??"",recurringPaymentIntervalUnit:t==null?void 0:t.billing_interval,recurringPaymentIntervalCount:(t==null?void 0:t.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},Yn=({overridePaymentRequest:r,initialPreview:e,prefill:t,defaultLabel:n="Total"})=>{var c,l;const o=(((c=r==null?void 0:r.amount)==null?void 0:c.currency)??(t==null?void 0:t.currency)??e.currency).toUpperCase(),i=((((l=r==null?void 0:r.amount)==null?void 0:l.amountAtom)??(e==null?void 0:e.amountAtom)??0)/100).toFixed(2);return{currencyCode:o,total:{label:(r==null?void 0:r.label)??n??"Total",type:r!=null&&r.pending?"pending":"final",amount:i}}},{log__:Jt}=U("awx-apple-pay");async function vc(r,e){try{const n=(await bn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:r.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o)}catch(t){throw e.session.abort(),t}}async function wc(r,e){if(!r.redirect_url)throw new Error("No redirect URL found");Jt("3DS Required, starting verification...",r);const{status:t}=await Wt({url:r.redirect_url,baseUrl:e.baseUrl});if(Jt(`╰ 3DS verification completed [Status: ${t}]`),t===ne.CANCELLED)throw new Error("3DS verification cancelled");if(t===ne.FAILURE)throw new Error("3DS verification failed");const n=await pe(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:r.their_pm_id,airwallex_consent_id:r.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return Jt("[2nd] Confirm payment flow response",n),n}async function bc(r,e){var t,n,o,s,i;try{const c=r.payment,l=Bn(e.nonCdeFormInputs,c),u=Ne(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues),_=(await St(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[m.EMAIL],new_customer_first_name:u[m.FIRST_NAME],new_customer_last_name:u[m.LAST_NAME],new_customer_address:{zip_code:u[m.ZIP_CODE],country:u[m.COUNTRY]}})).required_user_actions[0].consent_id;if(!_)throw new Error("No consent ID received from payment flow");let p=await pe(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:_,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});Jt("[1st] Confirm payment flow response",p);let y=(n=(t=p.payment_methods)==null?void 0:t[0])==null?void 0:n.id;const w=(o=p.required_user_actions)==null?void 0:o.find(I=>I.type==="airwallex_payment_consent");if(w!=null&&w.redirect_url&&w.consent_id&&w.their_pm_id&&(p=await wc(w,e),y=(i=(s=p.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!y)throw new Error("No PM ID found");const C={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(C),Yt({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__:rt,err__:Sr}=U("awx-apple-pay"),kc=et(async({context:r,formCallbacks:e})=>{const t={processor:oe.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=he(r.checkoutPaymentMethods,jn);if(!n)return t;rt("Loading Apple Pay SDK...");try{await Gn(),rt("Apple Pay SDK loaded successfully")}catch(f){return Sr("Failed to load Apple Pay SDK",f),t}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return rt("Apple Pay is not available on this device/browser"),t;if(rt("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return rt("No active cards available for Apple Pay"),t;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=r.anyCdeConnection,c=await W(i),l=c.mode==="setup",u=await Je(i,c.token,l,void 0),d=async f=>{try{await B.airwallexApplePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:be(r.formDiv),formCallbacks:e,customParams:{...f,initialPreview:u},initResult:void 0})}catch(_){Sr("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:oe.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Ec=Oe(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:o})=>{var C;const s=he(r.checkoutPaymentMethods,jn),{overridePaymentRequest:i,initialPreview:c}=n,l=r.anyCdeConnection,u=await W(l),d=u.mode==="setup",{currencyCode:f,total:_}=Yn({overridePaymentRequest:i,initialPreview:c,defaultLabel:(C=s==null?void 0:s.metadata)==null?void 0:C.processor_account_name}),p={countryCode:"US",currencyCode:f,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:_,recurringPaymentRequest:qn({total:_,prefill:u}),...(i==null?void 0:i.applePayPaymentRequest)??{}},y=new ApplePaySession(3,p),w={session:y,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:r.baseUrl,formCallbacks:o,defaultFieldValues:n==null?void 0:n.defaultFieldValues};return new Promise((I,T)=>{const S=()=>{rt("Payment cancelled by user"),T(new Error("Payment cancelled by user"))},{cleanupCancelListener:D}=gc(S);y.oncancel=S,y.onvalidatemerchant=async L=>{try{await vc(L,w)}catch(F){T(F)}},y.onpaymentmethodselected=()=>{const L={newTotal:{..._}};y.completePaymentMethodSelection(L)},y.onpaymentauthorized=async L=>{try{const F=await bc(L,w);D(),I(F)}catch(F){T(F)}},y.begin()}).catch(I=>{throw Sr("Apple Pay payment error",I),I})});async function Cc(r,e){try{const n=(await bn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:r.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o)}catch(t){throw e.session.abort(),t}}async function Sc(r,e){var t,n;try{const o=r.payment,s=Bn(e.nonCdeFormInputs,o),i=Ne(s,e.formCallbacks.get.onValidationError);await St(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[m.EMAIL],new_customer_first_name:i[m.FIRST_NAME],new_customer_last_name:i[m.LAST_NAME],new_customer_address:{zip_code:i[m.ZIP_CODE],country:i[m.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await pe(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((n=(t=l.payment_methods)==null?void 0:t[0])==null?void 0:n.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),Yt({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 Wn=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()})}),Kn=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()})}),{log__:xt,err__:Pr}=U("authnet-applepay"),Pc=et(async({context:r,formCallbacks:e})=>{const t={processor:oe.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=he(r.checkoutPaymentMethods,Wn);if(!n)return t;xt("Loading Apple Pay SDK...");try{await Gn(),xt("Apple Pay SDK loaded successfully")}catch(f){return Pr("Failed to load Apple Pay SDK",f),t}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return xt("Apple Pay is not available on this device/browser"),t;if(!await ApplePaySession.canMakePayments())return xt("No active cards available for Apple Pay"),t;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=r.anyCdeConnection,c=await W(i),l=c.mode==="setup",u=await Je(i,c.token,l,void 0),d=async f=>{try{await B.authorizeNetApplePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:be(r.formDiv),formCallbacks:e,customParams:{...f,initialPreview:u},initResult:void 0})}catch(_){Pr("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:oe.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),Ac=Oe(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:o})=>{var C;const{initialPreview:s,overridePaymentRequest:i}=n,c=he(r.checkoutPaymentMethods,Wn),{currencyCode:l,total:u}=Yn({overridePaymentRequest:i,initialPreview:s,defaultLabel:(C=c==null?void 0:c.metadata)==null?void 0:C.processor_account_name}),d=r.anyCdeConnection,f=await W(d),_=f.mode==="setup",p={countryCode:"US",currencyCode:l,total:u,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],recurringPaymentRequest:qn({total:u,prefill:f}),...(i==null?void 0:i.applePayPaymentRequest)??{}},y=new ApplePaySession(3,p),w={session:y,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:e.metadata,prefill:f,isSetupMode:_,baseUrl:r.baseUrl,formCallbacks:o};return new Promise((I,T)=>{y.oncancel=()=>{xt("Payment cancelled by user"),T(new Error("Payment cancelled by user"))},y.onvalidatemerchant=async S=>{try{await Cc(S,w)}catch(D){T(D)}},y.onpaymentmethodselected=()=>{const S={newTotal:p.total};y.completePaymentMethodSelection(S)},y.onpaymentauthorized=async S=>{try{const D=await Sc(S,w);I(D)}catch(D){T(D)}},y.begin()}).catch(I=>{throw Pr("Apple Pay payment error",I),I})}),{log__:$e,err__:Tt}=U("authnet-googlepay"),xc=et(async({context:r,formCallbacks:e})=>{var d,f;$e("Initializing Authnet GooglePay flow");const t={processor:oe.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=he(r.checkoutPaymentMethods,Kn);if(!n)return t;$e("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return Tt("No gateway merchant ID found in processor account"),t;if($e("Loading Google Pay SDK..."),await Zn(),!((f=(d=window.google)==null?void 0:d.payments)!=null&&f.api))return Tt("Google Pay SDK not loaded properly"),t;$e("Google Pay SDK loaded",window.google.payments);try{const _=Kt({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:p}=await Ht(r.baseUrl,_).isReadyToPay(_);if(!p)return $e("Google Pay is not available for this user"),t}catch(_){return Tt("Error checking Google Pay availability",_),t}const s=r.anyCdeConnection,i=await W(s),c=i.mode==="setup",l=await Je(s,i.token,c,void 0),u=async _=>{try{B.authorizeNetGooglePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:be(r.formDiv),formCallbacks:e,initResult:void 0,customParams:{..._,initialPreview:l}})}catch(p){Tt("Google Pay payment error",p),e.get.onCheckoutError((p==null?void 0:p.message)??"Unknown error")}};return{processor:oe.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),Tc=Oe(async({context:r,nonCdeFormInputs:e,checkoutPaymentMethod:t,formCallbacks:n,customParams:o})=>{var f,_,p,y;const{initialPreview:s,overridePaymentRequest:i}=o,l=he(r.checkoutPaymentMethods,Kn).metadata,u=Kt({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=Ht(r.baseUrl,u);try{const w=await d.loadPaymentData(u);$e("Google Pay Payment data",w);const C=r.anyCdeConnection,I=await W(C),T=zn(e,w),S=Ne(T,n.get.onValidationError),D=(_=(f=w.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:_.token;if(!D)throw new Error("No payment token received from Google Pay");const L=await St(C,{payment_provider:t.provider,checkout_payment_method:t,new_customer_email:S[m.EMAIL],new_customer_first_name:S[m.FIRST_NAME],new_customer_last_name:S[m.LAST_NAME],new_customer_address:{zip_code:S[m.ZIP_CODE],country:S[m.COUNTRY]}});$e("Start payment flow response",L);const F=await pe(C,{secure_token:I.token,processor_specific_metadata:{payment_provider:t.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(D)}}});if(!((y=(p=F.payment_methods)==null?void 0:p[0])==null?void 0:y.id))throw new Error("No PM ID found");return Yt({logPrefix:"authnet-googlepay",anyCdeConnection:C,checkoutPaymentMethod:t,requiredFormFields:S,confirmResult:F,usePayFirstFlow:!1})}catch(w){throw Tt("Google Pay payment error",w),new Error((w==null?void 0:w.message)??"Unknown error")}}),Qt=(r,e,t)=>{const n=r.filter(o=>{const s=t===void 0?!0:o.processor_name===t,i=o.provider===e;return s&&i});if(n.length===0)throw console.error("CPMs list",r),new Error(`No CPMs found with provider '${e}' and processor '${t}'`);if(n.length!==1)throw console.error("CPMs list",r),new Error(`More than one CPM found with provider '${e}' and processor '${t}'`);return n[0]},B={commonCC:{init:async()=>{},run:Xi},stripePR:{init:ac,run:ic},stripeLink:{init:Ri,run:Oi},pockytPaypal:{run:pc},airwallexGooglePay:{init:hc,run:mc},airwallexApplePay:{init:kc,run:Ec},authorizeNetApplePay:{init:Pc,run:Ac},authorizeNetGooglePay:{init:xc,run:Tc}};var Ar=function(r,e){return Ar=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])},Ar(r,e)};function Me(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Ar(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Ic(r,e,t,n){function o(s){return s instanceof t?s:new t(function(i){i(s)})}return new(t||(t=Promise))(function(s,i){function c(d){try{u(n.next(d))}catch(f){i(f)}}function l(d){try{u(n.throw(d))}catch(f){i(f)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((n=n.apply(r,e||[])).next())})}function Hn(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,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(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(t=0)),t;)try{if(n=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 t.label++,{value:u[1],done:!1};case 5:t.label++,o=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){t.label=u[1];break}if(u[0]===6&&t.label<s[1]){t.label=s[1],s=u;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(u);break}s[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(r,t)}catch(d){u=[6,d],o=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function nt(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Xt(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(c){i={error:c}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return s}function er(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return r.concat(s||Array.prototype.slice.call(e))}function ot(r){return this instanceof ot?(this.v=r,this):new ot(r)}function Rc(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,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(y){return Promise.resolve(y).then(p,f)}}function c(p,y){n[p]&&(o[p]=function(w){return new Promise(function(C,I){s.push([p,w,C,I])>1||l(p,w)})},y&&(o[p]=y(o[p])))}function l(p,y){try{u(n[p](y))}catch(w){_(s[0][3],w)}}function u(p){p.value instanceof ot?Promise.resolve(p.value.v).then(d,f):_(s[0][2],p)}function d(p){l("next",p)}function f(p){l("throw",p)}function _(p,y){p(y),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Oc(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof nt=="function"?nt(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=r[s]&&function(i){return new Promise(function(c,l){i=r[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 V(r){return typeof r=="function"}function tr(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var xr=tr(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
20
+ `;const t=document.createElement("div"),n=t.attachShadow({mode:"open"});n.appendChild(e.content.cloneNode(!0));const o=n.querySelector("#three-ds-iframe"),s=n.querySelector(".cancel-button");return document.body.appendChild(t),{host:t,iframe:o,cancelButton:s}};function Vi(r,e,t){const n=async()=>{try{const s=await vi(r,t);s&&(clearInterval(o),e(s))}catch{}};n();const o=setInterval(n,En);return o}function zi({elements:r,pollingInterval:e,resolve:t}){const n=()=>{clearInterval(e),r.host.remove(),t({status:$.CANCELLED})};return r.cancelButton.addEventListener("click",n),()=>{r.cancelButton.removeEventListener("click",n)}}async function Qt(r){const{url:e,baseUrl:t}=r,n=jn(e);return new Promise(o=>{const s=l=>{setTimeout(()=>{n.host.remove()},1e3),o(l),c==null||c()},i=Vi(n.iframe,s,new URL(t).origin),c=zi({elements:n,pollingInterval:i,resolve:o})})}const Ln=async r=>{const e=await Qt(r);if(e.status===$.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===$.FAILURE)throw new Error("3DS verification failed");return e.status!==$.SUCCESS&&Yt(e.status),{href:e.href}},Gi=(r,e)=>{const t=window.open(e,"_blank");if(!t)throw new Error(`${r} popup window blocked. Please allow popups for this site.`);return t},Bi=async(r,e,t,n)=>{const{err__:o}=L("popup-verify");return new Promise((s,i)=>{const c=Gi(r,n),l=setInterval(async()=>{try{const u=await mi(e,t);if(u.present)clearInterval(l),c.close(),s({href:u.href});else if(c.closed)throw new Error(`${r} payment cancelled`)}catch(u){o(fe(u)),clearInterval(l),i(fe(u))}},1e3)})},{log__:qi,err__:Fn}=L("pockyt-cc"),Yi=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),Wi=r=>{const e=Yi.safeParse(r);if(!e.success){const t="Unable to process your credit card. Please contact support for assistance.",n=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`;throw Fn(n),new Error(t)}return e.data},Un=r=>{try{const e=new URL(r??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return qi(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const t="Error verifying 3DS verification result.";throw Fn(t,`Resulting URL: ${r}.
21
+ Error: ${fe(e)}`),new Error(t)}},Ki=(r,e)=>new URL(r).searchParams.get(e),Hi=r=>(r==null?void 0:r["op-pockyt-3ds-url"])!==void 0,Ji=async(r,e)=>{const t=Wi(e),n=await Ln({url:t["op-pockyt-3ds-url"],baseUrl:r});return{existing_cc:{vault_id:Un(n.href??""),transaction_no:t["op-pockyt-txn-no"],reference_no:t["op-pockyt-ref-no"]}}},{log__:Qi,err__:xr}=L("airwallex-cc"),Xi=a.object({"op-airwallex-3ds-url":a.string(),"op-airwallex-initial-intent-id":a.string(),"op-airwallex-consent-id":a.string()}),ec=r=>{const e=Xi.safeParse(r);if(!e.success){const t="Unable to process your credit card. Please contact support for assistance.",n=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`;throw xr(n),new Error(t)}return e.data},tc=r=>(r==null?void 0:r["op-airwallex-3ds-url"])!==void 0,rc=r=>{try{const e=new URL(r??"").searchParams.get("payment_intent_id");if(!e)throw new Error("No intent ID found in Airwallex 3DS verification result");return Qi(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const t="Error verifying Airwallex 3DS verification result.";throw xr(t,`Resulting URL: ${r}.
22
+ Error: ${fe(e)}`),new Error(t)}},nc=async(r,e)=>{const t=ec(e),n=await Ln({url:t["op-airwallex-3ds-url"],baseUrl:r}),o=rc(n.href??""),s=t["op-airwallex-initial-intent-id"];if(s!==o){const c="Unable to process your credit card. Please contact support for assistance.",l=`Intent ID from callback (${o}) does not match the initial intent ID (${s}).`;throw xr(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:t["op-airwallex-consent-id"]}}},$n=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()})}),Zn=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()})}),oc=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),{log__:Tt,err__:Xt}=L("adyen-cc"),sc=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":oc,"op-adyen-action":a.string()}),Vn="Unable to process your credit card. Please contact support for assistance.",ac=r=>{const e=sc.safeParse(r);if(!e.success)throw Xt(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`),new Error(Vn);return e.data},ic=r=>JSON.parse(r),zn=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,cc=async()=>{Tt("Waiting for Adyen SDK to load...");for(let r=0;r<10;r++)zn()||await vr(500);if(!zn())throw Xt("Adyen SDK not loaded properly"),new Error(Vn);return Tt("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},lc=r=>{const{headers:e,locale:t,countryCode:n,component:o,host:s,cancelButton:i}=r,c=ic(e["op-adyen-action"]);return Tt(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{Tt("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",_),s.remove()},d=h=>{Xt("Authentication failed. Result:",h),l({status:$.FAILURE,cleanup:u})},p=h=>{Xt("Adyen error:",h),l({status:$.FAILURE,cleanup:u})},_=()=>{l({status:$.CANCELLED,cleanup:u})};i.addEventListener("click",_);const f=(h,w,x)=>{s.remove(),l({status:$.SUCCESS,additionalDetails:h,cleanup:u})};cc().then(h=>h({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:t,countryCode:n,onAdditionalDetails:f,onPaymentFailed:d,onError:p})).then(h=>{h.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},uc=r=>(r==null?void 0:r["op-adyen-action"])!==void 0,dc=async(r,e,t)=>{const n=ac(t),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=jn("http://example.com");i.replaceWith(o);const l=await lc({headers:n,locale:r,countryCode:e,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===$.FAILURE)throw new Error("3DS verification failed");if(l.status===$.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===$.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return Tt("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else Yt(l.status)},{log__:N,err__:Gn}=L("common-cc"),{log__:Bn}=L("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const pc=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var u;N("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=r.anyCdeConnection,i=await z(s);N(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=Me(t,n.get.onValidationError),l={session_id:r.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin}};try{N(`├ Tokenizing card info in CDE [Session: ${r.elementsSessionId}]`);const d=await _i(o.currentCdeConnections,{session_id:r.elementsSessionId});if(Ni(d,n.get.onValidationError),i.mode==="setup"){N(`├ Setting up payment method in CDE [Token: ${i.token}]`);const p=await gi(s,l);return N(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{N(`├ Initial checkout flow. Checking out card info in CDE [Session: ${r.elementsSessionId}]`);const p=await kn(s,l);return N("╰ Checkout completed successfully."),{mode:"checkout",result:p}}}catch(d){if(d instanceof bn&&d.originalErrorMessage.includes("3DS_REQUIRED")){N("├ Card requires 3DS, starting non-legacy payment flow"),N("Received 3DS error response headers:",d.response.headers);const p=Hi(d.response.headers);if(p){N("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const C=await Ji(r.baseUrl,d.response.headers);l.extra_metadata.pockyt=C}if(tc(d.response.headers)){N("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const C=await nc(r.baseUrl,d.response.headers);l.extra_metadata.airwallex=C}if(uc(d.response.headers)){N("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const C=await dc(i.locale,t[y.COUNTRY],d.response.headers);l.extra_metadata.adyen=C}const h=await pi(s,l);N("├ Payment flow result:",h);const w=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";p?N("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):w?(N("├ Using stripe 3DS flow"),await _c(h)):(N("├ Using common 3DS flow"),await yc(h,r.baseUrl));const x=h.cc_pm_id;if(i.mode==="setup"){N(`├ Confirming payment flow [cc_pm_id: ${x}]`);const C=await se(s,{secure_token:i.token,existing_cc_pm_id:x});N("├ Confirm payment flow result received Result:",C);const T=It(C);return N(`╰ Setup completed successfully [PM ID: ${T.payment_method_id}]`),{mode:"setup",result:T}}else{N(`├ Checking out after 3DS flow [Flow: ${w?"legacy":"new"}]`);const C=await kn(s,{...l,existing_cc_pm_id:x,do_not_use_legacy_cc_flow:w});return N("╰ Checkout completed successfully."),{mode:"checkout",result:C}}}throw Gn("╰ Error checking out card info in CDE"),Gn(d),d}}),fc=r=>{const e=r.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return na.parse(e)},hc=["airwallex_payment_consent","adyen"],mc=r=>{const e=r.required_user_actions.find(t=>hc.includes(t.type));if(!e)throw new Error("No common 3DS action found");return Xs.parse(e)},yc=async(r,e)=>{const t=mc(r);if(t.redirect_url==="3DS_COMPLETE"){N("├ 3DS flow completed successfully");return}N(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const{status:n}=await Qt({url:t.redirect_url,baseUrl:e});if(N(`╰ 3DS verification completed [Status: ${n}]`),n===$.CANCELLED)throw new Error("3DS verification cancelled");if(n===$.FAILURE)throw new Error("3DS verification failed")},_c=async r=>{const e=fc(r);Bn(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await ua(e),Bn("╰ Stripe 3DS flow completed successfully")},ie=a.enum(["stripe","airwallex","authorize_net"]);ie.Enum.stripe;const{log__:H,err__:gc}=L("stripe-pr"),vc=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()})}),wc=Ze(async({context:r,formCallbacks:e})=>{H("Checking if there are any CPMs for Stripe PR...");const t=ae(r.checkoutPaymentMethods,vc);H("Initializing Stripe PR flow...");const n=r.anyCdeConnection,o=await z(n),s=o.mode==="setup";H("Getting initial preview amount");const i=await tt(n,o.token,s,void 0),c=await ia(t.metadata.stripe_pk,i.amountAtom,i.currency,s);H("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return gc("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};H("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,p)=>Z.stripePR.run({context:r,checkoutPaymentMethod:Nt(r.checkoutPaymentMethods,d),nonCdeFormInputs:he(r.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:p==null?void 0:p.overridePaymentRequest},initResult:{processor:ie.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:ie.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),bc=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o,initResult:s})=>{if(H("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=r.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const h=o.overridePaymentRequest;H("Overriding PR amount with",h),Ec(c,h.amount,h.pending,h.applePayPaymentRequest)}H("Showing PR dialog..."),c.show();const l=await ca(c);H("Stripe PM added event:",l),H("Merging PM fields with form fields...");const u=kc(t,l),d=Me(u,n.get.onValidationError);H("PR dialog finished. Starting payment flow...",d);const p=await fi(i,{fields:d,checkoutPaymentMethod:e}),_=Cc(p);H("Confirming PR with Stripe..."),await la(_,l);const f=await z(i);if(f.mode==="setup"){H("Confirming payment flow for setup...");const h=await se(i,{secure_token:f.token});return{mode:"setup",result:It(h)}}else{H("Performing checkout...");const h={secure_token:f.token,payment_input:{provider_type:e.provider},customer_first_name:d[y.FIRST_NAME],customer_last_name:d[y.LAST_NAME],customer_email:d[y.EMAIL],customer_zip_code:d[y.ZIP_CODE],customer_country:d[y.COUNTRY],promotion_code:d[y.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 Er(i,h)}}}),kc=(r,e)=>{var l,u,d,p;const t={...r},[n,...o]=((u=(l=e.payerName)==null?void 0:l.trim())==null?void 0:u.split(/\s+/))??[],s=o.join(" ")||void 0,i=(p=(d=e.paymentMethod)==null?void 0:d.billing_details)==null?void 0:p.address,c=e.shippingAddress;return t[y.FIRST_NAME]=t[y.FIRST_NAME]||n||"_OP_UNKNOWN",t[y.LAST_NAME]=t[y.LAST_NAME]||s||"_OP_UNKNOWN",t[y.EMAIL]=t[y.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[y.ZIP_CODE]=t[y.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",t[y.COUNTRY]=t[y.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US",H("Final form inputs:",t),t},Ec=(r,e,t,n)=>{r.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency,applePay:n})},Cc=r=>{if(r.required_user_actions.length!==1)throw new Error(`Error occurred.
23
+ Details: got ${r.required_user_actions.length} required user actions`);return oa.parse(r.required_user_actions[0])},{log__:_e,err__:qn}=L("pockyt-paypal"),Sc=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 Pc=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var U,ve;_e("Running Pockyt Paypal flow...");const s=r.anyCdeConnection,i=await z(s);_e("Verifying CPM...");const c=Sc.parse(e);_e("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=Me(t,n.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=Oi(u);_e(`Starting payment flow... Mode: ${i.mode}`);const p=br(),_=i.mode!=="setup",f={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:_,pay_first_flow_cart_info:_?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((U=o==null?void 0:o.settings)!=null&&U.useRedirectFlow),frontend_token_for_redirect_flow:p},...d},h=new URL("/app/pre-action/start/",r.baseUrl).toString(),w=btoa(JSON.stringify(f)),x=new URLSearchParams({st:i.token,r:w}),C=`${h}?${x.toString()}`;if((ve=o==null?void 0:o.settings)!=null&&ve.useRedirectFlow)throw _e("Starting redirect mode for PayPal..."),window.location.href=C,await vr(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");_e("Starting popup mode for PayPal..."),_e("Opening paypal iframe...");const T=await Bi("PayPal",s,p,C);_e("Paypal flow result",T);const S=Un(T.href),D=Ki(T.href,"catt");if(!D)throw qn("Checkout attempt ID not found in redirect URL:",T.href),new Error("Checkout attempt ID not found in redirect URL");_e(`Confirming payment flow using vault ID ${S}`);const F=await se(s,{secure_token:i.token,their_pm_id:S,checkout_attempt_id:_?D:void 0});if(_e("Confirm payment flow result",F),i.mode==="setup")return{mode:"setup",result:{payment_method_id:F.payment_methods[0].id}};if(!F.pay_first_success_response)throw qn("Checkout failed, no pay-first success response:",F),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:F.pay_first_success_response}}),er=({gateway:r,gatewayMerchantId:e,merchantName:t,merchantId:n,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var p,_;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=(((_=s==null?void 0:s.amount)==null?void 0:_.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:r,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:n??"",merchantName:t},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?{...d,...s.googlePayPaymentRequest}:d},Yn=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://pay.google.com/gp/p/js/pay.js",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Google Pay SDK")),document.body.appendChild(t)});let Ir=null;const Wn=r=>r===je||r===window.location.origin?"PRODUCTION":"TEST",tr=(r,e)=>{const t=Wn(r);return Ir===null&&(Ir=new window.google.payments.api.PaymentsClient({environment:t,merchantInfo:e.merchantInfo})),Ir},Ac=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");return e?nn.parse(e):null},Kn=(r,e)=>{var o,s,i,c;const t={...r},n=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(n){const[l,...u]=((c=(i=n.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;t[y.EMAIL]=t[y.EMAIL]||e.email||"op_unfilled@getopenpay.com",t[y.COUNTRY]=t[y.COUNTRY]||n.countryCode||"US",t[y.ADDRESS]=t[y.ADDRESS]||n.address1||"",t[y.CITY]=t[y.CITY]||n.locality||"",t[y.ZIP_CODE]=t[y.ZIP_CODE]||n.postalCode||"00000",t[y.STATE]=t[y.STATE]||n.administrativeArea||"",t[y.FIRST_NAME]=t[y.FIRST_NAME]||l||"_OP_UNKNOWN",t[y.LAST_NAME]=t[y.LAST_NAME]||d||"_OP_UNKNOWN"}return t},{log__:ce,err__:ot}=L("awx-google-pay"),xc=Ze(async({context:r,formCallbacks:e})=>{var p,_;const t={processor:ie.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=ae(r.checkoutPaymentMethods,Zn);if(!n)return t;ce("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return ot("No gateway merchant ID found in processor account"),t;if(ce("Loading Google Pay SDK..."),await Yn(),!((_=(p=window.google)==null?void 0:p.payments)!=null&&_.api))return ot("Google Pay SDK not loaded properly"),t;if(Wn(r.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return ot("Google Pay merchant ID is required for production environment"),t;ce("Google Pay SDK loaded",window.google.payments);try{const f=er({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:h}=await tr(r.baseUrl,f).isReadyToPay(f);if(!h)return ce("Google Pay is not available for this user"),t}catch(f){return ot("Error checking Google Pay availability",f),t}const i=r.anyCdeConnection,c=await z(i),l=c.mode==="setup",u=await tt(i,c.token,l,void 0),d=async f=>{try{Z.airwallexGooglePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:he(r.formDiv),formCallbacks:e,initResult:void 0,customParams:{...f,initialPreview:u}})}catch(h){ot("Google Pay payment error",h),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:ie.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Ic=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var p,_,f,h,w,x,C;ce("Starting Google Pay flow...");const s=ae(r.checkoutPaymentMethods,Zn),{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=er({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=tr(r.baseUrl,u);try{const T=await d.loadPaymentData(u);ce("Google Pay Payment data",T);const S=r.anyCdeConnection,D=await z(S),F=Kn(t,T),U=Me(F,n.get.onValidationError,o==null?void 0:o.defaultFieldValues),ve=(_=(p=T.paymentMethodData)==null?void 0:p.tokenizationData)==null?void 0:_.token;if(!ve)throw new Error("No payment token received from Google Pay");const Hl=await et(S,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:U[y.EMAIL],new_customer_first_name:U[y.FIRST_NAME],new_customer_last_name:U[y.LAST_NAME],new_customer_address:{zip_code:U[y.ZIP_CODE],country:U[y.COUNTRY]}}),ur=Ac(Hl);ce("Start flow next actions",ur);let Ge=await se(S,{secure_token:D.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:ur==null?void 0:ur.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:ve}}}});ce("[1st] Confirm payment flow response",Ge);let $r=(h=(f=Ge.payment_methods)==null?void 0:f[0])==null?void 0:h.id;const Be=(w=Ge.required_user_actions)==null?void 0:w.find(Dt=>Dt.type==="airwallex_payment_consent");if(Be&&Be.redirect_url){ce("3DS Required, starting verification...",Be);const{status:Dt}=await Qt({url:Be.redirect_url,baseUrl:r.baseUrl});if(ce(`╰ 3DS verification completed [Status: ${Dt}]`),Dt===$.CANCELLED)throw new Error("3DS verification cancelled");if(Dt===$.FAILURE)throw new Error("3DS verification failed")}if(Be&&!$r&&(Ge=await se(S,{secure_token:D.token,their_pm_id:Be.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Be.consent_id}}),ce("[2nd] Confirm payment flow response",Ge),$r=(C=(x=Ge.payment_methods)==null?void 0:x[0])==null?void 0:C.id),!$r)throw new Error("No PM ID found");return Jt({logPrefix:"awx-googlepay",anyCdeConnection:S,checkoutPaymentMethod:e,requiredFormFields:U,confirmResult:Ge,usePayFirstFlow:!1})}catch(T){throw ot("Google Pay payment error",T),new Error((T==null?void 0:T.message)??"Unknown error")}}),Hn=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",t.crossOrigin="anonymous",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Apple Pay SDK")),document.body.appendChild(t)}),Jn=(r,e)=>{const t=e.token.paymentMethod.billingContact,n=e.billingContact,o=e.shippingContact,s={...r};return(t||n||o)&&(s[y.EMAIL]=s[y.EMAIL]||(t==null?void 0:t.emailAddress)||(n==null?void 0:n.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[y.COUNTRY]=s[y.COUNTRY]||(t==null?void 0:t.countryCode)||(n==null?void 0:n.countryCode)||(o==null?void 0:o.countryCode)||"US",s[y.ZIP_CODE]=s[y.ZIP_CODE]||(t==null?void 0:t.postalCode)||(n==null?void 0:n.postalCode)||(o==null?void 0:o.postalCode)||"00000",s[y.FIRST_NAME]=s[y.FIRST_NAME]||(t==null?void 0:t.givenName)||(n==null?void 0:n.givenName)||(o==null?void 0:o.givenName)||"_OP_UNKNOWN",s[y.LAST_NAME]=s[y.LAST_NAME]||(t==null?void 0:t.familyName)||(n==null?void 0:n.familyName)||(o==null?void 0:o.familyName)||"_OP_UNKNOWN"),s},Tc=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")}),Rc=r=>Tc.safeParse(r).data,Oc=r=>{const e=new AbortController;return window.addEventListener("message",t=>{var o;const n=Rc(t);((o=n==null?void 0:n.data)==null?void 0:o.messageType)==="windowclosing"&&(r(),e.abort())},{signal:e.signal}),{cleanupCancelListener:()=>e.abort()}},Qn=({total:r,prefill:e})=>{var n;if(e.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:r.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${e.token}`,je).toString()};const t=(n=e.line_items)==null?void 0:n[0];if(t)return{paymentDescription:(t==null?void 0:t.description)??"",regularBilling:{amount:r.amount,label:(t==null?void 0:t.description)??"",recurringPaymentIntervalUnit:t==null?void 0:t.billing_interval,recurringPaymentIntervalCount:(t==null?void 0:t.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},Xn=({overridePaymentRequest:r,initialPreview:e,prefill:t,defaultLabel:n="Total"})=>{var c,l;const o=(((c=r==null?void 0:r.amount)==null?void 0:c.currency)??(t==null?void 0:t.currency)??e.currency).toUpperCase(),i=((((l=r==null?void 0:r.amount)==null?void 0:l.amountAtom)??(e==null?void 0:e.amountAtom)??0)/100).toFixed(2);return{currencyCode:o,total:{label:(r==null?void 0:r.label)??n??"Total",type:r!=null&&r.pending?"pending":"final",amount:i}}},{log__:rr}=L("awx-apple-pay");async function Nc(r,e){try{const n=(await Cn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:r.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o)}catch(t){throw e.session.abort(),t}}async function Mc(r,e){if(!r.redirect_url)throw new Error("No redirect URL found");rr("3DS Required, starting verification...",r);const{status:t}=await Qt({url:r.redirect_url,baseUrl:e.baseUrl});if(rr(`╰ 3DS verification completed [Status: ${t}]`),t===$.CANCELLED)throw new Error("3DS verification cancelled");if(t===$.FAILURE)throw new Error("3DS verification failed");const n=await se(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:r.their_pm_id,airwallex_consent_id:r.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return rr("[2nd] Confirm payment flow response",n),n}async function Dc(r,e){var t,n,o,s,i;try{const c=r.payment,l=Jn(e.nonCdeFormInputs,c),u=Me(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues),_=(await et(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[y.EMAIL],new_customer_first_name:u[y.FIRST_NAME],new_customer_last_name:u[y.LAST_NAME],new_customer_address:{zip_code:u[y.ZIP_CODE],country:u[y.COUNTRY]}})).required_user_actions[0].consent_id;if(!_)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:_,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});rr("[1st] Confirm payment flow response",f);let h=(n=(t=f.payment_methods)==null?void 0:t[0])==null?void 0:n.id;const w=(o=f.required_user_actions)==null?void 0:o.find(C=>C.type==="airwallex_payment_consent");if(w!=null&&w.redirect_url&&w.consent_id&&w.their_pm_id&&(f=await Mc(w,e),h=(i=(s=f.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!h)throw new Error("No PM ID found");const x={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(x),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__:st,err__:Tr}=L("awx-apple-pay"),jc=Ze(async({context:r,formCallbacks:e})=>{const t={processor:ie.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=ae(r.checkoutPaymentMethods,$n);if(!n)return t;st("Loading Apple Pay SDK...");try{await Hn(),st("Apple Pay SDK loaded successfully")}catch(p){return Tr("Failed to load Apple Pay SDK",p),t}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return st("Apple Pay is not available on this device/browser"),t;if(st("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return st("No active cards available for Apple Pay"),t;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=r.anyCdeConnection,c=await z(i),l=c.mode==="setup",u=await tt(i,c.token,l,void 0),d=async p=>{try{await Z.airwallexApplePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:he(r.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Tr("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ie.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Lc=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:o})=>{var x;const s=ae(r.checkoutPaymentMethods,$n),{overridePaymentRequest:i,initialPreview:c}=n,l=r.anyCdeConnection,u=await z(l),d=u.mode==="setup",{currencyCode:p,total:_}=Xn({overridePaymentRequest:i,initialPreview:c,defaultLabel:(x=s==null?void 0:s.metadata)==null?void 0:x.processor_account_name}),f={countryCode:"US",currencyCode:p,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:_,recurringPaymentRequest:Qn({total:_,prefill:u}),...(i==null?void 0:i.applePayPaymentRequest)??{}},h=new ApplePaySession(3,f),w={session:h,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:r.baseUrl,formCallbacks:o,defaultFieldValues:n==null?void 0:n.defaultFieldValues};return new Promise((C,T)=>{const S=()=>{st("Payment cancelled by user"),T(new Error("Payment cancelled by user"))},{cleanupCancelListener:D}=Oc(S);h.oncancel=S,h.onvalidatemerchant=async F=>{try{await Nc(F,w)}catch(U){T(U)}},h.onpaymentmethodselected=()=>{const F={newTotal:{..._}};h.completePaymentMethodSelection(F)},h.onpaymentauthorized=async F=>{try{const U=await Dc(F,w);D(),C(U)}catch(U){T(U)}},h.begin()}).catch(C=>{throw Tr("Apple Pay payment error",C),C})}),Fc=1,Uc=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()})}),{log__:J,err__:$c}=L("loop-crypto"),Zc=Ze(async({context:r})=>{J("Checking if there are any CPMs for Loop Crypto...");const e=ae(r.checkoutPaymentMethods,Uc);J(`checkoutPaymentMethod: ${JSON.stringify(e)}`),J("Starting Loop Crypto flow...");const t=await z(r.anyCdeConnection);let n;if(t.mode==="setup"?n=Fc:n=t.amount_total_atom,t.currency!=="usd"&&t.mode!=="setup")throw Error("Cannot support non USD currency for Loop");const o=n,s=Math.max(o*12,1e5),i=br(),c={paymentUsdAmount:o,suggestedAuthorizationUsdAmount:s,customerRefId:i},l={apiKey:e.metadata.api_token,entityId:e.metadata.entity_id,merchantId:e.metadata.merchant_id};return{isAvailable:!0,widgetProps:c,initLoopConnectProps:l}}),Vc=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o,initResult:s})=>{J("Running Loop flow..."),J("context",r),J("checkoutPaymentMethod",e),J("nonCdeFormInputs",t),J("flowCallbacks",n),J("customParams",o),J("initResult",s);const i=r.anyCdeConnection;if(!s.isAvailable)throw Error("Failed to initialize Loop flow. Cannot submit without initialization. Exiting running Loop flow.");const c=await z(r.anyCdeConnection),l=c.mode!=="setup",u=await et(r.anyCdeConnection,{checkout_payment_method:e,payment_provider:e.provider,new_customer_email:o.email,new_customer_first_name:o.firstName,new_customer_last_name:o.lastName,use_pay_first_flow:l,pay_first_flow_cart_info:l?{line_items:c.line_items,displayed_total_amount_atom:s.widgetProps.paymentUsdAmount}:void 0});if(!o.success)throw Error(`Payin was not successful: ${o.detail.type} ${o.detail.message} ${JSON.stringify(o.detail.data)}`);const d=await se(i,{secure_token:c.token,their_pm_id:o.payin.paymentMethod.paymentMethodId,checkout_attempt_id:c.mode!=="setup"?u.checkout_attempt_id:void 0,processor_specific_metadata:{loop_customer:o.customer,loop_payin:o.payin}});if(J(`Confirm result: ${d}`),c.mode==="setup"){J("Doing payment setup..."),J("├ Confirm payment flow result received Result:",d);const p=It(d);return J(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{if(J("Doing checkout..."),!d.pay_first_success_response)throw $c("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}}});async function zc(r,e){try{const n=(await Cn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:r.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o)}catch(t){throw e.session.abort(),t}}async function Gc(r,e){var t,n;try{const o=r.payment,s=Jn(e.nonCdeFormInputs,o),i=Me(s,e.formCallbacks.get.onValidationError);await et(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[y.EMAIL],new_customer_first_name:i[y.FIRST_NAME],new_customer_last_name:i[y.LAST_NAME],new_customer_address:{zip_code:i[y.ZIP_CODE],country:i[y.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(!((n=(t=l.payment_methods)==null?void 0:t[0])==null?void 0:n.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 eo=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),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()})}),{log__:Rt,err__:Rr}=L("authnet-applepay"),Bc=Ze(async({context:r,formCallbacks:e})=>{const t={processor:ie.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=ae(r.checkoutPaymentMethods,eo);if(!n)return t;Rt("Loading Apple Pay SDK...");try{await Hn(),Rt("Apple Pay SDK loaded successfully")}catch(p){return Rr("Failed to load Apple Pay SDK",p),t}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return Rt("Apple Pay is not available on this device/browser"),t;if(!await ApplePaySession.canMakePayments())return Rt("No active cards available for Apple Pay"),t;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=r.anyCdeConnection,c=await z(i),l=c.mode==="setup",u=await tt(i,c.token,l,void 0),d=async p=>{try{await Z.authorizeNetApplePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:he(r.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Rr("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ie.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),qc=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:o})=>{var x;const{initialPreview:s,overridePaymentRequest:i}=n,c=ae(r.checkoutPaymentMethods,eo),{currencyCode:l,total:u}=Xn({overridePaymentRequest:i,initialPreview:s,defaultLabel:(x=c==null?void 0:c.metadata)==null?void 0:x.processor_account_name}),d=r.anyCdeConnection,p=await z(d),_=p.mode==="setup",f={countryCode:"US",currencyCode:l,total:u,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],recurringPaymentRequest:Qn({total:u,prefill:p}),...(i==null?void 0:i.applePayPaymentRequest)??{}},h=new ApplePaySession(3,f),w={session:h,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:e.metadata,prefill:p,isSetupMode:_,baseUrl:r.baseUrl,formCallbacks:o};return new Promise((C,T)=>{h.oncancel=()=>{Rt("Payment cancelled by user"),T(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async S=>{try{await zc(S,w)}catch(D){T(D)}},h.onpaymentmethodselected=()=>{const S={newTotal:f.total};h.completePaymentMethodSelection(S)},h.onpaymentauthorized=async S=>{try{const D=await Gc(S,w);C(D)}catch(D){T(D)}},h.begin()}).catch(C=>{throw Rr("Apple Pay payment error",C),C})}),{log__:Ve,err__:Ot}=L("authnet-googlepay"),Yc=Ze(async({context:r,formCallbacks:e})=>{var d,p;Ve("Initializing Authnet GooglePay flow");const t={processor:ie.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=ae(r.checkoutPaymentMethods,to);if(!n)return t;Ve("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return Ot("No gateway merchant ID found in processor account"),t;if(Ve("Loading Google Pay SDK..."),await Yn(),!((p=(d=window.google)==null?void 0:d.payments)!=null&&p.api))return Ot("Google Pay SDK not loaded properly"),t;Ve("Google Pay SDK loaded",window.google.payments);try{const _=er({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:f}=await tr(r.baseUrl,_).isReadyToPay(_);if(!f)return Ve("Google Pay is not available for this user"),t}catch(_){return Ot("Error checking Google Pay availability",_),t}const s=r.anyCdeConnection,i=await z(s),c=i.mode==="setup",l=await tt(s,i.token,c,void 0),u=async _=>{try{Z.authorizeNetGooglePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:he(r.formDiv),formCallbacks:e,initResult:void 0,customParams:{..._,initialPreview:l}})}catch(f){Ot("Google Pay payment error",f),e.get.onCheckoutError((f==null?void 0:f.message)??"Unknown error")}};return{processor:ie.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),Wc=Ee(async({context:r,nonCdeFormInputs:e,checkoutPaymentMethod:t,formCallbacks:n,customParams:o})=>{var p,_,f,h;const{initialPreview:s,overridePaymentRequest:i}=o,l=ae(r.checkoutPaymentMethods,to).metadata,u=er({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=tr(r.baseUrl,u);try{const w=await d.loadPaymentData(u);Ve("Google Pay Payment data",w);const x=r.anyCdeConnection,C=await z(x),T=Kn(e,w),S=Me(T,n.get.onValidationError),D=(_=(p=w.paymentMethodData)==null?void 0:p.tokenizationData)==null?void 0:_.token;if(!D)throw new Error("No payment token received from Google Pay");const F=await et(x,{payment_provider:t.provider,checkout_payment_method:t,new_customer_email:S[y.EMAIL],new_customer_first_name:S[y.FIRST_NAME],new_customer_last_name:S[y.LAST_NAME],new_customer_address:{zip_code:S[y.ZIP_CODE],country:S[y.COUNTRY]}});Ve("Start payment flow response",F);const U=await se(x,{secure_token:C.token,processor_specific_metadata:{payment_provider:t.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(D)}}});if(!((h=(f=U.payment_methods)==null?void 0:f[0])==null?void 0:h.id))throw new Error("No PM ID found");return Jt({logPrefix:"authnet-googlepay",anyCdeConnection:x,checkoutPaymentMethod:t,requiredFormFields:S,confirmResult:U,usePayFirstFlow:!1})}catch(w){throw Ot("Google Pay payment error",w),new Error((w==null?void 0:w.message)??"Unknown error")}}),Nt=(r,e,t)=>{const n=r.filter(o=>{const s=t===void 0?!0:o.processor_name===t,i=o.provider===e;return s&&i});if(n.length===0)throw console.error("CPMs list",r),new Error(`No CPMs found with provider '${e}' and processor '${t}'`);if(n.length!==1)throw console.error("CPMs list",r),new Error(`More than one CPM found with provider '${e}' and processor '${t}'`);return n[0]},Z={commonCC:{init:async()=>{},run:pc},stripePR:{init:wc,run:bc},stripeLink:{init:Li,run:Fi},pockytPaypal:{run:Pc},airwallexGooglePay:{init:xc,run:Ic},airwallexApplePay:{init:jc,run:Lc},loopCrypto:{init:Zc,run:Vc},authorizeNetApplePay:{init:Bc,run:qc},authorizeNetGooglePay:{init:Yc,run:Wc}};var Or=function(r,e){return Or=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])},Or(r,e)};function De(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Or(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Kc(r,e,t,n){function o(s){return s instanceof t?s:new t(function(i){i(s)})}return new(t||(t=Promise))(function(s,i){function c(d){try{u(n.next(d))}catch(p){i(p)}}function l(d){try{u(n.throw(d))}catch(p){i(p)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((n=n.apply(r,e||[])).next())})}function ro(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,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(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(t=0)),t;)try{if(n=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 t.label++,{value:u[1],done:!1};case 5:t.label++,o=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){t.label=u[1];break}if(u[0]===6&&t.label<s[1]){t.label=s[1],s=u;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(u);break}s[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(r,t)}catch(d){u=[6,d],o=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function at(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function nr(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(c){i={error:c}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return s}function or(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return r.concat(s||Array.prototype.slice.call(e))}function it(r){return this instanceof it?(this.v=r,this):new it(r)}function Hc(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,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(h){return Promise.resolve(h).then(f,p)}}function c(f,h){n[f]&&(o[f]=function(w){return new Promise(function(x,C){s.push([f,w,x,C])>1||l(f,w)})},h&&(o[f]=h(o[f])))}function l(f,h){try{u(n[f](h))}catch(w){_(s[0][3],w)}}function u(f){f.value instanceof it?Promise.resolve(f.value.v).then(d,p):_(s[0][2],f)}function d(f){l("next",f)}function p(f){l("throw",f)}function _(f,h){f(h),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Jc(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof at=="function"?at(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=r[s]&&function(i){return new Promise(function(c,l){i=r[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 B(r){return typeof r=="function"}function sr(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Nr=sr(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
24
24
  `+t.map(function(n,o){return o+1+") "+n.toString()}).join(`
25
- `):"",this.name="UnsubscriptionError",this.errors=t}});function rr(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var It=function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,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=nt(i),l=c.next();!l.done;l=c.next()){var u=l.value;u.remove(this)}}catch(w){e={error:w}}finally{try{l&&!l.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(V(d))try{d()}catch(w){s=w instanceof xr?w.errors:[w]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var _=nt(f),p=_.next();!p.done;p=_.next()){var y=p.value;try{Xn(y)}catch(w){s=s??[],w instanceof xr?s=er(er([],Xt(s)),Xt(w.errors)):s.push(w)}}}catch(w){n={error:w}}finally{try{p&&!p.done&&(o=_.return)&&o.call(_)}finally{if(n)throw n.error}}}if(s)throw new xr(s)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Xn(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&rr(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&rr(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),Jn=It.EMPTY;function Qn(r){return r instanceof It||r&&"closed"in r&&V(r.remove)&&V(r.add)&&V(r.unsubscribe)}function Xn(r){V(r)?r():r.unsubscribe()}var eo={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},to={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,er([r,e],Xt(t)))},clearTimeout:function(r){var e=to.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function ro(r){to.setTimeout(function(){throw r})}function no(){}function nr(r){r()}var Tr=function(r){Me(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,Qn(t)&&t.add(n)):n.destination=jc,n}return e.create=function(t,n,o){return new Rr(t,n,o)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(It),Nc=Function.prototype.bind;function Ir(r,e){return Nc.call(r,e)}var Mc=function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){or(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){or(n)}else or(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){or(t)}},r}(),Rr=function(r){Me(e,r);function e(t,n,o){var s=r.call(this)||this,i;if(V(t)||!t)i={next:t??void 0,error:n??void 0,complete:o??void 0};else{var c;s&&eo.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&Ir(t.next,c),error:t.error&&Ir(t.error,c),complete:t.complete&&Ir(t.complete,c)}):i=t}return s.destination=new Mc(i),s}return e}(Tr);function or(r){ro(r)}function Dc(r){throw r}var jc={closed:!0,next:no,error:Dc,complete:no},Or=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Lc(r){return r}function Fc(r){return r.length===0?Lc:r.length===1?r[0]:function(t){return r.reduce(function(n,o){return o(n)},t)}}var ke=function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var o=this,s=$c(e)?e:new Rr(e,t,n);return nr(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},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=oo(t),new t(function(o,s){var i=new Rr({next:function(c){try{e(c)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});n.subscribe(i)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Or]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fc(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=oo(e),new e(function(n,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return n(s)})})},r.create=function(e){return new r(e)},r}();function oo(r){var e;return(e=r??eo.Promise)!==null&&e!==void 0?e:Promise}function Uc(r){return r&&V(r.next)&&V(r.error)&&V(r.complete)}function $c(r){return r&&r instanceof Tr||Uc(r)&&Qn(r)}function Zc(r){return V(r==null?void 0:r.lift)}function Vc(r){return function(e){if(Zc(e))return e.lift(function(t){try{return r(t,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function zc(r,e,t,n,o){return new Gc(r,e,t,n,o)}var Gc=function(r){Me(e,r);function e(t,n,o,s,i,c){var l=r.call(this,t)||this;return l.onFinalize=i,l.shouldUnsubscribe=c,l._next=n?function(u){try{n(u)}catch(d){t.error(d)}}:r.prototype._next,l._error=s?function(u){try{s(u)}catch(d){t.error(d)}finally{this.unsubscribe()}}:r.prototype._error,l._complete=o?function(){try{o()}catch(u){t.error(u)}finally{this.unsubscribe()}}:r.prototype._complete,l}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;r.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(Tr),Bc=tr(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),so=function(r){Me(e,r);function e(){var t=r.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var n=new ao(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new Bc},e.prototype.next=function(t){var n=this;nr(function(){var o,s;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var i=nt(n.currentObservers),c=i.next();!c.done;c=i.next()){var l=c.value;l.next(t)}}catch(u){o={error:u}}finally{try{c&&!c.done&&(s=i.return)&&s.call(i)}finally{if(o)throw o.error}}}})},e.prototype.error=function(t){var n=this;nr(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=t;for(var o=n.observers;o.length;)o.shift().error(t)}})},e.prototype.complete=function(){var t=this;nr(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var n=t.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,o=this,s=o.hasError,i=o.isStopped,c=o.observers;return s||i?Jn:(this.currentObservers=null,c.push(t),new It(function(){n.currentObservers=null,rr(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,o=n.hasError,s=n.thrownError,i=n.isStopped;o?t.error(s):i&&t.complete()},e.prototype.asObservable=function(){var t=new ke;return t.source=this,t},e.create=function(t,n){return new ao(t,n)},e}(ke),ao=function(r){Me(e,r);function e(t,n){var o=r.call(this)||this;return o.destination=t,o.source=n,o}return e.prototype.next=function(t){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,t)},e.prototype.error=function(t){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&o!==void 0?o:Jn},e}(so),qc={now:function(){return Date.now()},delegate:void 0},Yc=function(r){Me(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(It),io={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,er([r,e],Xt(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},Wc=function(r){Me(e,r);function e(t,n){var o=r.call(this,t,n)||this;return o.scheduler=t,o.work=n,o.pending=!1,o}return e.prototype.schedule=function(t,n){var o;if(n===void 0&&(n=0),this.closed)return this;this.state=t;var s=this.id,i=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(i,s,n)),this.pending=!0,this.delay=n,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(i,this.id,n),this},e.prototype.requestAsyncId=function(t,n,o){return o===void 0&&(o=0),io.setInterval(t.flush.bind(t,this),o)},e.prototype.recycleAsyncId=function(t,n,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return n;n!=null&&io.clearInterval(n)},e.prototype.execute=function(t,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(t,n);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,n){var o=!1,s;try{this.work(t)}catch(i){o=!0,s=i||new Error("Scheduled action threw falsy error")}if(o)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,o=t.scheduler,s=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,rr(s,this),n!=null&&(this.id=this.recycleAsyncId(o,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(Yc),co=function(){function r(e,t){t===void 0&&(t=r.now),this.schedulerActionCtor=e,this.now=t}return r.prototype.schedule=function(e,t,n){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},r.now=qc.now,r}(),Kc=function(r){Me(e,r);function e(t,n){n===void 0&&(n=co.now);var o=r.call(this,t,n)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(t){var n=this.actions;if(this._active){n.push(t);return}var o;this._active=!0;do if(o=t.execute(t.state,t.delay))break;while(t=n.shift());if(this._active=!1,o){for(;t=n.shift();)t.unsubscribe();throw o}},e}(co),Hc=new Kc(Wc),Jc=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function Qc(r){return V(r==null?void 0:r.then)}function Xc(r){return V(r[Or])}function el(r){return Symbol.asyncIterator&&V(r==null?void 0:r[Symbol.asyncIterator])}function tl(r){return new TypeError("You provided "+(r!==null&&typeof r=="object"?"an invalid object":"'"+r+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function rl(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var nl=rl();function ol(r){return V(r==null?void 0:r[nl])}function sl(r){return Rc(this,arguments,function(){var t,n,o,s;return Hn(this,function(i){switch(i.label){case 0:t=r.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,ot(t.read())];case 3:return n=i.sent(),o=n.value,s=n.done,s?[4,ot(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,ot(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function al(r){return V(r==null?void 0:r.getReader)}function il(r){if(r instanceof ke)return r;if(r!=null){if(Xc(r))return cl(r);if(Jc(r))return ll(r);if(Qc(r))return ul(r);if(el(r))return lo(r);if(ol(r))return dl(r);if(al(r))return pl(r)}throw tl(r)}function cl(r){return new ke(function(e){var t=r[Or]();if(V(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function ll(r){return new ke(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function ul(r){return new ke(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,ro)})}function dl(r){return new ke(function(e){var t,n;try{for(var o=nt(r),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(c){t={error:c}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}e.complete()})}function lo(r){return new ke(function(e){fl(r,e).catch(function(t){return e.error(t)})})}function pl(r){return lo(sl(r))}function fl(r,e){var t,n,o,s;return Ic(this,void 0,void 0,function(){var i,c;return Hn(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),t=Oc(r),l.label=1;case 1:return[4,t.next()];case 2:if(n=l.sent(),!!n.done)return[3,4];if(i=n.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]),n&&!n.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function hl(r,e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(s),!o)return s}function ml(r,e){var t=V(r)?r:function(){return r},n=function(o){return o.error(t())};return new ke(n)}var yl=tr(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function _l(r,e){return new Promise(function(t,n){var o=!1,s;r.subscribe({next:function(i){s=i,o=!0},error:n,complete:function(){o?t(s):n(new yl)}})})}function gl(r){return r instanceof Date&&!isNaN(r)}var vl=tr(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function wl(r,e){var t=gl(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,o=t.each,s=t.with,i=s===void 0?bl:s,c=t.scheduler,l=c===void 0?Hc:c,u=t.meta,d=u===void 0?null:u;if(n==null&&o==null)throw new TypeError("No timeout provided.");return Vc(function(f,_){var p,y,w=null,C=0,I=function(T){y=hl(_,l,function(){try{p.unsubscribe(),il(i({meta:d,lastValue:w,seen:C})).subscribe(_)}catch(S){_.error(S)}},T)};p=f.subscribe(zc(_,function(T){y==null||y.unsubscribe(),C++,_.next(w=T),o>0&&I(o)},void 0,void 0,function(){y!=null&&y.closed||y==null||y.unsubscribe(),w=null})),!C&&I(n!=null?typeof n=="number"?n:+n-l.now():o)})}function bl(r){throw new vl(r)}class sr{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,t)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:t},this._subject.error(e)},this.getValueIfLoadedElse=e=>this._current.status==="success"?this._current.loadedValue:e,this.subscribe=e=>{if(this._current.status==="success"){e(this._current);return}this._current.status==="error"&&e(this._current);const t=this._subject.subscribe({next:()=>{if(this._current.status!=="success")throw new Error("Invalid state (next): please make sure to update _current before the subject");e(this._current),t.unsubscribe()},error:()=>{if(this._current.status!=="error")throw new Error("Invalid state (error): please make sure to update _current before the subject");e(this._current)}})},this.waitForLoad=e=>{if(this._current.status==="success")return Promise.resolve(this._current.loadedValue);if(this._current.status==="error")return Promise.reject(this._current.error);this._current.status!=="initial"&&gr(this._current);const t={first:e.timeoutSec*1e3,with:()=>ml(()=>new Error(e.timeoutErrMsg))};return _l(this._subject.pipe(wl(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new so}get current(){return this._current}}const{log__:kl,err__:El}=U("init-flows"),st=(r,e)=>{const t=new sr;return{publisher:t,initialize:async n=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(n);kl(`✔ ${r} flow initialized successfully. Result:`,o),t.set(o)}catch(o){El(`𝙭 ${r} flow initialization failed. Error:`,ue(o),"Details:",o),t.throw(o,ue(o))}}}},Cl=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},Sl=()=>({stripePR:st("Stripe PR",B.stripePR.init),stripeLink:st("Stripe Link",B.stripeLink.init),airwallexGooglePay:st("Airwallex GooglePay",B.airwallexGooglePay.init),airwallexApplePay:st("Airwallex ApplePay",B.airwallexApplePay.init),authorizeNetGooglePay:st("Authnet GooglePay",B.authorizeNetGooglePay.init),authorizeNetApplePay:st("Authnet ApplePay",B.authorizeNetApplePay.init)}),{err__:Pl}=U("form-callbacks"),ae=a.function().optional(),uo=a.object({onFocus:ae,onBlur:ae,onChange:ae,onLoad:ae,onLoadError:ae,onValidationError:ae,onCheckoutStarted:ae,onCheckoutSuccess:ae,onSetupPaymentMethodSuccess:ae,onCheckoutError:ae,onPaymentRequestLoad:ae}),ye=class ye{constructor(){this.setCallbacks=e=>{this._callbacks=ye.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const o=ws(t,n??ye.NOOP,Pl);this._callbacks[t]=o})},this._callbacks=ye.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ye.NOOP=()=>{},ye.createEmptyCallbacks=()=>{const e={};return Object.keys(uo.keyof().enum).forEach(t=>{e[t]=ye.NOOP}),e},ye.fromObject=e=>{const t=new ye;return t.setCallbacks(uo.parse(e)),t};let Nr=ye;class Al{constructor(e,t,n,o){this.handleMessage=s=>{if(!s.source)throw new Error("No source found");if(po(s.origin)!==po(this.baseUrl)||typeof s.data=="object"&&s.data.penpal)return;let i=null;try{i=ua(JSON.parse(s.data))}catch(f){console.warn("[OJS] Unknown event. Ignoring:",f);return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=n,this.internalCallbacks=o}}const po=r=>new URL(r).origin;async function xl(r,e){const n=await cn({iframe:r,debug:!1,childOrigin:e}).promise,o=await Oa(n);if(!Na(n,o))throw new Error("Got invalid CDE connection object");return n}class Tl{constructor(){this.connections=new Map}addConnection(e,t){this.connections.set(e,t)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Il=(r,e,t)=>{const{stripePR:n}=r;n.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&&fo("apple_pay",s,e,t,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&fo("google_pay",s,e,t,u)}}};t.get.onPaymentRequestLoad(l)}})},fo=(r,e,t,n,o)=>B.stripePR.run({context:t,checkoutPaymentMethod:Qt(t.checkoutPaymentMethods,r),nonCdeFormInputs:be(t.formDiv),formCallbacks:n,customParams:{provider:r,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__:Ee,err__:Ce}=U("op-form"),Se=class Se{constructor(e){this.cdeLoadEvent=new sr,this.anyCdeConn=new sr,this.context=new sr,this.initFlows=Sl(),this.startFormInit=async()=>{try{Ee("Initializing OpenPay form:"),Ee("├ Waiting for CDE load event...");const t=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:ho});Ee("├ CDE load event received"),Ee("├ Waiting for CDE connection...");const n=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:ho});Ee("├ CDE connection received"),Ee("├ Creating OJS context, setting up handlers...");const o=Se.buildOjsFlowContext(this.config,t,n,this.getFormDiv());this.context.set(o),Il(this.initFlows,o,this.formCallbacks),Ee("├ Starting OJS init flows..."),await Cl(this.initFlows,o,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),Ee("╰ Done initializing OJS flows.")}catch(t){const n=ue(t);Ce("╰ Error initializing OP form:",n),this.formCallbacks.get.onLoadError(n)}},this.setFormHeight=t=>{this.formProperties.height=t,this.registeredElements&&Object.values(this.registeredElements).forEach(n=>{n&&(n.node.style.height=t)})},this.onCdeLoaded=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.set(t)},this.onCdeLoadError=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.throw(new Error(t),t)},this.createElement=(t,n={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const o=ks.parse(t),s=document.createElement("iframe"),i=this.buildQueryString(n);s.name=`${o}-element`;const c=new URL(`/app/v1/${s.name}/`,this.config.baseUrl);return c.search=i.toString(),s.src=c.href,s.style.border="none",s.style.width="100%",this.registerIframe(o,s)},this.registerIframe=(t,n)=>{const o={type:t,node:n,mount:s=>{var i;return(i=document.querySelector(s))==null?void 0:i.appendChild(n)}};return this.connectToElement({type:o.type,node:o.node}),this.registeredElements||(this.registeredElements={[Ke.CARD]:void 0,[Ke.CARD_NUMBER]:void 0,[Ke.CARD_EXPIRY]:void 0,[Ke.CARD_CVC]:void 0}),this.registeredElements[t]=o,o},this.buildQueryString=t=>{const n=new URLSearchParams;return n.append("referer",this.referrer),n.append("formId",this.formId),t.styles&&n.append("styles",sa(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{xl(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Ce("[FORM] Error connecting to CDE iframe",n))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{const t=this.context.getValueIfLoadedElse(null);if(!t){Ce("Please wait for the form to finish loading before submitting.");return}B.commonCC.run({context:t,checkoutPaymentMethod:Qt(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:be(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){Ce("Please wait for the form to finish loading before getting available payment methods.");return}const n={airwallexGooglePay:Q.airwallexGooglePay,airwallexApplePay:Q.airwallexApplePay,authorizeNetGooglePay:Q.authorizenetGooglePay,authorizeNetApplePay:Q.authorizenetApplePay};return Object.entries(this.initFlows).map(([o,s])=>({name:n[o]??o,...s.publisher.getValueIfLoadedElse(null)}))},this.generalSubmit=(t,n)=>{const o=this.context.getValueIfLoadedElse(null);if(!o){Ce("Please wait for the form to finish loading before submitting.");return}switch(t){case Q.pockytPaypal:return B.pockytPaypal.run({context:o,checkoutPaymentMethod:Qt(o.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:be(o.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:n},initResult:void 0});case Q.airwallexGooglePay:{const s=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Ce("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case Q.airwallexApplePay:{const s=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!s){Ce("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case Q.authorizenetGooglePay:{const s=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Ce("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case Q.authorizenetApplePay:{const s=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!s){Ce("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}default:gr(t)}},this.submit=this.submitCard,this.destroy=()=>{Ee("Destroying OpenPay form...");for(const t of Object.values(this.registeredElements??{}))t&&t.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.registeredElements=null,delete window.ojs},this.updateCallbacks=t=>{this.formCallbacks.setCallbacks(t)},Se.assignAsSingleton(this),this.ojsVersion="0.2.13",this.ojsReleaseVersion="0.2.13",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Nr.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${rn()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Tl,this.eventHandler=new Al(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),window.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}};Se.ojsFlows=B,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,t,n,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??De).origin,formDiv:o,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Mr=Se;ge.FieldName=m,ge.OpenPayForm=Mr,ge.SubmitMethod=bs,ge.SubmitMethods=Q,Object.defineProperty(ge,Symbol.toStringTag,{value:"Module"})});
25
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function ar(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var Mt=function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var c=at(i),l=c.next();!l.done;l=c.next()){var u=l.value;u.remove(this)}}catch(w){e={error:w}}finally{try{l&&!l.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(B(d))try{d()}catch(w){s=w instanceof Nr?w.errors:[w]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var _=at(p),f=_.next();!f.done;f=_.next()){var h=f.value;try{so(h)}catch(w){s=s??[],w instanceof Nr?s=or(or([],nr(s)),nr(w.errors)):s.push(w)}}}catch(w){n={error:w}}finally{try{f&&!f.done&&(o=_.return)&&o.call(_)}finally{if(n)throw n.error}}}if(s)throw new Nr(s)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)so(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&ar(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&ar(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),no=Mt.EMPTY;function oo(r){return r instanceof Mt||r&&"closed"in r&&B(r.remove)&&B(r.add)&&B(r.unsubscribe)}function so(r){B(r)?r():r.unsubscribe()}var ao={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},io={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,or([r,e],nr(t)))},clearTimeout:function(r){var e=io.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function co(r){io.setTimeout(function(){throw r})}function lo(){}function ir(r){r()}var Mr=function(r){De(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,oo(t)&&t.add(n)):n.destination=tl,n}return e.create=function(t,n,o){return new jr(t,n,o)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Mt),Qc=Function.prototype.bind;function Dr(r,e){return Qc.call(r,e)}var Xc=function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){cr(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){cr(n)}else cr(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){cr(t)}},r}(),jr=function(r){De(e,r);function e(t,n,o){var s=r.call(this)||this,i;if(B(t)||!t)i={next:t??void 0,error:n??void 0,complete:o??void 0};else{var c;s&&ao.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&Dr(t.next,c),error:t.error&&Dr(t.error,c),complete:t.complete&&Dr(t.complete,c)}):i=t}return s.destination=new Xc(i),s}return e}(Mr);function cr(r){co(r)}function el(r){throw r}var tl={closed:!0,next:lo,error:el,complete:lo},Lr=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function rl(r){return r}function nl(r){return r.length===0?rl:r.length===1?r[0]:function(t){return r.reduce(function(n,o){return o(n)},t)}}var Ce=function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var o=this,s=sl(e)?e:new jr(e,t,n);return ir(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},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=uo(t),new t(function(o,s){var i=new jr({next:function(c){try{e(c)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});n.subscribe(i)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Lr]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return nl(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=uo(e),new e(function(n,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return n(s)})})},r.create=function(e){return new r(e)},r}();function uo(r){var e;return(e=r??ao.Promise)!==null&&e!==void 0?e:Promise}function ol(r){return r&&B(r.next)&&B(r.error)&&B(r.complete)}function sl(r){return r&&r instanceof Mr||ol(r)&&oo(r)}function al(r){return B(r==null?void 0:r.lift)}function il(r){return function(e){if(al(e))return e.lift(function(t){try{return r(t,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function cl(r,e,t,n,o){return new ll(r,e,t,n,o)}var ll=function(r){De(e,r);function e(t,n,o,s,i,c){var l=r.call(this,t)||this;return l.onFinalize=i,l.shouldUnsubscribe=c,l._next=n?function(u){try{n(u)}catch(d){t.error(d)}}:r.prototype._next,l._error=s?function(u){try{s(u)}catch(d){t.error(d)}finally{this.unsubscribe()}}:r.prototype._error,l._complete=o?function(){try{o()}catch(u){t.error(u)}finally{this.unsubscribe()}}:r.prototype._complete,l}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;r.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(Mr),ul=sr(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),po=function(r){De(e,r);function e(){var t=r.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var n=new fo(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new ul},e.prototype.next=function(t){var n=this;ir(function(){var o,s;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var i=at(n.currentObservers),c=i.next();!c.done;c=i.next()){var l=c.value;l.next(t)}}catch(u){o={error:u}}finally{try{c&&!c.done&&(s=i.return)&&s.call(i)}finally{if(o)throw o.error}}}})},e.prototype.error=function(t){var n=this;ir(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=t;for(var o=n.observers;o.length;)o.shift().error(t)}})},e.prototype.complete=function(){var t=this;ir(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var n=t.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,o=this,s=o.hasError,i=o.isStopped,c=o.observers;return s||i?no:(this.currentObservers=null,c.push(t),new Mt(function(){n.currentObservers=null,ar(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,o=n.hasError,s=n.thrownError,i=n.isStopped;o?t.error(s):i&&t.complete()},e.prototype.asObservable=function(){var t=new Ce;return t.source=this,t},e.create=function(t,n){return new fo(t,n)},e}(Ce),fo=function(r){De(e,r);function e(t,n){var o=r.call(this)||this;return o.destination=t,o.source=n,o}return e.prototype.next=function(t){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,t)},e.prototype.error=function(t){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&o!==void 0?o:no},e}(po),dl={now:function(){return Date.now()},delegate:void 0},pl=function(r){De(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(Mt),ho={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,or([r,e],nr(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},fl=function(r){De(e,r);function e(t,n){var o=r.call(this,t,n)||this;return o.scheduler=t,o.work=n,o.pending=!1,o}return e.prototype.schedule=function(t,n){var o;if(n===void 0&&(n=0),this.closed)return this;this.state=t;var s=this.id,i=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(i,s,n)),this.pending=!0,this.delay=n,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(i,this.id,n),this},e.prototype.requestAsyncId=function(t,n,o){return o===void 0&&(o=0),ho.setInterval(t.flush.bind(t,this),o)},e.prototype.recycleAsyncId=function(t,n,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return n;n!=null&&ho.clearInterval(n)},e.prototype.execute=function(t,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(t,n);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,n){var o=!1,s;try{this.work(t)}catch(i){o=!0,s=i||new Error("Scheduled action threw falsy error")}if(o)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,o=t.scheduler,s=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,ar(s,this),n!=null&&(this.id=this.recycleAsyncId(o,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(pl),mo=function(){function r(e,t){t===void 0&&(t=r.now),this.schedulerActionCtor=e,this.now=t}return r.prototype.schedule=function(e,t,n){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},r.now=dl.now,r}(),hl=function(r){De(e,r);function e(t,n){n===void 0&&(n=mo.now);var o=r.call(this,t,n)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(t){var n=this.actions;if(this._active){n.push(t);return}var o;this._active=!0;do if(o=t.execute(t.state,t.delay))break;while(t=n.shift());if(this._active=!1,o){for(;t=n.shift();)t.unsubscribe();throw o}},e}(mo),ml=new hl(fl),yl=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function _l(r){return B(r==null?void 0:r.then)}function gl(r){return B(r[Lr])}function vl(r){return Symbol.asyncIterator&&B(r==null?void 0:r[Symbol.asyncIterator])}function wl(r){return new TypeError("You provided "+(r!==null&&typeof r=="object"?"an invalid object":"'"+r+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function bl(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var kl=bl();function El(r){return B(r==null?void 0:r[kl])}function Cl(r){return Hc(this,arguments,function(){var t,n,o,s;return ro(this,function(i){switch(i.label){case 0:t=r.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,it(t.read())];case 3:return n=i.sent(),o=n.value,s=n.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 t.releaseLock(),[7];case 10:return[2]}})})}function Sl(r){return B(r==null?void 0:r.getReader)}function Pl(r){if(r instanceof Ce)return r;if(r!=null){if(gl(r))return Al(r);if(yl(r))return xl(r);if(_l(r))return Il(r);if(vl(r))return yo(r);if(El(r))return Tl(r);if(Sl(r))return Rl(r)}throw wl(r)}function Al(r){return new Ce(function(e){var t=r[Lr]();if(B(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function xl(r){return new Ce(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function Il(r){return new Ce(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,co)})}function Tl(r){return new Ce(function(e){var t,n;try{for(var o=at(r),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(c){t={error:c}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}e.complete()})}function yo(r){return new Ce(function(e){Ol(r,e).catch(function(t){return e.error(t)})})}function Rl(r){return yo(Cl(r))}function Ol(r,e){var t,n,o,s;return Kc(this,void 0,void 0,function(){var i,c;return ro(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),t=Jc(r),l.label=1;case 1:return[4,t.next()];case 2:if(n=l.sent(),!!n.done)return[3,4];if(i=n.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]),n&&!n.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Nl(r,e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(s),!o)return s}function Ml(r,e){var t=B(r)?r:function(){return r},n=function(o){return o.error(t())};return new Ce(n)}var Dl=sr(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function jl(r,e){return new Promise(function(t,n){var o=!1,s;r.subscribe({next:function(i){s=i,o=!0},error:n,complete:function(){o?t(s):n(new Dl)}})})}function Ll(r){return r instanceof Date&&!isNaN(r)}var Fl=sr(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Ul(r,e){var t=Ll(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,o=t.each,s=t.with,i=s===void 0?$l:s,c=t.scheduler,l=c===void 0?ml:c,u=t.meta,d=u===void 0?null:u;if(n==null&&o==null)throw new TypeError("No timeout provided.");return il(function(p,_){var f,h,w=null,x=0,C=function(T){h=Nl(_,l,function(){try{f.unsubscribe(),Pl(i({meta:d,lastValue:w,seen:x})).subscribe(_)}catch(S){_.error(S)}},T)};f=p.subscribe(cl(_,function(T){h==null||h.unsubscribe(),x++,_.next(w=T),o>0&&C(o)},void 0,void 0,function(){h!=null&&h.closed||h==null||h.unsubscribe(),w=null})),!x&&C(n!=null?typeof n=="number"?n:+n-l.now():o)})}function $l(r){throw new Fl(r)}class lr{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,t)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:t},this._subject.error(e)},this.getValueIfLoadedElse=e=>this._current.status==="success"?this._current.loadedValue:e,this.subscribe=e=>{if(this._current.status==="success"){e(this._current);return}this._current.status==="error"&&e(this._current);const t=this._subject.subscribe({next:()=>{if(this._current.status!=="success")throw new Error("Invalid state (next): please make sure to update _current before the subject");e(this._current),t.unsubscribe()},error:()=>{if(this._current.status!=="error")throw new Error("Invalid state (error): please make sure to update _current before the subject");e(this._current)}})},this.waitForLoad=e=>{if(this._current.status==="success")return Promise.resolve(this._current.loadedValue);if(this._current.status==="error")return Promise.reject(this._current.error);this._current.status!=="initial"&&Yt(this._current);const t={first:e.timeoutSec*1e3,with:()=>Ml(()=>new Error(e.timeoutErrMsg))};return jl(this._subject.pipe(Ul(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new po}get current(){return this._current}}const{log__:Zl,err__:Vl}=L("init-flows"),ze=(r,e)=>{const t=new lr;return{publisher:t,initialize:async n=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(n);Zl(`✔ ${r} flow initialized successfully. Result:`,o),t.set(o)}catch(o){Vl(`𝙭 ${r} flow initialization failed. Error:`,fe(o),"Details:",o),t.throw(o,fe(o))}}}},zl=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},Gl=()=>({stripePR:ze("Stripe PR",Z.stripePR.init),stripeLink:ze("Stripe Link",Z.stripeLink.init),airwallexGooglePay:ze("Airwallex GooglePay",Z.airwallexGooglePay.init),airwallexApplePay:ze("Airwallex ApplePay",Z.airwallexApplePay.init),loop:ze("Loop",Z.loopCrypto.init),authorizeNetGooglePay:ze("Authnet GooglePay",Z.authorizeNetGooglePay.init),authorizeNetApplePay:ze("Authnet ApplePay",Z.authorizeNetApplePay.init)}),{err__:Bl}=L("form-callbacks"),le=a.function().optional(),_o=a.object({onFocus:le,onBlur:le,onChange:le,onLoad:le,onLoadError:le,onValidationError:le,onCheckoutStarted:le,onCheckoutSuccess:le,onSetupPaymentMethodSuccess:le,onCheckoutError:le,onPaymentRequestLoad:le}),ge=class ge{constructor(){this.setCallbacks=e=>{this._callbacks=ge.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const o=Ps(t,n??ge.NOOP,Bl);this._callbacks[t]=o})},this._callbacks=ge.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ge.NOOP=()=>{},ge.createEmptyCallbacks=()=>{const e={};return Object.keys(_o.keyof().enum).forEach(t=>{e[t]=ge.NOOP}),e},ge.fromObject=e=>{const t=new ge;return t.setCallbacks(_o.parse(e)),t};let Fr=ge;class ql{constructor(e,t,n,o){this.handleMessage=s=>{if(!s.source)throw new Error("No source found");if(go(s.origin)!==go(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=ya(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=n,this.internalCallbacks=o}}const go=r=>new URL(r).origin;async function Yl(r,e){const n=await dn({iframe:r,debug:!1,childOrigin:e}).promise,o=await Fa(n);if(!Ua(n,o))throw new Error("Got invalid CDE connection object");return n}class Wl{constructor(){this.connections=new Map}addConnection(e,t){this.connections.set(e,t)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Kl=(r,e,t)=>{const{stripePR:n}=r;n.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&vo("apple_pay",s,e,t,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&vo("google_pay",s,e,t,u)}}};t.get.onPaymentRequestLoad(l)}})},vo=(r,e,t,n,o)=>Z.stripePR.run({context:t,checkoutPaymentMethod:Nt(t.checkoutPaymentMethods,r),nonCdeFormInputs:he(t.formDiv),formCallbacks:n,customParams:{provider:r,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__:Se,err__:Pe}=L("op-form"),Ae=class Ae{constructor(e){this.cdeLoadEvent=new lr,this.anyCdeConn=new lr,this.context=new lr,this.initFlows=Gl(),this.startFormInit=async()=>{try{Se("Initializing OpenPay form:"),Se("├ Waiting for CDE load event...");const t=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:wo});Se("├ CDE load event received"),Se("├ Waiting for CDE connection...");const n=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:wo});Se("├ CDE connection received"),Se("├ Creating OJS context, setting up handlers...");const o=Ae.buildOjsFlowContext(this.config,t,n,this.getFormDiv());this.context.set(o),Kl(this.initFlows,o,this.formCallbacks),Se("├ Starting OJS init flows..."),await zl(this.initFlows,o,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),Se("╰ Done initializing OJS flows.")}catch(t){const n=fe(t);Pe("╰ Error initializing OP form:",n),this.formCallbacks.get.onLoadError(n)}},this.setFormHeight=t=>{this.formProperties.height=t,this.registeredElements&&Object.values(this.registeredElements).forEach(n=>{n&&(n.node.style.height=t)})},this.onCdeLoaded=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.set(t)},this.onCdeLoadError=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.throw(new Error(t),t)},this.createElement=(t,n={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const o=xs.parse(t),s=document.createElement("iframe"),i=this.buildQueryString(n);s.name=`${o}-element`;const c=new URL(`/app/v1/${s.name}/`,this.config.baseUrl);return c.search=i.toString(),s.src=c.href,s.style.border="none",s.style.width="100%",this.registerIframe(o,s)},this.registerIframe=(t,n)=>{const o={type:t,node:n,mount:s=>{var i;return(i=document.querySelector(s))==null?void 0:i.appendChild(n)}};return this.connectToElement({type:o.type,node:o.node}),this.registeredElements||(this.registeredElements={[Qe.CARD]:void 0,[Qe.CARD_NUMBER]:void 0,[Qe.CARD_EXPIRY]:void 0,[Qe.CARD_CVC]:void 0}),this.registeredElements[t]=o,o},this.buildQueryString=t=>{const n=new URLSearchParams;return n.append("referer",this.referrer),n.append("formId",this.formId),t.styles&&n.append("styles",da(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{Yl(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Pe("[FORM] Error connecting to CDE iframe",n))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{const t=this.context.getValueIfLoadedElse(null);if(!t){Pe("Please wait for the form to finish loading before submitting.");return}Z.commonCC.run({context:t,checkoutPaymentMethod:Nt(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:he(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){Pe("Please wait for the form to finish loading before getting available payment methods.");return}const n={airwallexGooglePay:ee.airwallexGooglePay,airwallexApplePay:ee.airwallexApplePay,authorizeNetGooglePay:ee.authorizenetGooglePay,authorizeNetApplePay:ee.authorizenetApplePay};return Object.entries(this.initFlows).map(([o,s])=>({name:n[o]??o,...s.publisher.getValueIfLoadedElse(null)}))},this.generalSubmit=(t,n)=>{const o=this.context.getValueIfLoadedElse(null);if(!o){Pe("Please wait for the form to finish loading before submitting.");return}switch(t){case ee.pockytPaypal:return Z.pockytPaypal.run({context:o,checkoutPaymentMethod:Nt(o.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:he(o.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:n},initResult:void 0});case ee.airwallexGooglePay:{const s=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Pe("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.airwallexApplePay:{const s=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!s){Pe("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.authorizenetGooglePay:{const s=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Pe("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.authorizenetApplePay:{const s=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!s){Pe("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.loopCrypto:{const s=this.initFlows.loop.publisher.current;if(!s.isSuccess)throw Error("Loop has not successfully initialized. Cannot submit.");return Z.loopCrypto.run({context:o,checkoutPaymentMethod:Nt(o.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:he(o.formDiv),formCallbacks:this.formCallbacks,customParams:n&&"success"in n&&n.success?{customer:n.customer,payin:n.payin,email:n.email,firstName:n.firstName,lastName:n.lastName,success:!0}:{detail:n.detail,email:n.email,firstName:n.firstName,lastName:n.lastName,success:!1},initResult:s.loadedValue})}default:Yt(t)}},this.submit=this.submitCard,this.destroy=()=>{Se("Destroying OpenPay form...");for(const t of Object.values(this.registeredElements??{}))t&&t.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.registeredElements=null,delete window.ojs},this.updateCallbacks=t=>{this.formCallbacks.setCallbacks(t)},Ae.assignAsSingleton(this),this.ojsVersion="0.2.16",this.ojsReleaseVersion="0.2.16-alpha.1b02bc3",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Fr.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${br()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Wl,this.eventHandler=new ql(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),window.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}};Ae.ojsFlows=Z,Ae.assignAsSingleton=e=>{if(Ae.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},Ae.getInstance=()=>window.ojs??null,Ae.buildOjsFlowContext=(e,t,n,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??je).origin,formDiv:o,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Ur=Ae;we.FieldName=y,we.OpenPayForm=Ur,we.SubmitMethod=As,we.SubmitMethods=ee,Object.defineProperty(we,Symbol.toStringTag,{value:"Module"})});