@getopenpay/openpay-js 0.2.8 → 0.2.10

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,13 +1,13 @@
1
- (function(Oe,Fe){typeof exports=="object"&&typeof module<"u"?Fe(exports):typeof define=="function"&&define.amd?define(["exports"],Fe):(Oe=typeof globalThis<"u"?globalThis:Oe||self,Fe(Oe.OpenPay={}))})(this,function(Oe){"use strict";const Fe="https://cde.getopenpay.com";var P;(function(r){r.assertEqual=s=>s;function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},r.getValidEnumValues=s=>{const o=r.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(const c of o)a[c]=s[c];return r.objectValues(a)},r.objectValues=s=>r.objectKeys(s).map(function(o){return s[o]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},r.find=(s,o)=>{for(const a of s)if(o(a))return a},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}r.joinValues=n,r.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(P||(P={}));var Qt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Qt||(Qt={}));const _=P.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),be=r=>{switch(typeof r){case"undefined":return _.undefined;case"string":return _.string;case"number":return isNaN(r)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":return Array.isArray(r)?_.array:r===null?_.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?_.promise:typeof Map<"u"&&r instanceof Map?_.map:typeof Set<"u"&&r instanceof Set?_.set:typeof Date<"u"&&r instanceof Date?_.date:_.object;default:return _.unknown}},f=P.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"]),Wn=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class G 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(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let c=n,u=0;for(;u<a.path.length;){const l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(t(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}};return s(this),n}static assert(e){if(!(e instanceof G))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,P.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}G.create=r=>new G(r);const Ue=(r,e)=>{let t;switch(r.code){case f.invalid_type:r.received===_.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case f.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,P.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:t=`Unrecognized key(s) in object: ${P.joinValues(r.keys,", ")}`;break;case f.invalid_union:t="Invalid input";break;case f.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${P.joinValues(r.options)}`;break;case f.invalid_enum_value:t=`Invalid enum value. Expected ${P.joinValues(r.options)}, received '${r.received}'`;break;case f.invalid_arguments:t="Invalid function arguments";break;case f.invalid_return_type:t="Invalid function return type";break;case f.invalid_date:t="Invalid date";break;case f.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}"`:P.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case f.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 f.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 f.custom:t="Invalid input";break;case f.invalid_intersection_types:t="Intersection results could not be merged";break;case f.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case f.not_finite:t="Number must be finite";break;default:t=e.defaultError,P.assertNever(r)}return{message:t}};let xr=Ue;function Hn(r){xr=r}function St(){return xr}const Ct=r=>{const{data:e,path:t,errorMaps:n,issueData:s}=r,o=[...t,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let c="";const u=n.filter(l=>!!l).slice().reverse();for(const l of u)c=l(a,{data:e,defaultError:c}).message;return{...s,path:o,message:c}},Kn=[];function y(r,e){const t=St(),n=Ct({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Ue?void 0:Ue].filter(s=>!!s)});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 s of t){if(s.status==="aborted")return E;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const s of t){const o=await s.key,a=await s.value;n.push({key:o,value:a})}return Z.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return E;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[o.value]=a.value)}return{status:e.value,value:n}}}const E=Object.freeze({status:"aborted"}),$e=r=>({status:"dirty",value:r}),z=r=>({status:"valid",value:r}),Xt=r=>r.status==="aborted",er=r=>r.status==="dirty",tt=r=>r.status==="valid",rt=r=>typeof Promise<"u"&&r instanceof Promise;function xt(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 Ar(r,e,t,n,s){if(typeof e=="function"?r!==e||!s:!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 v;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(v||(v={}));var nt,st;class se{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}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 Pr=(r,e)=>{if(tt(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 G(r.common.issues);return this._error=t,this._error}}};function S(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:s}=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:s}:{errorMap:(a,c)=>{var u,l;const{message:d}=r;return a.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(u=d??n)!==null&&u!==void 0?u:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(l=d??t)!==null&&l!==void 0?l:c.defaultError}},description:s}}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 be(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:be(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:be(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(rt(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 s={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:be(e)},o=this._parseSync({data:e,path:s.path,parent:s});return Pr(s,o)}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:be(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(rt(s)?s:Promise.resolve(s));return Pr(n,o)}refine(e,t){const n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,o)=>{const a=e(s),c=()=>o.addIssue({code:f.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new Q({schema:this,typeName:k.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return ie.create(this,this._def)}nullable(){return Ce.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return J.create(this,this._def)}promise(){return Be.create(this,this._def)}or(e){return ct.create([this,e],this._def)}and(e){return lt.create(this,e,this._def)}transform(e){return new Q({...S(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ht({...S(this._def),innerType:this,defaultValue:t,typeName:k.ZodDefault})}brand(){return new nr({typeName:k.ZodBranded,type:this,...S(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new mt({...S(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 yt.create(this,e)}readonly(){return _t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Jn=/^c[^\s-]{8,}$/i,Qn=/^[0-9a-z]+$/,Xn=/^[0-9A-HJKMNP-TV-Z]{26}$/,es=/^[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,ts=/^[a-z0-9_-]{21}$/i,rs=/^[-+]?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)?)??$/,ns=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ss="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let tr;const os=/^(?:(?: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])$/,is=/^(([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})))$/,as=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Tr="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",cs=new RegExp(`^${Tr}$`);function Ir(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 ls(r){return new RegExp(`^${Ir(r)}$`)}function Or(r){let e=`${Tr}T${Ir(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 us(r,e){return!!((e==="v4"||!e)&&os.test(r)||(e==="v6"||!e)&&is.test(r))}class K extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==_.string){const o=this._getOrReturnCtx(e);return y(o,{code:f.invalid_type,expected:_.string,received:o.parsedType}),E}const n=new Z;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:f.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const a=e.data.length>o.value,c=e.data.length<o.value;(a||c)&&(s=this._getOrReturnCtx(e,s),a?y(s,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&y(s,{code:f.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")ns.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"email",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")tr||(tr=new RegExp(ss,"u")),tr.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"emoji",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")es.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"uuid",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")ts.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"nanoid",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")Jn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"cuid",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Qn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"cuid2",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Xn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"ulid",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),y(s,{validation:"url",code:f.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"regex",code:f.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),y(s,{code:f.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),y(s,{code:f.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),y(s,{code:f.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Or(o).test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{code:f.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?cs.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{code:f.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?ls(o).test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{code:f.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?rs.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"duration",code:f.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?us(e.data,o.version)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"ip",code:f.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?as.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"base64",code:f.invalid_string,message:o.message}),n.dirty()):P.assertNever(o);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:f.invalid_string,...v.errToObj(n)})}_addCheck(e){return new K({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...v.errToObj(e)})}url(e){return this._addCheck({kind:"url",...v.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...v.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...v.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...v.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...v.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...v.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...v.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...v.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...v.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,...v.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,...v.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...v.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...v.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...v.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...v.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...v.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...v.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...v.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...v.errToObj(t)})}nonempty(e){return this.min(1,v.errToObj(e))}trim(){return new K({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new K({...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}}K.create=r=>{var e;return new K({checks:[],typeName:k.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...S(r)})};function ds(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,o=parseInt(r.toFixed(s).replace(".","")),a=parseInt(e.toFixed(s).replace(".",""));return o%a/Math.pow(10,s)}class ke 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)!==_.number){const o=this._getOrReturnCtx(e);return y(o,{code:f.invalid_type,expected:_.number,received:o.parsedType}),E}let n;const s=new Z;for(const o of this._def.checks)o.kind==="int"?P.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:f.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:f.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:f.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?ds(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),y(n,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:f.not_finite,message:o.message}),s.dirty()):P.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,s){return new ke({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(s)}]})}_addCheck(e){return new ke({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:v.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:v.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.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"&&P.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)}}ke.create=r=>new ke({checks:[],typeName:k.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...S(r)});class Ee 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)!==_.bigint){const o=this._getOrReturnCtx(e);return y(o,{code:f.invalid_type,expected:_.bigint,received:o.parsedType}),E}let n;const s=new Z;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:f.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:f.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),y(n,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):P.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,s){return new Ee({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(s)}]})}_addCheck(e){return new Ee({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.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}}Ee.create=r=>{var e;return new Ee({checks:[],typeName:k.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...S(r)})};class ot extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==_.boolean){const n=this._getOrReturnCtx(e);return y(n,{code:f.invalid_type,expected:_.boolean,received:n.parsedType}),E}return z(e.data)}}ot.create=r=>new ot({typeName:k.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...S(r)});class Re extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==_.date){const o=this._getOrReturnCtx(e);return y(o,{code:f.invalid_type,expected:_.date,received:o.parsedType}),E}if(isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return y(o,{code:f.invalid_date}),E}const n=new Z;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:f.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:f.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):P.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Re({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:v.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:v.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}}Re.create=r=>new Re({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:k.ZodDate,...S(r)});class At extends x{_parse(e){if(this._getType(e)!==_.symbol){const n=this._getOrReturnCtx(e);return y(n,{code:f.invalid_type,expected:_.symbol,received:n.parsedType}),E}return z(e.data)}}At.create=r=>new At({typeName:k.ZodSymbol,...S(r)});class it extends x{_parse(e){if(this._getType(e)!==_.undefined){const n=this._getOrReturnCtx(e);return y(n,{code:f.invalid_type,expected:_.undefined,received:n.parsedType}),E}return z(e.data)}}it.create=r=>new it({typeName:k.ZodUndefined,...S(r)});class at extends x{_parse(e){if(this._getType(e)!==_.null){const n=this._getOrReturnCtx(e);return y(n,{code:f.invalid_type,expected:_.null,received:n.parsedType}),E}return z(e.data)}}at.create=r=>new at({typeName:k.ZodNull,...S(r)});class Ze extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return z(e.data)}}Ze.create=r=>new Ze({typeName:k.ZodAny,...S(r)});class Ne extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return z(e.data)}}Ne.create=r=>new Ne({typeName:k.ZodUnknown,...S(r)});class fe extends x{_parse(e){const t=this._getOrReturnCtx(e);return y(t,{code:f.invalid_type,expected:_.never,received:t.parsedType}),E}}fe.create=r=>new fe({typeName:k.ZodNever,...S(r)});class Pt extends x{_parse(e){if(this._getType(e)!==_.undefined){const n=this._getOrReturnCtx(e);return y(n,{code:f.invalid_type,expected:_.void,received:n.parsedType}),E}return z(e.data)}}Pt.create=r=>new Pt({typeName:k.ZodVoid,...S(r)});class J extends x{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==_.array)return y(t,{code:f.invalid_type,expected:_.array,received:t.parsedType}),E;if(s.exactLength!==null){const a=t.data.length>s.exactLength.value,c=t.data.length<s.exactLength.value;(a||c)&&(y(t,{code:a?f.too_big:f.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(y(t,{code:f.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(y(t,{code:f.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,c)=>s.type._parseAsync(new se(t,a,t.path,c)))).then(a=>Z.mergeArray(n,a));const o=[...t.data].map((a,c)=>s.type._parseSync(new se(t,a,t.path,c)));return Z.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new J({...this._def,minLength:{value:e,message:v.toString(t)}})}max(e,t){return new J({...this._def,maxLength:{value:e,message:v.toString(t)}})}length(e,t){return new J({...this._def,exactLength:{value:e,message:v.toString(t)}})}nonempty(e){return this.min(1,e)}}J.create=(r,e)=>new J({type:r,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...S(e)});function Ve(r){if(r instanceof R){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=ie.create(Ve(n))}return new R({...r._def,shape:()=>e})}else return r instanceof J?new J({...r._def,type:Ve(r.element)}):r instanceof ie?ie.create(Ve(r.unwrap())):r instanceof Ce?Ce.create(Ve(r.unwrap())):r instanceof oe?oe.create(r.items.map(e=>Ve(e))):r}class R 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=P.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==_.object){const l=this._getOrReturnCtx(e);return y(l,{code:f.invalid_type,expected:_.object,received:l.parsedType}),E}const{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof fe&&this._def.unknownKeys==="strip"))for(const l in s.data)a.includes(l)||c.push(l);const u=[];for(const l of a){const d=o[l],h=s.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new se(s,h,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof fe){const l=this._def.unknownKeys;if(l==="passthrough")for(const d of c)u.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")c.length>0&&(y(s,{code:f.unrecognized_keys,keys:c}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const d of c){const h=s.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new se(s,h,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const d of u){const h=await d.key,w=await d.value;l.push({key:h,value:w,alwaysSet:d.alwaysSet})}return l}).then(l=>Z.mergeObjectSync(n,l)):Z.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new R({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var s,o,a,c;const u=(a=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,t,n).message)!==null&&a!==void 0?a:n.defaultError;return t.code==="unrecognized_keys"?{message:(c=v.errToObj(e).message)!==null&&c!==void 0?c:u}:{message:u}}}:{}})}strip(){return new R({...this._def,unknownKeys:"strip"})}passthrough(){return new R({...this._def,unknownKeys:"passthrough"})}extend(e){return new R({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new R({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 R({...this._def,catchall:e})}pick(e){const t={};return P.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new R({...this._def,shape:()=>t})}omit(e){const t={};return P.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new R({...this._def,shape:()=>t})}deepPartial(){return Ve(this)}partial(e){const t={};return P.objectKeys(this.shape).forEach(n=>{const s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}),new R({...this._def,shape:()=>t})}required(e){const t={};return P.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ie;)o=o._def.innerType;t[n]=o}}),new R({...this._def,shape:()=>t})}keyof(){return Rr(P.objectKeys(this.shape))}}R.create=(r,e)=>new R({shape:()=>r,unknownKeys:"strip",catchall:fe.create(),typeName:k.ZodObject,...S(e)}),R.strictCreate=(r,e)=>new R({shape:()=>r,unknownKeys:"strict",catchall:fe.create(),typeName:k.ZodObject,...S(e)}),R.lazycreate=(r,e)=>new R({shape:r,unknownKeys:"strip",catchall:fe.create(),typeName:k.ZodObject,...S(e)});class ct extends x{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function s(o){for(const c of o)if(c.result.status==="valid")return c.result;for(const c of o)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;const a=o.map(c=>new G(c.ctx.common.issues));return y(t,{code:f.invalid_union,unionErrors:a}),E}if(t.common.async)return Promise.all(n.map(async o=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const u of n){const l={...t,common:{...t.common,issues:[]},parent:null},d=u._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;const c=a.map(u=>new G(u));return y(t,{code:f.invalid_union,unionErrors:c}),E}}get options(){return this._def.options}}ct.create=(r,e)=>new ct({options:r,typeName:k.ZodUnion,...S(e)});const pe=r=>r instanceof dt?pe(r.schema):r instanceof Q?pe(r.innerType()):r instanceof ft?[r.value]:r instanceof Se?r.options:r instanceof pt?P.objectValues(r.enum):r instanceof ht?pe(r._def.innerType):r instanceof it?[void 0]:r instanceof at?[null]:r instanceof ie?[void 0,...pe(r.unwrap())]:r instanceof Ce?[null,...pe(r.unwrap())]:r instanceof nr||r instanceof _t?pe(r.unwrap()):r instanceof mt?pe(r._def.innerType):[];class Tt extends x{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.object)return y(t,{code:f.invalid_type,expected:_.object,received:t.parsedType}),E;const n=this.discriminator,s=t.data[n],o=this.optionsMap.get(s);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(y(t,{code:f.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 s=new Map;for(const o of t){const a=pe(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const c of a){if(s.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);s.set(c,o)}}return new Tt({typeName:k.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...S(n)})}}function rr(r,e){const t=be(r),n=be(e);if(r===e)return{valid:!0,data:r};if(t===_.object&&n===_.object){const s=P.objectKeys(e),o=P.objectKeys(r).filter(c=>s.indexOf(c)!==-1),a={...r,...e};for(const c of o){const u=rr(r[c],e[c]);if(!u.valid)return{valid:!1};a[c]=u.data}return{valid:!0,data:a}}else if(t===_.array&&n===_.array){if(r.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<r.length;o++){const a=r[o],c=e[o],u=rr(a,c);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===_.date&&n===_.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class lt extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(o,a)=>{if(Xt(o)||Xt(a))return E;const c=rr(o.value,a.value);return c.valid?((er(o)||er(a))&&t.dirty(),{status:t.value,value:c.data}):(y(n,{code:f.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(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}lt.create=(r,e,t)=>new lt({left:r,right:e,typeName:k.ZodIntersection,...S(t)});class oe extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.array)return y(n,{code:f.invalid_type,expected:_.array,received:n.parsedType}),E;if(n.data.length<this._def.items.length)return y(n,{code:f.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),E;!this._def.rest&&n.data.length>this._def.items.length&&(y(n,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const o=[...n.data].map((a,c)=>{const u=this._def.items[c]||this._def.rest;return u?u._parse(new se(n,a,n.path,c)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>Z.mergeArray(t,a)):Z.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new oe({...this._def,rest:e})}}oe.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new oe({items:r,typeName:k.ZodTuple,rest:null,...S(e)})};class ut 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!==_.object)return y(n,{code:f.invalid_type,expected:_.object,received:n.parsedType}),E;const s=[],o=this._def.keyType,a=this._def.valueType;for(const c in n.data)s.push({key:o._parse(new se(n,c,n.path,c)),value:a._parse(new se(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?Z.mergeObjectAsync(t,s):Z.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof x?new ut({keyType:e,valueType:t,typeName:k.ZodRecord,...S(n)}):new ut({keyType:K.create(),valueType:e,typeName:k.ZodRecord,...S(t)})}}class It 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!==_.map)return y(n,{code:f.invalid_type,expected:_.map,received:n.parsedType}),E;const s=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([c,u],l)=>({key:s._parse(new se(n,c,n.path,[l,"key"])),value:o._parse(new se(n,u,n.path,[l,"value"]))}));if(n.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const u of a){const l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return E;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}})}else{const c=new Map;for(const u of a){const l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return E;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}}}}It.create=(r,e,t)=>new It({valueType:e,keyType:r,typeName:k.ZodMap,...S(t)});class Me extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.set)return y(n,{code:f.invalid_type,expected:_.set,received:n.parsedType}),E;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(y(n,{code:f.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(y(n,{code:f.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const o=this._def.valueType;function a(u){const l=new Set;for(const d of u){if(d.status==="aborted")return E;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}const c=[...n.data.values()].map((u,l)=>o._parse(new se(n,u,n.path,l)));return n.common.async?Promise.all(c).then(u=>a(u)):a(c)}min(e,t){return new Me({...this._def,minSize:{value:e,message:v.toString(t)}})}max(e,t){return new Me({...this._def,maxSize:{value:e,message:v.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Me.create=(r,e)=>new Me({valueType:r,minSize:null,maxSize:null,typeName:k.ZodSet,...S(e)});class ze extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.function)return y(t,{code:f.invalid_type,expected:_.function,received:t.parsedType}),E;function n(c,u){return Ct({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,St(),Ue].filter(l=>!!l),issueData:{code:f.invalid_arguments,argumentsError:u}})}function s(c,u){return Ct({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,St(),Ue].filter(l=>!!l),issueData:{code:f.invalid_return_type,returnTypeError:u}})}const o={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Be){const c=this;return z(async function(...u){const l=new G([]),d=await c._def.args.parseAsync(u,o).catch(m=>{throw l.addIssue(n(u,m)),l}),h=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(h,o).catch(m=>{throw l.addIssue(s(h,m)),l})})}else{const c=this;return z(function(...u){const l=c._def.args.safeParse(u,o);if(!l.success)throw new G([n(u,l.error)]);const d=Reflect.apply(a,this,l.data),h=c._def.returns.safeParse(d,o);if(!h.success)throw new G([s(d,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ze({...this._def,args:oe.create(e).rest(Ne.create())})}returns(e){return new ze({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new ze({args:e||oe.create([]).rest(Ne.create()),returns:t||Ne.create(),typeName:k.ZodFunction,...S(n)})}}class dt 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})}}dt.create=(r,e)=>new dt({getter:r,typeName:k.ZodLazy,...S(e)});class ft extends x{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return y(t,{received:t.data,code:f.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:e.data}}get value(){return this._def.value}}ft.create=(r,e)=>new ft({value:r,typeName:k.ZodLiteral,...S(e)});function Rr(r,e){return new Se({values:r,typeName:k.ZodEnum,...S(e)})}class Se extends x{constructor(){super(...arguments),nt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return y(t,{expected:P.joinValues(n),received:t.parsedType,code:f.invalid_type}),E}if(xt(this,nt)||Ar(this,nt,new Set(this._def.values)),!xt(this,nt).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return y(t,{received:t.data,code:f.invalid_enum_value,options:n}),E}return z(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 Se.create(e,{...this._def,...t})}exclude(e,t=this._def){return Se.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}nt=new WeakMap,Se.create=Rr;class pt extends x{constructor(){super(...arguments),st.set(this,void 0)}_parse(e){const t=P.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==_.string&&n.parsedType!==_.number){const s=P.objectValues(t);return y(n,{expected:P.joinValues(s),received:n.parsedType,code:f.invalid_type}),E}if(xt(this,st)||Ar(this,st,new Set(P.getValidEnumValues(this._def.values))),!xt(this,st).has(e.data)){const s=P.objectValues(t);return y(n,{received:n.data,code:f.invalid_enum_value,options:s}),E}return z(e.data)}get enum(){return this._def.values}}st=new WeakMap,pt.create=(r,e)=>new pt({values:r,typeName:k.ZodNativeEnum,...S(e)});class Be extends x{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.promise&&t.common.async===!1)return y(t,{code:f.invalid_type,expected:_.promise,received:t.parsedType}),E;const n=t.parsedType===_.promise?t.data:Promise.resolve(t.data);return z(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Be.create=(r,e)=>new Be({type:r,typeName:k.ZodPromise,...S(e)});class Q 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),s=this._def.effect||null,o={addIssue:a=>{y(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async c=>{if(t.value==="aborted")return E;const u=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return u.status==="aborted"?E:u.status==="dirty"||t.value==="dirty"?$e(u.value):u});{if(t.value==="aborted")return E;const c=this._def.schema._parseSync({data:a,path:n.path,parent:n});return c.status==="aborted"?E:c.status==="dirty"||t.value==="dirty"?$e(c.value):c}}if(s.type==="refinement"){const a=c=>{const u=s.refinement(c,o);if(n.common.async)return Promise.resolve(u);if(u 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(),a(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(),a(c.value).then(()=>({status:t.value,value:c.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!tt(a))return a;const c=s.transform(a.value,o);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(a=>tt(a)?Promise.resolve(s.transform(a.value,o)).then(c=>({status:t.value,value:c})):a);P.assertNever(s)}}Q.create=(r,e,t)=>new Q({schema:r,typeName:k.ZodEffects,effect:e,...S(t)}),Q.createWithPreprocess=(r,e,t)=>new Q({schema:e,effect:{type:"preprocess",transform:r},typeName:k.ZodEffects,...S(t)});class ie extends x{_parse(e){return this._getType(e)===_.undefined?z(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ie.create=(r,e)=>new ie({innerType:r,typeName:k.ZodOptional,...S(e)});class Ce extends x{_parse(e){return this._getType(e)===_.null?z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ce.create=(r,e)=>new Ce({innerType:r,typeName:k.ZodNullable,...S(e)});class ht extends x{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===_.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ht.create=(r,e)=>new ht({innerType:r,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...S(e)});class mt extends x{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return rt(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new G(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new G(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}mt.create=(r,e)=>new mt({innerType:r,typeName:k.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...S(e)});class Ot extends x{_parse(e){if(this._getType(e)!==_.nan){const n=this._getOrReturnCtx(e);return y(n,{code:f.invalid_type,expected:_.nan,received:n.parsedType}),E}return{status:"valid",value:e.data}}}Ot.create=r=>new Ot({typeName:k.ZodNaN,...S(r)});const fs=Symbol("zod_brand");class nr 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 yt extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?E:o.status==="dirty"?(t.dirty(),$e(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?E:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new yt({in:e,out:t,typeName:k.ZodPipeline})}}class _t extends x{_parse(e){const t=this._def.innerType._parse(e),n=s=>(tt(s)&&(s.value=Object.freeze(s.value)),s);return rt(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}}_t.create=(r,e)=>new _t({innerType:r,typeName:k.ZodReadonly,...S(e)});function Nr(r,e={},t){return r?Ze.create().superRefine((n,s)=>{var o,a;if(!r(n)){const c=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,u=(a=(o=c.fatal)!==null&&o!==void 0?o:t)!==null&&a!==void 0?a:!0,l=typeof c=="string"?{message:c}:c;s.addIssue({code:"custom",...l,fatal:u})}}):Ze.create()}const ps={object:R.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 hs=(r,e={message:`Input not instance of ${r.name}`})=>Nr(t=>t instanceof r,e),Mr=K.create,jr=ke.create,ms=Ot.create,ys=Ee.create,Dr=ot.create,_s=Re.create,gs=At.create,vs=it.create,ws=at.create,bs=Ze.create,ks=Ne.create,Es=fe.create,Ss=Pt.create,Cs=J.create,xs=R.create,As=R.strictCreate,Ps=ct.create,Ts=Tt.create,Is=lt.create,Os=oe.create,Rs=ut.create,Ns=It.create,Ms=Me.create,js=ze.create,Ds=dt.create,Ls=ft.create,Fs=Se.create,Us=pt.create,$s=Be.create,Lr=Q.create,Zs=ie.create,Vs=Ce.create,zs=Q.createWithPreprocess,Bs=yt.create;var i=Object.freeze({__proto__:null,defaultErrorMap:Ue,setErrorMap:Hn,getErrorMap:St,makeIssue:Ct,EMPTY_PATH:Kn,addIssueToContext:y,ParseStatus:Z,INVALID:E,DIRTY:$e,OK:z,isAborted:Xt,isDirty:er,isValid:tt,isAsync:rt,get util(){return P},get objectUtil(){return Qt},ZodParsedType:_,getParsedType:be,ZodType:x,datetimeRegex:Or,ZodString:K,ZodNumber:ke,ZodBigInt:Ee,ZodBoolean:ot,ZodDate:Re,ZodSymbol:At,ZodUndefined:it,ZodNull:at,ZodAny:Ze,ZodUnknown:Ne,ZodNever:fe,ZodVoid:Pt,ZodArray:J,ZodObject:R,ZodUnion:ct,ZodDiscriminatedUnion:Tt,ZodIntersection:lt,ZodTuple:oe,ZodRecord:ut,ZodMap:It,ZodSet:Me,ZodFunction:ze,ZodLazy:dt,ZodLiteral:ft,ZodEnum:Se,ZodNativeEnum:pt,ZodPromise:Be,ZodEffects:Q,ZodTransformer:Q,ZodOptional:ie,ZodNullable:Ce,ZodDefault:ht,ZodCatch:mt,ZodNaN:Ot,BRAND:fs,ZodBranded:nr,ZodPipeline:yt,ZodReadonly:_t,custom:Nr,Schema:x,ZodSchema:x,late:ps,get ZodFirstPartyTypeKind(){return k},coerce:{string:r=>K.create({...r,coerce:!0}),number:r=>ke.create({...r,coerce:!0}),boolean:r=>ot.create({...r,coerce:!0}),bigint:r=>Ee.create({...r,coerce:!0}),date:r=>Re.create({...r,coerce:!0})},any:bs,array:Cs,bigint:ys,boolean:Dr,date:_s,discriminatedUnion:Ts,effect:Lr,enum:Fs,function:js,instanceof:hs,intersection:Is,lazy:Ds,literal:Ls,map:Ns,nan:ms,nativeEnum:Us,never:Es,null:ws,nullable:Vs,number:jr,object:xs,oboolean:()=>Dr().optional(),onumber:()=>jr().optional(),optional:Zs,ostring:()=>Mr().optional(),pipeline:Bs,preprocess:zs,promise:$s,record:Rs,set:Ms,strictObject:As,string:Mr,symbol:gs,transformer:Lr,tuple:Os,undefined:vs,union:Ps,unknown:ks,void:Ss,NEVER:E,ZodIssueCode:f,quotelessJson:Wn,ZodError:G});const qs=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()}),Gs=i.array(qs),Ys=i.object({code:i.string(),message:i.string(),path:i.array(i.string())}),Ws=i.array(Ys),Hs={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},sr=r=>{const e=r.toLowerCase().trim();return Hs[e]??r},Ks=r=>{try{return typeof JSON.parse(r)=="object"}catch{return!1}},Js=r=>r.length===1?sr(r[0].msg):`Please fix the following errors:
2
- ${r.map(t=>`• ${sr(t.msg)}`).join(`
3
- `)}`,Qs=r=>`Encountered the following errors:
1
+ (function(Oe,Fe){typeof exports=="object"&&typeof module<"u"?Fe(exports):typeof define=="function"&&define.amd?define(["exports"],Fe):(Oe=typeof globalThis<"u"?globalThis:Oe||self,Fe(Oe.OpenPay={}))})(this,function(Oe){"use strict";const Fe="https://cde.getopenpay.com";var P;(function(r){r.assertEqual=s=>s;function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},r.getValidEnumValues=s=>{const o=r.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(const c of o)a[c]=s[c];return r.objectValues(a)},r.objectValues=s=>r.objectKeys(s).map(function(o){return s[o]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},r.find=(s,o)=>{for(const a of s)if(o(a))return a},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}r.joinValues=n,r.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(P||(P={}));var Jt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Jt||(Jt={}));const _=P.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ke=r=>{switch(typeof r){case"undefined":return _.undefined;case"string":return _.string;case"number":return isNaN(r)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":return Array.isArray(r)?_.array:r===null?_.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?_.promise:typeof Map<"u"&&r instanceof Map?_.map:typeof Set<"u"&&r instanceof Set?_.set:typeof Date<"u"&&r instanceof Date?_.date:_.object;default:return _.unknown}},f=P.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"]),Hn=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class Y 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(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let c=n,u=0;for(;u<a.path.length;){const l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(t(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}};return s(this),n}static assert(e){if(!(e instanceof Y))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,P.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Y.create=r=>new Y(r);const Ue=(r,e)=>{let t;switch(r.code){case f.invalid_type:r.received===_.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case f.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,P.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:t=`Unrecognized key(s) in object: ${P.joinValues(r.keys,", ")}`;break;case f.invalid_union:t="Invalid input";break;case f.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${P.joinValues(r.options)}`;break;case f.invalid_enum_value:t=`Invalid enum value. Expected ${P.joinValues(r.options)}, received '${r.received}'`;break;case f.invalid_arguments:t="Invalid function arguments";break;case f.invalid_return_type:t="Invalid function return type";break;case f.invalid_date:t="Invalid date";break;case f.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}"`:P.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case f.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 f.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 f.custom:t="Invalid input";break;case f.invalid_intersection_types:t="Intersection results could not be merged";break;case f.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case f.not_finite:t="Number must be finite";break;default:t=e.defaultError,P.assertNever(r)}return{message:t}};let xr=Ue;function Kn(r){xr=r}function St(){return xr}const Ct=r=>{const{data:e,path:t,errorMaps:n,issueData:s}=r,o=[...t,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let c="";const u=n.filter(l=>!!l).slice().reverse();for(const l of u)c=l(a,{data:e,defaultError:c}).message;return{...s,path:o,message:c}},Jn=[];function y(r,e){const t=St(),n=Ct({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Ue?void 0:Ue].filter(s=>!!s)});r.common.issues.push(n)}class V{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 s of t){if(s.status==="aborted")return E;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const s of t){const o=await s.key,a=await s.value;n.push({key:o,value:a})}return V.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return E;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[o.value]=a.value)}return{status:e.value,value:n}}}const E=Object.freeze({status:"aborted"}),$e=r=>({status:"dirty",value:r}),B=r=>({status:"valid",value:r}),Qt=r=>r.status==="aborted",Xt=r=>r.status==="dirty",tt=r=>r.status==="valid",rt=r=>typeof Promise<"u"&&r instanceof Promise;function xt(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 Ar(r,e,t,n,s){if(typeof e=="function"?r!==e||!s:!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 v;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(v||(v={}));var nt,st;class ie{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}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 Pr=(r,e)=>{if(tt(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 Y(r.common.issues);return this._error=t,this._error}}};function S(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:s}=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:s}:{errorMap:(a,c)=>{var u,l;const{message:d}=r;return a.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(u=d??n)!==null&&u!==void 0?u:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(l=d??t)!==null&&l!==void 0?l:c.defaultError}},description:s}}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 ke(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new V,ctx:{common:e.parent.common,data:e.data,parsedType:ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(rt(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 s={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:ke(e)},o=this._parseSync({data:e,path:s.path,parent:s});return Pr(s,o)}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:ke(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(rt(s)?s:Promise.resolve(s));return Pr(n,o)}refine(e,t){const n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,o)=>{const a=e(s),c=()=>o.addIssue({code:f.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new X({schema:this,typeName:b.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return ce.create(this,this._def)}nullable(){return xe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Q.create(this,this._def)}promise(){return Be.create(this,this._def)}or(e){return ct.create([this,e],this._def)}and(e){return lt.create(this,e,this._def)}transform(e){return new X({...S(this._def),schema:this,typeName:b.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ht({...S(this._def),innerType:this,defaultValue:t,typeName:b.ZodDefault})}brand(){return new rr({typeName:b.ZodBranded,type:this,...S(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new mt({...S(this._def),innerType:this,catchValue:t,typeName:b.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return yt.create(this,e)}readonly(){return _t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Qn=/^c[^\s-]{8,}$/i,Xn=/^[0-9a-z]+$/,es=/^[0-9A-HJKMNP-TV-Z]{26}$/,ts=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,rs=/^[a-z0-9_-]{21}$/i,ns=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ss=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,os="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let er;const is=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,as=/^(([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})))$/,cs=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Tr="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ls=new RegExp(`^${Tr}$`);function Ir(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 us(r){return new RegExp(`^${Ir(r)}$`)}function Or(r){let e=`${Tr}T${Ir(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 ds(r,e){return!!((e==="v4"||!e)&&is.test(r)||(e==="v6"||!e)&&as.test(r))}class J extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==_.string){const o=this._getOrReturnCtx(e);return y(o,{code:f.invalid_type,expected:_.string,received:o.parsedType}),E}const n=new V;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:f.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const a=e.data.length>o.value,c=e.data.length<o.value;(a||c)&&(s=this._getOrReturnCtx(e,s),a?y(s,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&y(s,{code:f.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")ss.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"email",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")er||(er=new RegExp(os,"u")),er.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"emoji",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")ts.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"uuid",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")rs.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"nanoid",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")Qn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"cuid",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Xn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"cuid2",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")es.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"ulid",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),y(s,{validation:"url",code:f.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"regex",code:f.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),y(s,{code:f.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),y(s,{code:f.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),y(s,{code:f.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Or(o).test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{code:f.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?ls.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{code:f.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?us(o).test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{code:f.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?ns.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"duration",code:f.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?ds(e.data,o.version)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"ip",code:f.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?cs.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"base64",code:f.invalid_string,message:o.message}),n.dirty()):P.assertNever(o);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:f.invalid_string,...v.errToObj(n)})}_addCheck(e){return new J({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...v.errToObj(e)})}url(e){return this._addCheck({kind:"url",...v.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...v.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...v.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...v.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...v.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...v.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...v.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...v.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...v.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,...v.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,...v.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...v.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...v.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...v.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...v.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...v.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...v.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...v.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...v.errToObj(t)})}nonempty(e){return this.min(1,v.errToObj(e))}trim(){return new J({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new J({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new J({...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}}J.create=r=>{var e;return new J({checks:[],typeName:b.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...S(r)})};function fs(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,o=parseInt(r.toFixed(s).replace(".","")),a=parseInt(e.toFixed(s).replace(".",""));return o%a/Math.pow(10,s)}class Ee 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)!==_.number){const o=this._getOrReturnCtx(e);return y(o,{code:f.invalid_type,expected:_.number,received:o.parsedType}),E}let n;const s=new V;for(const o of this._def.checks)o.kind==="int"?P.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:f.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:f.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:f.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?fs(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),y(n,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:f.not_finite,message:o.message}),s.dirty()):P.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,s){return new Ee({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(s)}]})}_addCheck(e){return new Ee({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:v.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:v.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.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"&&P.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)}}Ee.create=r=>new Ee({checks:[],typeName:b.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...S(r)});class Se 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)!==_.bigint){const o=this._getOrReturnCtx(e);return y(o,{code:f.invalid_type,expected:_.bigint,received:o.parsedType}),E}let n;const s=new V;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:f.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:f.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),y(n,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):P.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,s){return new Se({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(s)}]})}_addCheck(e){return new Se({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.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}}Se.create=r=>{var e;return new Se({checks:[],typeName:b.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...S(r)})};class ot extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==_.boolean){const n=this._getOrReturnCtx(e);return y(n,{code:f.invalid_type,expected:_.boolean,received:n.parsedType}),E}return B(e.data)}}ot.create=r=>new ot({typeName:b.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...S(r)});class Re extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==_.date){const o=this._getOrReturnCtx(e);return y(o,{code:f.invalid_type,expected:_.date,received:o.parsedType}),E}if(isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return y(o,{code:f.invalid_date}),E}const n=new V;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:f.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:f.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):P.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Re({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:v.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:v.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}}Re.create=r=>new Re({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:b.ZodDate,...S(r)});class At extends x{_parse(e){if(this._getType(e)!==_.symbol){const n=this._getOrReturnCtx(e);return y(n,{code:f.invalid_type,expected:_.symbol,received:n.parsedType}),E}return B(e.data)}}At.create=r=>new At({typeName:b.ZodSymbol,...S(r)});class it extends x{_parse(e){if(this._getType(e)!==_.undefined){const n=this._getOrReturnCtx(e);return y(n,{code:f.invalid_type,expected:_.undefined,received:n.parsedType}),E}return B(e.data)}}it.create=r=>new it({typeName:b.ZodUndefined,...S(r)});class at extends x{_parse(e){if(this._getType(e)!==_.null){const n=this._getOrReturnCtx(e);return y(n,{code:f.invalid_type,expected:_.null,received:n.parsedType}),E}return B(e.data)}}at.create=r=>new at({typeName:b.ZodNull,...S(r)});class Ze extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return B(e.data)}}Ze.create=r=>new Ze({typeName:b.ZodAny,...S(r)});class Ne extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return B(e.data)}}Ne.create=r=>new Ne({typeName:b.ZodUnknown,...S(r)});class he extends x{_parse(e){const t=this._getOrReturnCtx(e);return y(t,{code:f.invalid_type,expected:_.never,received:t.parsedType}),E}}he.create=r=>new he({typeName:b.ZodNever,...S(r)});class Pt extends x{_parse(e){if(this._getType(e)!==_.undefined){const n=this._getOrReturnCtx(e);return y(n,{code:f.invalid_type,expected:_.void,received:n.parsedType}),E}return B(e.data)}}Pt.create=r=>new Pt({typeName:b.ZodVoid,...S(r)});class Q extends x{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==_.array)return y(t,{code:f.invalid_type,expected:_.array,received:t.parsedType}),E;if(s.exactLength!==null){const a=t.data.length>s.exactLength.value,c=t.data.length<s.exactLength.value;(a||c)&&(y(t,{code:a?f.too_big:f.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(y(t,{code:f.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(y(t,{code:f.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,c)=>s.type._parseAsync(new ie(t,a,t.path,c)))).then(a=>V.mergeArray(n,a));const o=[...t.data].map((a,c)=>s.type._parseSync(new ie(t,a,t.path,c)));return V.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new Q({...this._def,minLength:{value:e,message:v.toString(t)}})}max(e,t){return new Q({...this._def,maxLength:{value:e,message:v.toString(t)}})}length(e,t){return new Q({...this._def,exactLength:{value:e,message:v.toString(t)}})}nonempty(e){return this.min(1,e)}}Q.create=(r,e)=>new Q({type:r,minLength:null,maxLength:null,exactLength:null,typeName:b.ZodArray,...S(e)});function Ve(r){if(r instanceof M){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=ce.create(Ve(n))}return new M({...r._def,shape:()=>e})}else return r instanceof Q?new Q({...r._def,type:Ve(r.element)}):r instanceof ce?ce.create(Ve(r.unwrap())):r instanceof xe?xe.create(Ve(r.unwrap())):r instanceof ae?ae.create(r.items.map(e=>Ve(e))):r}class M 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=P.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==_.object){const l=this._getOrReturnCtx(e);return y(l,{code:f.invalid_type,expected:_.object,received:l.parsedType}),E}const{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof he&&this._def.unknownKeys==="strip"))for(const l in s.data)a.includes(l)||c.push(l);const u=[];for(const l of a){const d=o[l],h=s.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new ie(s,h,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof he){const l=this._def.unknownKeys;if(l==="passthrough")for(const d of c)u.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")c.length>0&&(y(s,{code:f.unrecognized_keys,keys:c}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const d of c){const h=s.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new ie(s,h,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const d of u){const h=await d.key,w=await d.value;l.push({key:h,value:w,alwaysSet:d.alwaysSet})}return l}).then(l=>V.mergeObjectSync(n,l)):V.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new M({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var s,o,a,c;const u=(a=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,t,n).message)!==null&&a!==void 0?a:n.defaultError;return t.code==="unrecognized_keys"?{message:(c=v.errToObj(e).message)!==null&&c!==void 0?c:u}:{message:u}}}:{}})}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:b.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new M({...this._def,catchall:e})}pick(e){const t={};return P.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 P.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new M({...this._def,shape:()=>t})}deepPartial(){return Ve(this)}partial(e){const t={};return P.objectKeys(this.shape).forEach(n=>{const s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}),new M({...this._def,shape:()=>t})}required(e){const t={};return P.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ce;)o=o._def.innerType;t[n]=o}}),new M({...this._def,shape:()=>t})}keyof(){return Rr(P.objectKeys(this.shape))}}M.create=(r,e)=>new M({shape:()=>r,unknownKeys:"strip",catchall:he.create(),typeName:b.ZodObject,...S(e)}),M.strictCreate=(r,e)=>new M({shape:()=>r,unknownKeys:"strict",catchall:he.create(),typeName:b.ZodObject,...S(e)}),M.lazycreate=(r,e)=>new M({shape:r,unknownKeys:"strip",catchall:he.create(),typeName:b.ZodObject,...S(e)});class ct extends x{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function s(o){for(const c of o)if(c.result.status==="valid")return c.result;for(const c of o)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;const a=o.map(c=>new Y(c.ctx.common.issues));return y(t,{code:f.invalid_union,unionErrors:a}),E}if(t.common.async)return Promise.all(n.map(async o=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const u of n){const l={...t,common:{...t.common,issues:[]},parent:null},d=u._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;const c=a.map(u=>new Y(u));return y(t,{code:f.invalid_union,unionErrors:c}),E}}get options(){return this._def.options}}ct.create=(r,e)=>new ct({options:r,typeName:b.ZodUnion,...S(e)});const me=r=>r instanceof dt?me(r.schema):r instanceof X?me(r.innerType()):r instanceof ft?[r.value]:r instanceof Ce?r.options:r instanceof pt?P.objectValues(r.enum):r instanceof ht?me(r._def.innerType):r instanceof it?[void 0]:r instanceof at?[null]:r instanceof ce?[void 0,...me(r.unwrap())]:r instanceof xe?[null,...me(r.unwrap())]:r instanceof rr||r instanceof _t?me(r.unwrap()):r instanceof mt?me(r._def.innerType):[];class Tt extends x{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.object)return y(t,{code:f.invalid_type,expected:_.object,received:t.parsedType}),E;const n=this.discriminator,s=t.data[n],o=this.optionsMap.get(s);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(y(t,{code:f.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 s=new Map;for(const o of t){const a=me(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const c of a){if(s.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);s.set(c,o)}}return new Tt({typeName:b.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...S(n)})}}function tr(r,e){const t=ke(r),n=ke(e);if(r===e)return{valid:!0,data:r};if(t===_.object&&n===_.object){const s=P.objectKeys(e),o=P.objectKeys(r).filter(c=>s.indexOf(c)!==-1),a={...r,...e};for(const c of o){const u=tr(r[c],e[c]);if(!u.valid)return{valid:!1};a[c]=u.data}return{valid:!0,data:a}}else if(t===_.array&&n===_.array){if(r.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<r.length;o++){const a=r[o],c=e[o],u=tr(a,c);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===_.date&&n===_.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class lt extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(o,a)=>{if(Qt(o)||Qt(a))return E;const c=tr(o.value,a.value);return c.valid?((Xt(o)||Xt(a))&&t.dirty(),{status:t.value,value:c.data}):(y(n,{code:f.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(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}lt.create=(r,e,t)=>new lt({left:r,right:e,typeName:b.ZodIntersection,...S(t)});class ae extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.array)return y(n,{code:f.invalid_type,expected:_.array,received:n.parsedType}),E;if(n.data.length<this._def.items.length)return y(n,{code:f.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),E;!this._def.rest&&n.data.length>this._def.items.length&&(y(n,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const o=[...n.data].map((a,c)=>{const u=this._def.items[c]||this._def.rest;return u?u._parse(new ie(n,a,n.path,c)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>V.mergeArray(t,a)):V.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new ae({...this._def,rest:e})}}ae.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ae({items:r,typeName:b.ZodTuple,rest:null,...S(e)})};class ut 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!==_.object)return y(n,{code:f.invalid_type,expected:_.object,received:n.parsedType}),E;const s=[],o=this._def.keyType,a=this._def.valueType;for(const c in n.data)s.push({key:o._parse(new ie(n,c,n.path,c)),value:a._parse(new ie(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?V.mergeObjectAsync(t,s):V.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof x?new ut({keyType:e,valueType:t,typeName:b.ZodRecord,...S(n)}):new ut({keyType:J.create(),valueType:e,typeName:b.ZodRecord,...S(t)})}}class It 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!==_.map)return y(n,{code:f.invalid_type,expected:_.map,received:n.parsedType}),E;const s=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([c,u],l)=>({key:s._parse(new ie(n,c,n.path,[l,"key"])),value:o._parse(new ie(n,u,n.path,[l,"value"]))}));if(n.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const u of a){const l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return E;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}})}else{const c=new Map;for(const u of a){const l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return E;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}}}}It.create=(r,e,t)=>new It({valueType:e,keyType:r,typeName:b.ZodMap,...S(t)});class Me extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.set)return y(n,{code:f.invalid_type,expected:_.set,received:n.parsedType}),E;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(y(n,{code:f.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(y(n,{code:f.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const o=this._def.valueType;function a(u){const l=new Set;for(const d of u){if(d.status==="aborted")return E;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}const c=[...n.data.values()].map((u,l)=>o._parse(new ie(n,u,n.path,l)));return n.common.async?Promise.all(c).then(u=>a(u)):a(c)}min(e,t){return new Me({...this._def,minSize:{value:e,message:v.toString(t)}})}max(e,t){return new Me({...this._def,maxSize:{value:e,message:v.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Me.create=(r,e)=>new Me({valueType:r,minSize:null,maxSize:null,typeName:b.ZodSet,...S(e)});class ze extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.function)return y(t,{code:f.invalid_type,expected:_.function,received:t.parsedType}),E;function n(c,u){return Ct({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,St(),Ue].filter(l=>!!l),issueData:{code:f.invalid_arguments,argumentsError:u}})}function s(c,u){return Ct({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,St(),Ue].filter(l=>!!l),issueData:{code:f.invalid_return_type,returnTypeError:u}})}const o={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Be){const c=this;return B(async function(...u){const l=new Y([]),d=await c._def.args.parseAsync(u,o).catch(m=>{throw l.addIssue(n(u,m)),l}),h=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(h,o).catch(m=>{throw l.addIssue(s(h,m)),l})})}else{const c=this;return B(function(...u){const l=c._def.args.safeParse(u,o);if(!l.success)throw new Y([n(u,l.error)]);const d=Reflect.apply(a,this,l.data),h=c._def.returns.safeParse(d,o);if(!h.success)throw new Y([s(d,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ze({...this._def,args:ae.create(e).rest(Ne.create())})}returns(e){return new ze({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new ze({args:e||ae.create([]).rest(Ne.create()),returns:t||Ne.create(),typeName:b.ZodFunction,...S(n)})}}class dt 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})}}dt.create=(r,e)=>new dt({getter:r,typeName:b.ZodLazy,...S(e)});class ft extends x{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return y(t,{received:t.data,code:f.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:e.data}}get value(){return this._def.value}}ft.create=(r,e)=>new ft({value:r,typeName:b.ZodLiteral,...S(e)});function Rr(r,e){return new Ce({values:r,typeName:b.ZodEnum,...S(e)})}class Ce extends x{constructor(){super(...arguments),nt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return y(t,{expected:P.joinValues(n),received:t.parsedType,code:f.invalid_type}),E}if(xt(this,nt)||Ar(this,nt,new Set(this._def.values)),!xt(this,nt).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return y(t,{received:t.data,code:f.invalid_enum_value,options:n}),E}return B(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 Ce.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ce.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}nt=new WeakMap,Ce.create=Rr;class pt extends x{constructor(){super(...arguments),st.set(this,void 0)}_parse(e){const t=P.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==_.string&&n.parsedType!==_.number){const s=P.objectValues(t);return y(n,{expected:P.joinValues(s),received:n.parsedType,code:f.invalid_type}),E}if(xt(this,st)||Ar(this,st,new Set(P.getValidEnumValues(this._def.values))),!xt(this,st).has(e.data)){const s=P.objectValues(t);return y(n,{received:n.data,code:f.invalid_enum_value,options:s}),E}return B(e.data)}get enum(){return this._def.values}}st=new WeakMap,pt.create=(r,e)=>new pt({values:r,typeName:b.ZodNativeEnum,...S(e)});class Be extends x{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.promise&&t.common.async===!1)return y(t,{code:f.invalid_type,expected:_.promise,received:t.parsedType}),E;const n=t.parsedType===_.promise?t.data:Promise.resolve(t.data);return B(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Be.create=(r,e)=>new Be({type:r,typeName:b.ZodPromise,...S(e)});class X extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===b.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:a=>{y(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async c=>{if(t.value==="aborted")return E;const u=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return u.status==="aborted"?E:u.status==="dirty"||t.value==="dirty"?$e(u.value):u});{if(t.value==="aborted")return E;const c=this._def.schema._parseSync({data:a,path:n.path,parent:n});return c.status==="aborted"?E:c.status==="dirty"||t.value==="dirty"?$e(c.value):c}}if(s.type==="refinement"){const a=c=>{const u=s.refinement(c,o);if(n.common.async)return Promise.resolve(u);if(u 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(),a(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(),a(c.value).then(()=>({status:t.value,value:c.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!tt(a))return a;const c=s.transform(a.value,o);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(a=>tt(a)?Promise.resolve(s.transform(a.value,o)).then(c=>({status:t.value,value:c})):a);P.assertNever(s)}}X.create=(r,e,t)=>new X({schema:r,typeName:b.ZodEffects,effect:e,...S(t)}),X.createWithPreprocess=(r,e,t)=>new X({schema:e,effect:{type:"preprocess",transform:r},typeName:b.ZodEffects,...S(t)});class ce extends x{_parse(e){return this._getType(e)===_.undefined?B(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ce.create=(r,e)=>new ce({innerType:r,typeName:b.ZodOptional,...S(e)});class xe extends x{_parse(e){return this._getType(e)===_.null?B(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}xe.create=(r,e)=>new xe({innerType:r,typeName:b.ZodNullable,...S(e)});class ht extends x{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===_.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ht.create=(r,e)=>new ht({innerType:r,typeName:b.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...S(e)});class mt extends x{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return rt(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Y(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Y(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}mt.create=(r,e)=>new mt({innerType:r,typeName:b.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...S(e)});class Ot extends x{_parse(e){if(this._getType(e)!==_.nan){const n=this._getOrReturnCtx(e);return y(n,{code:f.invalid_type,expected:_.nan,received:n.parsedType}),E}return{status:"valid",value:e.data}}}Ot.create=r=>new Ot({typeName:b.ZodNaN,...S(r)});const ps=Symbol("zod_brand");class rr 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 yt extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?E:o.status==="dirty"?(t.dirty(),$e(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?E:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new yt({in:e,out:t,typeName:b.ZodPipeline})}}class _t extends x{_parse(e){const t=this._def.innerType._parse(e),n=s=>(tt(s)&&(s.value=Object.freeze(s.value)),s);return rt(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}}_t.create=(r,e)=>new _t({innerType:r,typeName:b.ZodReadonly,...S(e)});function Nr(r,e={},t){return r?Ze.create().superRefine((n,s)=>{var o,a;if(!r(n)){const c=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,u=(a=(o=c.fatal)!==null&&o!==void 0?o:t)!==null&&a!==void 0?a:!0,l=typeof c=="string"?{message:c}:c;s.addIssue({code:"custom",...l,fatal:u})}}):Ze.create()}const hs={object:M.lazycreate};var b;(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"})(b||(b={}));const ms=(r,e={message:`Input not instance of ${r.name}`})=>Nr(t=>t instanceof r,e),Mr=J.create,jr=Ee.create,ys=Ot.create,_s=Se.create,Dr=ot.create,gs=Re.create,vs=At.create,ws=it.create,bs=at.create,ks=Ze.create,Es=Ne.create,Ss=he.create,Cs=Pt.create,xs=Q.create,As=M.create,Ps=M.strictCreate,Ts=ct.create,Is=Tt.create,Os=lt.create,Rs=ae.create,Ns=ut.create,Ms=It.create,js=Me.create,Ds=ze.create,Ls=dt.create,Fs=ft.create,Us=Ce.create,$s=pt.create,Zs=Be.create,Lr=X.create,Vs=ce.create,zs=xe.create,Bs=X.createWithPreprocess,qs=yt.create;var i=Object.freeze({__proto__:null,defaultErrorMap:Ue,setErrorMap:Kn,getErrorMap:St,makeIssue:Ct,EMPTY_PATH:Jn,addIssueToContext:y,ParseStatus:V,INVALID:E,DIRTY:$e,OK:B,isAborted:Qt,isDirty:Xt,isValid:tt,isAsync:rt,get util(){return P},get objectUtil(){return Jt},ZodParsedType:_,getParsedType:ke,ZodType:x,datetimeRegex:Or,ZodString:J,ZodNumber:Ee,ZodBigInt:Se,ZodBoolean:ot,ZodDate:Re,ZodSymbol:At,ZodUndefined:it,ZodNull:at,ZodAny:Ze,ZodUnknown:Ne,ZodNever:he,ZodVoid:Pt,ZodArray:Q,ZodObject:M,ZodUnion:ct,ZodDiscriminatedUnion:Tt,ZodIntersection:lt,ZodTuple:ae,ZodRecord:ut,ZodMap:It,ZodSet:Me,ZodFunction:ze,ZodLazy:dt,ZodLiteral:ft,ZodEnum:Ce,ZodNativeEnum:pt,ZodPromise:Be,ZodEffects:X,ZodTransformer:X,ZodOptional:ce,ZodNullable:xe,ZodDefault:ht,ZodCatch:mt,ZodNaN:Ot,BRAND:ps,ZodBranded:rr,ZodPipeline:yt,ZodReadonly:_t,custom:Nr,Schema:x,ZodSchema:x,late:hs,get ZodFirstPartyTypeKind(){return b},coerce:{string:r=>J.create({...r,coerce:!0}),number:r=>Ee.create({...r,coerce:!0}),boolean:r=>ot.create({...r,coerce:!0}),bigint:r=>Se.create({...r,coerce:!0}),date:r=>Re.create({...r,coerce:!0})},any:ks,array:xs,bigint:_s,boolean:Dr,date:gs,discriminatedUnion:Is,effect:Lr,enum:Us,function:Ds,instanceof:ms,intersection:Os,lazy:Ls,literal:Fs,map:Ms,nan:ys,nativeEnum:$s,never:Ss,null:bs,nullable:zs,number:jr,object:As,oboolean:()=>Dr().optional(),onumber:()=>jr().optional(),optional:Vs,ostring:()=>Mr().optional(),pipeline:qs,preprocess:Bs,promise:Zs,record:Ns,set:js,strictObject:Ps,string:Mr,symbol:vs,transformer:Lr,tuple:Rs,undefined:ws,union:Ts,unknown:Es,void:Cs,NEVER:E,ZodIssueCode:f,quotelessJson:Hn,ZodError:Y});const Gs=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()}),Ys=i.array(Gs),Ws=i.object({code:i.string(),message:i.string(),path:i.array(i.string())}),Hs=i.array(Ws),Ks={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},nr=r=>{const e=r.toLowerCase().trim();return Ks[e]??r},Js=r=>{try{return typeof JSON.parse(r)=="object"}catch{return!1}},Qs=r=>r.length===1?nr(r[0].msg):`Please fix the following errors:
2
+ ${r.map(t=>`• ${nr(t.msg)}`).join(`
3
+ `)}`,Xs=r=>`Encountered the following errors:
4
4
  ${r.map(t=>`- ${t.path.join("/")}: ${t.message}`).join(`
5
- `)}`,he=r=>{if(r instanceof Error)if(Ks(r.message)){const e=JSON.parse(r.message);return Gs.safeParse(e).success?Js(e):Ws.safeParse(e).success?Qs(e):(console.warn(`Encountered unknown stringified JSON object:
6
- ${r.message}`),r.message)}else return sr(r.message);if(typeof r=="object")try{return JSON.stringify(r)}catch(e){return e+""}else return r+""},Xs=(r,e,t)=>(...n)=>{try{return e(...n)}catch(s){t(`[form] Error running callback (${r}):`,s);return}},V=i.string().trim().min(1,{message:"Cannot be blank"}),D=i.string().trim().optional(),q=r=>i.nullable(r.optional());var p=(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))(p||{});const Fr=i.nativeEnum(p);var Ur=(r=>(r.CARD_NUMBER="cardNumber",r.CARD_EXPIRY="cardExpiry",r.CARD_CVC="cardCvc",r))(Ur||{});const $r=i.nativeEnum(Ur),Zr=i.union([Fr,$r]);var qe=(r=>(r.CARD="card",r.CARD_NUMBER="card-number",r.CARD_EXPIRY="card-expiry",r.CARD_CVC="card-cvc",r))(qe||{});const eo=i.nativeEnum(qe),Rt=i.object({provider:i.string(),processor_name:q(i.string()),metadata:q(i.record(i.string(),i.any()))}),to=i.object({id:i.string()});i.object({cardNumber:D,expiry:D,cvc:D}),i.object({backgroundColor:D,color:D,fontFamily:D,fontSize:D,fontWeight:D,margin:D,padding:D,letterSpacing:D,lineHeight:D,hideIcon:D});const X=i.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"]),ro=X.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),no=i.object({type:ro}),so=X.extract(["BLUR","FOCUS","CHANGE"]),oo=i.object({type:so,elementType:$r,errors:i.array(i.string()).optional()}),io=X.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),ao=i.object({type:io,message:V,headers:i.record(i.string(),i.string()).optional()}),co=X.extract(["VALIDATION_ERROR"]),lo=i.object({type:co,elementType:Zr,errors:i.array(i.string())}),uo=i.object({type:i.literal(X.enum.LAYOUT),height:V}),fo=i.object({type:i.literal(X.enum.LOADED),sessionId:V,totalAmountAtoms:i.number(),currency:D,checkoutPaymentMethods:i.array(Rt)}),po=i.object({type:i.literal(X.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:i.record(i.string(),i.any()),paymentFlowMetadata:i.any().optional(),startPFMetadata:i.optional(i.record(i.string(),i.any()))}),ho=i.object({type:i.literal(X.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:i.string()}),gt=i.object({firstName:V,lastName:V,email:V,zipCode:V,country:V,promotionCode:D}),mo=i.object({firstName:D,lastName:D,email:V,zipCode:V,country:V,promotionCode:D,address:D,city:D,state:D}),yo=X.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),_o=i.object({type:yo,sessionId:V,checkoutPaymentMethod:Rt,paymentFlowMetadata:i.any().optional(),doNotUseLegacyCCFlow:i.boolean().optional(),existingCCPMId:D}).extend(gt.shape),go=i.object({type:i.literal(X.enum.TOKENIZE_SUCCESS),isReadyForCheckout:i.boolean()}),vo=i.object({type:i.literal(X.enum.CHECKOUT_SUCCESS),invoiceUrls:i.array(i.string()),subscriptionIds:i.array(i.string()),customerId:i.string()}),wo=i.discriminatedUnion("type",[no,oo,ao,lo,uo,fo,_o,go,vo,po,ho]),bo=i.object({payload:wo,nonce:V,formId:V,elementId:V});i.object({amountAtom:i.number(),currency:V}),i.enum(["apple_pay","google_pay"]),i.object({secure_token:i.string(),promotion_code:i.string().optional()}),i.object({secure_token:i.string(),existing_cc_pm_id:q(i.string()),their_pm_id:q(i.string()),checkout_attempt_id:q(i.string()),processor_specific_metadata:q(i.record(i.string(),i.any()))});const or=i.object({invoice_urls:i.array(i.string()),subscription_ids:i.array(i.string()),customer_id:i.string()}),ko=i.object({elementType:i.string(),errors:i.array(i.string())});i.object({session_id:i.string()});const Eo=i.object({success:i.literal(!1),error_type:i.literal("validation_error"),errors:i.array(ko)}),So=i.discriminatedUnion("success",[i.object({success:i.literal(!0)}),Eo]);i.object({session_id:i.string(),checkout_payment_method:Rt,non_cde_form_fields:gt,do_not_use_legacy_cc_flow:i.boolean().optional(),existing_cc_pm_id:q(i.string())}),i.object({session_id:i.string(),checkout_payment_method:Rt,non_cde_form_fields:gt,extra_metadata:i.record(i.string(),i.any()).optional()});var ee=(r=>(r.SUCCESS="success",r.FAILURE="failure",r.CANCELLED="cancelled",r))(ee||{});const Co=i.object({status:i.enum(["success","failure","cancelled"]),href:i.string().optional().nullable()});i.object({href:i.string().optional().nullable()});const xo=i.object({type:i.string(),redirect_url:i.string(),initial_intent_id:i.string(),consent_id:i.string(),their_pm_id:i.string().optional()}),Vr=i.object({type:i.string(),redirect_url:q(i.string()),initial_intent_id:q(i.string()),consent_id:q(i.string()),their_pm_id:q(i.string()),payment_session:q(i.record(i.string(),i.any()))}),Ao=i.discriminatedUnion("present",[i.object({present:i.literal(!0),href:i.string()}),i.object({present:i.literal(!1)})]),Po=i.object({payment_methods:i.array(to),pay_first_success_response:q(or),required_user_actions:q(i.array(Vr))}),To=r=>{const e={};return Object.entries(r).forEach(([t,n])=>{try{const s=Fr.parse(t);Array.isArray(n)?e[s]=n:Array.isArray(n._errors)&&(e[s]=n._errors)}catch{return}}),e},Io=i.object({stripe_pk:i.string(),client_secret:i.string(),stripe_pm_id:i.string()}),Oo=i.object({type:i.string(),client_secret:i.string(),stripe_pk:i.string()}),Ro={usd:"usd",brl:"brl"},Nt=async r=>{for(let t=0;t<10;t++)Br()||await zr(500);if(!Br())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(r)},No=async(r,e)=>{const t=await Nt(r);return{elements:t.elements(e),stripe:t}},Mo=async(r,e,t,n,s)=>{const o=await Nt(r),a=Ro[t.toLowerCase().trim()];return o.paymentRequest({country:"US",currency:a,total:{label:"Total",amount:e,pending:n},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},zr=r=>new Promise(e=>{setTimeout(e,r)}),Br=()=>"Stripe"in window,jo=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)}}),Do=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 Nt(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},Lo=async r=>{var s,o,a,c;const t=await(await Nt(r.stripe_pk)).confirmCardSetup(r.client_secret,{payment_method:r.stripe_pm_id}),n=(s=t.setupIntent)==null?void 0:s.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(`${((o=t.error)==null?void 0:o.message)??((c=(a=t.setupIntent)==null?void 0:a.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},Fo=r=>JSON.stringify(r);for(var L=[],ir=0;ir<256;++ir)L.push((ir+256).toString(16).slice(1));function Uo(r,e=0){return(L[r[e+0]]+L[r[e+1]]+L[r[e+2]]+L[r[e+3]]+"-"+L[r[e+4]]+L[r[e+5]]+"-"+L[r[e+6]]+L[r[e+7]]+"-"+L[r[e+8]]+L[r[e+9]]+"-"+L[r[e+10]]+L[r[e+11]]+L[r[e+12]]+L[r[e+13]]+L[r[e+14]]+L[r[e+15]]).toLowerCase()}var Mt,$o=new Uint8Array(16);function Zo(){if(!Mt&&(Mt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Mt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Mt($o)}var Vo=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const qr={randomUUID:Vo};function zo(r,e,t){if(qr.randomUUID&&!e&&!r)return qr.randomUUID();r=r||{};var n=r.random||(r.rng||Zo)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Uo(n)}const Ge=(r,e)=>Array.from(r.querySelectorAll("[data-opid]")??[]).reduce((s,o)=>{const a=o.getAttribute("data-opid");return a?{...s,[a]:o.value}:s},{}),Bo=r=>{try{return bo.parse(r)}catch(e){throw console.error("Error parsing event payload:",r,e),e}};var ae;(function(r){r.Call="call",r.Reply="reply",r.Syn="syn",r.SynAck="synAck",r.Ack="ack"})(ae||(ae={}));var je;(function(r){r.Fulfilled="fulfilled",r.Rejected="rejected"})(je||(je={}));var vt;(function(r){r.ConnectionDestroyed="ConnectionDestroyed",r.ConnectionTimeout="ConnectionTimeout",r.NoIframeSrc="NoIframeSrc"})(vt||(vt={}));var ar;(function(r){r.DataCloneError="DataCloneError"})(ar||(ar={}));var xe;(function(r){r.Message="message"})(xe||(xe={}));const qo=(r,e)=>{const t=[];let n=!1;return{destroy(s){n||(n=!0,e(`${r}: Destroying connection`),t.forEach(o=>{o(s)}))},onDestroy(s){n?s():t.push(s)}}},Go=r=>(...e)=>{r&&console.log("[Penpal]",...e)},Yo={"http:":"80","https:":"443"},Wo=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Ho=["file:","data:"],Ko=r=>{if(r&&Ho.find(c=>r.startsWith(c)))return"null";const e=document.location,t=Wo.exec(r);let n,s,o;t?(n=t[1]?t[1]:e.protocol,s=t[2],o=t[4]):(n=e.protocol,s=e.hostname,o=e.port);const a=o&&o!==Yo[n]?`:${o}`:"";return`${n}//${s}${a}`},Gr=({name:r,message:e,stack:t})=>({name:r,message:e,stack:t}),Jo=r=>{const e=new Error;return Object.keys(r).forEach(t=>e[t]=r[t]),e},Qo=(r,e,t)=>{const{localName:n,local:s,remote:o,originForSending:a,originForReceiving:c}=r;let u=!1;const l=d=>{if(d.source!==o||d.data.penpal!==ae.Call)return;if(c!=="*"&&d.origin!==c){t(`${n} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const h=d.data,{methodName:w,args:m,id:g}=h;t(`${n}: Received ${w}() call`);const b=A=>O=>{if(t(`${n}: Sending ${w}() reply`),u){t(`${n}: Unable to send ${w}() reply due to destroyed connection`);return}const T={penpal:ae.Reply,id:g,resolution:A,returnValue:O};A===je.Rejected&&O instanceof Error&&(T.returnValue=Gr(O),T.returnValueIsError=!0);try{o.postMessage(T,a)}catch(M){if(M.name===ar.DataCloneError){const j={penpal:ae.Reply,id:g,resolution:je.Rejected,returnValue:Gr(M),returnValueIsError:!0};o.postMessage(j,a)}throw M}};new Promise(A=>A(e[w].apply(e,m))).then(b(je.Fulfilled),b(je.Rejected))};return s.addEventListener(xe.Message,l),()=>{u=!0,s.removeEventListener(xe.Message,l)}};let Xo=0;const ei=()=>++Xo,Yr=".",Wr=r=>r?r.split(Yr):[],ti=r=>r.join(Yr),ri=(r,e)=>{const t=Wr(e||"");return t.push(r),ti(t)},ni=(r,e,t)=>{const n=Wr(e);return n.reduce((s,o,a)=>(typeof s[o]>"u"&&(s[o]={}),a===n.length-1&&(s[o]=t),s[o]),r),r},Hr=(r,e)=>{const t={};return Object.keys(r).forEach(n=>{const s=r[n],o=ri(n,e);typeof s=="object"&&Object.assign(t,Hr(s,o)),typeof s=="function"&&(t[o]=s)}),t},si=r=>{const e={};for(const t in r)ni(e,t,r[t]);return e},oi=(r,e,t,n,s)=>{const{localName:o,local:a,remote:c,originForSending:u,originForReceiving:l}=e;let d=!1;s(`${o}: Connecting call sender`);const h=m=>(...g)=>{s(`${o}: Sending ${m}() call`);let b;try{c.closed&&(b=!0)}catch{b=!0}if(b&&n(),d){const A=new Error(`Unable to send ${m}() call due to destroyed connection`);throw A.code=vt.ConnectionDestroyed,A}return new Promise((A,O)=>{const T=ei(),M=W=>{if(W.source!==c||W.data.penpal!==ae.Reply||W.data.id!==T)return;if(l!=="*"&&W.origin!==l){s(`${o} received message from origin ${W.origin} which did not match expected origin ${l}`);return}const Ie=W.data;s(`${o}: Received ${m}() reply`),a.removeEventListener(xe.Message,M);let ue=Ie.returnValue;Ie.returnValueIsError&&(ue=Jo(ue)),(Ie.resolution===je.Fulfilled?A:O)(ue)};a.addEventListener(xe.Message,M);const j={penpal:ae.Call,id:T,methodName:m,args:g};c.postMessage(j,u)})},w=t.reduce((m,g)=>(m[g]=h(g),m),{});return Object.assign(r,si(w)),()=>{d=!0}},ii=(r,e,t,n,s)=>{const{destroy:o,onDestroy:a}=n;let c,u;const l={};return d=>{if(e!=="*"&&d.origin!==e){s(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}s("Parent: Handshake - Received ACK");const h={localName:"Parent",local:window,remote:d.source,originForSending:t,originForReceiving:e};c&&c(),c=Qo(h,r,s),a(c),u&&u.forEach(m=>{delete l[m]}),u=d.data.methodNames;const w=oi(l,h,u,o,s);return a(w),l}},ai=(r,e,t,n)=>s=>{if(!s.source)return;if(t!=="*"&&s.origin!==t){r(`Parent: Handshake - Received SYN message from origin ${s.origin} which did not match expected origin ${t}`);return}r("Parent: Handshake - Received SYN, responding with SYN-ACK");const o={penpal:ae.SynAck,methodNames:Object.keys(e)};s.source.postMessage(o,n)},ci=6e4,li=(r,e)=>{const{destroy:t,onDestroy:n}=e,s=setInterval(()=>{r.isConnected||(clearInterval(s),t())},ci);n(()=>{clearInterval(s)})},ui=(r,e)=>{let t;return r!==void 0&&(t=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${r}ms`);n.code=vt.ConnectionTimeout,e(n)},r)),()=>{clearTimeout(t)}},di=r=>{if(!r.src&&!r.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=vt.NoIframeSrc,e}},Kr=r=>{let{iframe:e,methods:t={},childOrigin:n,timeout:s,debug:o=!1}=r;const a=Go(o),c=qo("Parent",a),{onDestroy:u,destroy:l}=c;n||(di(e),n=Ko(e.src));const d=n==="null"?"*":n,h=Hr(t),w=ai(a,h,n,d),m=ii(h,n,d,c,a);return{promise:new Promise((b,A)=>{const O=ui(s,l),T=M=>{if(!(M.source!==e.contentWindow||!M.data)){if(M.data.penpal===ae.Syn){w(M);return}if(M.data.penpal===ae.Ack){const j=m(M);j&&(O(),b(j));return}}};window.addEventListener(xe.Message,T),a("Parent: Awaiting handshake"),li(e,c),u(M=>{window.removeEventListener(xe.Message,T),M&&A(M)})}),destroy(){l()}}},fi=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}},pi=(r,e)=>!!r&&e,C=r=>i.nullable(r.optional());i.string().trim().min(1,{message:"Cannot be blank"});const hi=i.object({cde_response_type:i.literal("error"),message:i.string(),headers:i.record(i.string(),i.string()).optional()});i.enum(["usd","brl"]);const Jr=i.object({name:i.string(),amount_atom_off:C(i.number()),percent_off:C(i.number()),currency:C(i.string()),duration:i.string(),duration_in_months:C(i.number())}),Qr=i.object({amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),currency:i.string(),description:C(i.string()),price_id:i.string(),billing_interval:C(i.string()),billing_interval_count:C(i.number().int()),quantity:i.number().int()}),mi=i.record(i.string(),i.any()),yi=i.object({name:i.string(),settings:C(mi)}),wt=i.object({provider:i.string(),processor_name:C(i.string()),metadata:C(i.record(i.string(),i.any()))}),_i=i.object({quantity:i.number()}),gi=i.object({id:C(i.string()),billing_interval:C(i.string()),billing_interval_count:C(i.number().int()),subscription_items:i.array(_i),trial_start:C(i.string()),trial_end:C(i.string())}),Xr=i.object({amount_atom:i.number()}),vi=i.object({amount_atom:i.number(),amount_atom_considering_discount_applied:i.number(),currency:i.string(),discount_amount_atoms:i.array(Xr),subscription_item_id:i.string()}),wi=i.object({coupon:Jr}),bi=i.object({currency:i.string(),discounts:i.array(wi),hosted_invoice_url:C(i.string()),lines:i.array(vi),remaining_amount_atom:i.number(),tax_amount_atom:i.number(),total_amount_atom:i.number(),total_discount_amount_atoms:i.array(Xr)}),en=i.object({created:i.array(gi),invoices:i.array(bi)}),tn=i.object({preview:en,preview_post_trial:C(en),coupons:i.array(Jr)}),rn=i.object({status:i.literal("open"),token:i.string(),email:C(i.string()),line_items:i.array(Qr),amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),brand:yi,subs_preview:C(tn),methods_available:i.array(wt)}),nn=i.discriminatedUnion("mode",[i.object({mode:i.literal("setup"),currency:i.nullable(i.undefined())}).extend(rn.shape),i.object({mode:i.enum(["payment","subscription"]),currency:i.string()}).extend(rn.shape)]),ki=i.object({status:i.literal("complete")}),Ei=i.object({status:i.literal("expired")});i.union([nn,ki,Ei]),i.object({logo:i.string(),icon:i.string(),primary_color:i.string(),secondary_color:i.string()}),i.object({secure_token:i.string(),pm_id:i.string()}),i.object({secure_token:i.string(),payment_input:i.any(),customer_first_name:i.string().optional(),customer_last_name:i.string().optional(),customer_email:i.string(),customer_zip_code:i.string(),customer_country:i.string(),line_items:i.array(Qr),total_amount_atom:i.number().int(),cancel_at_end:i.boolean(),checkout_payment_method:wt,promotion_code:i.string().optional(),do_not_use_legacy_cc_flow:i.boolean().optional(),use_confirmed_pm_id:C(i.string())});const Si=i.object({payment_method_id:i.string()});i.object({id:i.string(),return_url:i.string()});const Ci=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()});i.array(Ci);const xi=i.object({new_customer_email:i.string().optional(),new_customer_address:i.record(i.string(),i.any()).optional(),new_customer_first_name:i.string().optional(),new_customer_last_name:i.string().optional()}),Ai=i.object({price_id:i.string(),quantity:i.number().int()}),Pi=i.object({line_items:i.array(Ai),promotion_code:i.string().optional(),displayed_total_amount_atom:i.number().int()}),Ti=i.object({processor_specific_metadata:C(i.record(i.string(),i.any()))});i.object({payment_provider:i.string(),checkout_payment_method:wt,existing_cc_pm_id:i.string().optional(),their_existing_pm_id:i.string().optional(),use_pay_first_flow:i.boolean().optional(),pay_first_flow_cart_info:Pi.optional()}).extend(xi.shape).extend(Ti.shape);const sn=i.object({required_user_actions:i.array(i.record(i.string(),i.any())),checkout_attempt_id:C(i.string())});i.object({fields:mo,checkoutPaymentMethod:wt}),i.object({session_id:i.string(),non_cde_form_fields:gt,checkout_payment_method:wt,extra_metadata:i.record(i.string(),i.any())});const Ii=i.object({required_user_actions:i.array(i.record(i.string(),i.any())),cc_pm_id:i.string()});i.record(i.any()),i.object({first_name:C(i.string()),last_name:C(i.string()),line1:C(i.string()),line2:C(i.string()),line3:C(i.string()),city:C(i.string()),state:C(i.string()),country:C(i.string()),zip_code:C(i.string()),email:C(i.string()),billing_email:C(i.string()),phone_number:C(i.string()),update_processor_customer:C(i.boolean())});const Oi=i.object({id:i.string(),email:C(i.string()),first_name:C(i.string()),last_name:C(i.string()),phone_number:C(i.string()),billing_email:C(i.string()),address:C(i.record(i.string(),i.any()))}),Ri=r=>r.reduce((e,t)=>e+t,0);function Ni(r,e){var t=Object.setPrototypeOf;t?t(r,e):r.__proto__=e}function Mi(r,e){e===void 0&&(e=r.constructor);var t=Error.captureStackTrace;t&&t(r,e)}var ji=function(){var r=function(t,n){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,o){s.__proto__=o}||function(s,o){for(var a in o)Object.prototype.hasOwnProperty.call(o,a)&&(s[a]=o[a])},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)}}(),Di=function(r){ji(e,r);function e(t,n){var s=this.constructor,o=r.call(this,t,n)||this;return Object.defineProperty(o,"name",{value:s.name,enumerable:!1,configurable:!0}),Ni(o,s.prototype),Mi(o),o}return e}(Error);class on extends Di{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(Fi(n))throw new on(n);if(!Li(n,t)){const s=t.safeParse(n);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",t,"Actual:",n),s.error)}return n},Li=(r,e)=>e.safeParse(r).success,Fi=r=>hi.safeParse(r).success,Ui=async(r,e)=>await Y(r,{type:"get_checkout_preview",payload:e},tn),Ae=async r=>await Y(r,{type:"get_prefill",payload:{}},nn),jt=async(r,e)=>await Y(r,{type:"v2_start_payment_flow",payload:e},sn),$i=async(r,e)=>await Y(r,{type:"start_payment_flow_for_cc",payload:e},Ii),Zi=async(r,e)=>await Y(r,{type:"start_payment_flow_for_pr",payload:e},sn),Pe=async(r,e)=>await Y(r,{type:"confirm_payment_flow",payload:e},Po),Vi=async(r,e)=>await Y(r,{type:"check_if_popup_window_verified",payload:e},Ao),zi=async(r,e,t)=>{const n=await Ui(r,{secure_token:e,promotion_code:t}),s=new Set(n.preview.invoices.map(c=>c.currency));if(s.size!==1)throw new Error(`Expected exactly one currency, got ${s.size}`);const o=s.values().next().value??"usd",a=Ri(n.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:o,amountAtom:a}},Dt=async(r,e,t,n)=>{if(t)return{amountAtom:0,currency:"usd"};{n=n||void 0;const s=await zi(r,e,n);return{amountAtom:s.amountAtom,currency:s.currency}}},Bi=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},So)))},an=async(r,e)=>{try{return await Y(r,{type:"checkout_card_elements",payload:e},or)}catch(t){throw console.error("[cde-client] Error during checkoutCardElements:",t,JSON.stringify(t)),t}},qi=async(r,e)=>await Y(r,{type:"setup_payment_method",payload:e},Si),Lt=async(r,e)=>await Y(r,{type:"checkout",payload:e},or),cn=1e3,Gi=async(r,e)=>{console.log(e);const n=await Kr({iframe:r,debug:!0,timeout:cn,childOrigin:"*"}).promise,s=await Y(n,{type:"ping-3ds-status"},Co);return console.log("🟢 CDE connection successful! Stopping polling... Result:",s),s},Yi=async(r,e)=>await Y(r,{type:"update_checkout_customer",payload:e},Oi);function cr(r){throw new Error(`Unhandled case: ${r}`)}const lr=10,ln=(r=0)=>e=>`\x1B[${e+r}m`,un=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,dn=(r=0)=>(e,t,n)=>`\x1B[${38+r};2;${e};${t};${n}m`,I={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(I.modifier);const Wi=Object.keys(I.color),Hi=Object.keys(I.bgColor);[...Wi,...Hi];function Ki(){const r=new Map;for(const[e,t]of Object.entries(I)){for(const[n,s]of Object.entries(t))I[n]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},t[n]=I[n],r.set(s[0],s[1]);Object.defineProperty(I,e,{value:t,enumerable:!1})}return Object.defineProperty(I,"codes",{value:r,enumerable:!1}),I.color.close="\x1B[39m",I.bgColor.close="\x1B[49m",I.color.ansi=ln(),I.color.ansi256=un(),I.color.ansi16m=dn(),I.bgColor.ansi=ln(lr),I.bgColor.ansi256=un(lr),I.bgColor.ansi16m=dn(lr),Object.defineProperties(I,{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(o=>o+o).join(""));const s=Number.parseInt(n,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:e=>I.rgbToAnsi256(...I.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,s;if(e>=232)t=((e-232)*10+8)/255,n=t,s=t;else{e-=16;const c=e%36;t=Math.floor(e/36)/5,n=Math.floor(c/6)/5,s=c%6/5}const o=Math.max(t,n,s)*2;if(o===0)return 30;let a=30+(Math.round(s)<<2|Math.round(n)<<1|Math.round(t));return o===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>I.ansi256ToAnsi(I.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>I.ansi256ToAnsi(I.hexToAnsi256(e)),enumerable:!1}}),I}const ce=Ki(),Ft=(()=>{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})(),fn=Ft!==0&&{level:Ft,hasBasic:!0,has256:Ft>=2,has16m:Ft>=3},Ji={stdout:fn,stderr:fn};function Qi(r,e,t){let n=r.indexOf(e);if(n===-1)return r;const s=e.length;let o=0,a="";do a+=r.slice(o,n)+e+t,o=n+s,n=r.indexOf(e,o);while(n!==-1);return a+=r.slice(o),a}function Xi(r,e,t,n){let s=0,o="";do{const a=r[n-1]==="\r";o+=r.slice(s,a?n-1:n)+e+(a?`\r
5
+ `)}`,ye=r=>{if(r instanceof Error)if(Js(r.message)){const e=JSON.parse(r.message);return Ys.safeParse(e).success?Qs(e):Hs.safeParse(e).success?Xs(e):(console.warn(`Encountered unknown stringified JSON object:
6
+ ${r.message}`),r.message)}else return nr(r.message);if(typeof r=="object")try{return JSON.stringify(r)}catch(e){return e+""}else return r+""},eo=(r,e,t)=>(...n)=>{try{return e(...n)}catch(s){t(`[form] Error running callback (${r}):`,s);return}},z=i.string().trim().min(1,{message:"Cannot be blank"}),D=i.string().trim().optional(),G=r=>i.nullable(r.optional());var p=(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))(p||{});const Fr=i.nativeEnum(p);var Ur=(r=>(r.CARD_NUMBER="cardNumber",r.CARD_EXPIRY="cardExpiry",r.CARD_CVC="cardCvc",r))(Ur||{});const $r=i.nativeEnum(Ur),Zr=i.union([Fr,$r]);var qe=(r=>(r.CARD="card",r.CARD_NUMBER="card-number",r.CARD_EXPIRY="card-expiry",r.CARD_CVC="card-cvc",r))(qe||{});const to=i.nativeEnum(qe),Rt=i.object({provider:i.string(),processor_name:G(i.string()),metadata:G(i.record(i.string(),i.any()))}),ro=i.object({id:i.string()});i.object({cardNumber:D,expiry:D,cvc:D}),i.object({backgroundColor:D,color:D,fontFamily:D,fontSize:D,fontWeight:D,margin:D,padding:D,letterSpacing:D,lineHeight:D,hideIcon:D});const ee=i.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"]),no=ee.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),so=i.object({type:no}),oo=ee.extract(["BLUR","FOCUS","CHANGE"]),io=i.object({type:oo,elementType:$r,errors:i.array(i.string()).optional()}),ao=ee.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),co=i.object({type:ao,message:z,headers:i.record(i.string(),i.string()).optional()}),lo=ee.extract(["VALIDATION_ERROR"]),uo=i.object({type:lo,elementType:Zr,errors:i.array(i.string())}),fo=i.object({type:i.literal(ee.enum.LAYOUT),height:z}),po=i.object({type:i.literal(ee.enum.LOADED),sessionId:z,totalAmountAtoms:i.number(),currency:D,checkoutPaymentMethods:i.array(Rt)}),ho=i.object({type:i.literal(ee.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:i.record(i.string(),i.any()),paymentFlowMetadata:i.any().optional(),startPFMetadata:i.optional(i.record(i.string(),i.any()))}),mo=i.object({type:i.literal(ee.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:i.string()}),gt=i.object({firstName:z,lastName:z,email:z,zipCode:z,country:z,promotionCode:D}),yo=i.object({firstName:D,lastName:D,email:z,zipCode:z,country:z,promotionCode:D,address:D,city:D,state:D}),_o=ee.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),go=i.object({type:_o,sessionId:z,checkoutPaymentMethod:Rt,paymentFlowMetadata:i.any().optional(),doNotUseLegacyCCFlow:i.boolean().optional(),existingCCPMId:D}).extend(gt.shape),vo=i.object({type:i.literal(ee.enum.TOKENIZE_SUCCESS),isReadyForCheckout:i.boolean()}),wo=i.object({type:i.literal(ee.enum.CHECKOUT_SUCCESS),invoiceUrls:i.array(i.string()),subscriptionIds:i.array(i.string()),customerId:i.string()}),bo=i.discriminatedUnion("type",[so,io,co,uo,fo,po,go,vo,wo,ho,mo]),ko=i.object({payload:bo,nonce:z,formId:z,elementId:z});i.object({amountAtom:i.number(),currency:z}),i.enum(["apple_pay","google_pay"]),i.object({secure_token:i.string(),promotion_code:i.string().optional()}),i.object({secure_token:i.string(),existing_cc_pm_id:G(i.string()),their_pm_id:G(i.string()),checkout_attempt_id:G(i.string()),processor_specific_metadata:G(i.record(i.string(),i.any()))});const sr=i.object({invoice_urls:i.array(i.string()),subscription_ids:i.array(i.string()),customer_id:i.string()}),Eo=i.object({elementType:i.string(),errors:i.array(i.string())});i.object({session_id:i.string()});const So=i.object({success:i.literal(!1),error_type:i.literal("validation_error"),errors:i.array(Eo)}),Co=i.discriminatedUnion("success",[i.object({success:i.literal(!0)}),So]);i.object({session_id:i.string(),checkout_payment_method:Rt,non_cde_form_fields:gt,do_not_use_legacy_cc_flow:i.boolean().optional(),existing_cc_pm_id:G(i.string())}),i.object({session_id:i.string(),checkout_payment_method:Rt,non_cde_form_fields:gt,extra_metadata:i.record(i.string(),i.any()).optional()});var te=(r=>(r.SUCCESS="success",r.FAILURE="failure",r.CANCELLED="cancelled",r))(te||{});const xo=i.object({status:i.enum(["success","failure","cancelled"]),href:i.string().optional().nullable()});i.object({href:i.string().optional().nullable()});const Ao=i.object({type:i.string(),redirect_url:i.string(),initial_intent_id:i.string(),consent_id:i.string(),their_pm_id:i.string().optional()}),Vr=i.object({type:i.string(),redirect_url:G(i.string()),initial_intent_id:G(i.string()),consent_id:G(i.string()),their_pm_id:G(i.string()),payment_session:G(i.record(i.string(),i.any()))}),Po=i.discriminatedUnion("present",[i.object({present:i.literal(!0),href:i.string()}),i.object({present:i.literal(!1)})]),To=i.object({payment_methods:i.array(ro),pay_first_success_response:G(sr),required_user_actions:G(i.array(Vr))}),Io=r=>{const e={};return Object.entries(r).forEach(([t,n])=>{try{const s=Fr.parse(t);Array.isArray(n)?e[s]=n:Array.isArray(n._errors)&&(e[s]=n._errors)}catch{return}}),e},Oo=i.object({stripe_pk:i.string(),client_secret:i.string(),stripe_pm_id:i.string()}),Ro=i.object({type:i.string(),client_secret:i.string(),stripe_pk:i.string()}),No={usd:"usd",brl:"brl"},Nt=async r=>{for(let t=0;t<10;t++)Br()||await zr(500);if(!Br())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(r)},Mo=async(r,e)=>{const t=await Nt(r);return{elements:t.elements(e),stripe:t}},jo=async(r,e,t,n,s)=>{const o=await Nt(r),a=No[t.toLowerCase().trim()];return o.paymentRequest({country:"US",currency:a,total:{label:"Total",amount:e,pending:n},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},zr=r=>new Promise(e=>{setTimeout(e,r)}),Br=()=>"Stripe"in window,Do=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)}}),Lo=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 Nt(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},Fo=async r=>{var s,o,a,c;const t=await(await Nt(r.stripe_pk)).confirmCardSetup(r.client_secret,{payment_method:r.stripe_pm_id}),n=(s=t.setupIntent)==null?void 0:s.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(`${((o=t.error)==null?void 0:o.message)??((c=(a=t.setupIntent)==null?void 0:a.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},Uo=r=>JSON.stringify(r);for(var F=[],or=0;or<256;++or)F.push((or+256).toString(16).slice(1));function $o(r,e=0){return(F[r[e+0]]+F[r[e+1]]+F[r[e+2]]+F[r[e+3]]+"-"+F[r[e+4]]+F[r[e+5]]+"-"+F[r[e+6]]+F[r[e+7]]+"-"+F[r[e+8]]+F[r[e+9]]+"-"+F[r[e+10]]+F[r[e+11]]+F[r[e+12]]+F[r[e+13]]+F[r[e+14]]+F[r[e+15]]).toLowerCase()}var Mt,Zo=new Uint8Array(16);function Vo(){if(!Mt&&(Mt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Mt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Mt(Zo)}var zo=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const qr={randomUUID:zo};function Gr(r,e,t){if(qr.randomUUID&&!e&&!r)return qr.randomUUID();r=r||{};var n=r.random||(r.rng||Vo)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,$o(n)}const Ge=(r,e)=>Array.from(r.querySelectorAll("[data-opid]")??[]).reduce((s,o)=>{const a=o.getAttribute("data-opid");return a?{...s,[a]:o.value}:s},{}),Bo=r=>{try{return ko.parse(r)}catch(e){throw console.error("Error parsing event payload:",r,e),e}};var le;(function(r){r.Call="call",r.Reply="reply",r.Syn="syn",r.SynAck="synAck",r.Ack="ack"})(le||(le={}));var je;(function(r){r.Fulfilled="fulfilled",r.Rejected="rejected"})(je||(je={}));var vt;(function(r){r.ConnectionDestroyed="ConnectionDestroyed",r.ConnectionTimeout="ConnectionTimeout",r.NoIframeSrc="NoIframeSrc"})(vt||(vt={}));var ir;(function(r){r.DataCloneError="DataCloneError"})(ir||(ir={}));var Ae;(function(r){r.Message="message"})(Ae||(Ae={}));const qo=(r,e)=>{const t=[];let n=!1;return{destroy(s){n||(n=!0,e(`${r}: Destroying connection`),t.forEach(o=>{o(s)}))},onDestroy(s){n?s():t.push(s)}}},Go=r=>(...e)=>{r&&console.log("[Penpal]",...e)},Yo={"http:":"80","https:":"443"},Wo=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Ho=["file:","data:"],Ko=r=>{if(r&&Ho.find(c=>r.startsWith(c)))return"null";const e=document.location,t=Wo.exec(r);let n,s,o;t?(n=t[1]?t[1]:e.protocol,s=t[2],o=t[4]):(n=e.protocol,s=e.hostname,o=e.port);const a=o&&o!==Yo[n]?`:${o}`:"";return`${n}//${s}${a}`},Yr=({name:r,message:e,stack:t})=>({name:r,message:e,stack:t}),Jo=r=>{const e=new Error;return Object.keys(r).forEach(t=>e[t]=r[t]),e},Qo=(r,e,t)=>{const{localName:n,local:s,remote:o,originForSending:a,originForReceiving:c}=r;let u=!1;const l=d=>{if(d.source!==o||d.data.penpal!==le.Call)return;if(c!=="*"&&d.origin!==c){t(`${n} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const h=d.data,{methodName:w,args:m,id:g}=h;t(`${n}: Received ${w}() call`);const k=A=>N=>{if(t(`${n}: Sending ${w}() reply`),u){t(`${n}: Unable to send ${w}() reply due to destroyed connection`);return}const T={penpal:le.Reply,id:g,resolution:A,returnValue:N};A===je.Rejected&&N instanceof Error&&(T.returnValue=Yr(N),T.returnValueIsError=!0);try{o.postMessage(T,a)}catch(I){if(I.name===ir.DataCloneError){const O={penpal:le.Reply,id:g,resolution:je.Rejected,returnValue:Yr(I),returnValueIsError:!0};o.postMessage(O,a)}throw I}};new Promise(A=>A(e[w].apply(e,m))).then(k(je.Fulfilled),k(je.Rejected))};return s.addEventListener(Ae.Message,l),()=>{u=!0,s.removeEventListener(Ae.Message,l)}};let Xo=0;const ei=()=>++Xo,Wr=".",Hr=r=>r?r.split(Wr):[],ti=r=>r.join(Wr),ri=(r,e)=>{const t=Hr(e||"");return t.push(r),ti(t)},ni=(r,e,t)=>{const n=Hr(e);return n.reduce((s,o,a)=>(typeof s[o]>"u"&&(s[o]={}),a===n.length-1&&(s[o]=t),s[o]),r),r},Kr=(r,e)=>{const t={};return Object.keys(r).forEach(n=>{const s=r[n],o=ri(n,e);typeof s=="object"&&Object.assign(t,Kr(s,o)),typeof s=="function"&&(t[o]=s)}),t},si=r=>{const e={};for(const t in r)ni(e,t,r[t]);return e},oi=(r,e,t,n,s)=>{const{localName:o,local:a,remote:c,originForSending:u,originForReceiving:l}=e;let d=!1;s(`${o}: Connecting call sender`);const h=m=>(...g)=>{s(`${o}: Sending ${m}() call`);let k;try{c.closed&&(k=!0)}catch{k=!0}if(k&&n(),d){const A=new Error(`Unable to send ${m}() call due to destroyed connection`);throw A.code=vt.ConnectionDestroyed,A}return new Promise((A,N)=>{const T=ei(),I=L=>{if(L.source!==c||L.data.penpal!==le.Reply||L.data.id!==T)return;if(l!=="*"&&L.origin!==l){s(`${o} received message from origin ${L.origin} which did not match expected origin ${l}`);return}const se=L.data;s(`${o}: Received ${m}() reply`),a.removeEventListener(Ae.Message,I);let H=se.returnValue;se.returnValueIsError&&(H=Jo(H)),(se.resolution===je.Fulfilled?A:N)(H)};a.addEventListener(Ae.Message,I);const O={penpal:le.Call,id:T,methodName:m,args:g};c.postMessage(O,u)})},w=t.reduce((m,g)=>(m[g]=h(g),m),{});return Object.assign(r,si(w)),()=>{d=!0}},ii=(r,e,t,n,s)=>{const{destroy:o,onDestroy:a}=n;let c,u;const l={};return d=>{if(e!=="*"&&d.origin!==e){s(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}s("Parent: Handshake - Received ACK");const h={localName:"Parent",local:window,remote:d.source,originForSending:t,originForReceiving:e};c&&c(),c=Qo(h,r,s),a(c),u&&u.forEach(m=>{delete l[m]}),u=d.data.methodNames;const w=oi(l,h,u,o,s);return a(w),l}},ai=(r,e,t,n)=>s=>{if(!s.source)return;if(t!=="*"&&s.origin!==t){r(`Parent: Handshake - Received SYN message from origin ${s.origin} which did not match expected origin ${t}`);return}r("Parent: Handshake - Received SYN, responding with SYN-ACK");const o={penpal:le.SynAck,methodNames:Object.keys(e)};s.source.postMessage(o,n)},ci=6e4,li=(r,e)=>{const{destroy:t,onDestroy:n}=e,s=setInterval(()=>{r.isConnected||(clearInterval(s),t())},ci);n(()=>{clearInterval(s)})},ui=(r,e)=>{let t;return r!==void 0&&(t=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${r}ms`);n.code=vt.ConnectionTimeout,e(n)},r)),()=>{clearTimeout(t)}},di=r=>{if(!r.src&&!r.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=vt.NoIframeSrc,e}},Jr=r=>{let{iframe:e,methods:t={},childOrigin:n,timeout:s,debug:o=!1}=r;const a=Go(o),c=qo("Parent",a),{onDestroy:u,destroy:l}=c;n||(di(e),n=Ko(e.src));const d=n==="null"?"*":n,h=Kr(t),w=ai(a,h,n,d),m=ii(h,n,d,c,a);return{promise:new Promise((k,A)=>{const N=ui(s,l),T=I=>{if(!(I.source!==e.contentWindow||!I.data)){if(I.data.penpal===le.Syn){w(I);return}if(I.data.penpal===le.Ack){const O=m(I);O&&(N(),k(O));return}}};window.addEventListener(Ae.Message,T),a("Parent: Awaiting handshake"),li(e,c),u(I=>{window.removeEventListener(Ae.Message,T),I&&A(I)})}),destroy(){l()}}},fi=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}},pi=(r,e)=>!!r&&e,C=r=>i.nullable(r.optional());i.string().trim().min(1,{message:"Cannot be blank"});const hi=i.object({cde_response_type:i.literal("error"),message:i.string(),headers:i.record(i.string(),i.string()).optional()});i.enum(["usd","brl"]);const Qr=i.object({name:i.string(),amount_atom_off:C(i.number()),percent_off:C(i.number()),currency:C(i.string()),duration:i.string(),duration_in_months:C(i.number())}),Xr=i.object({amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),currency:i.string(),description:C(i.string()),price_id:i.string(),billing_interval:C(i.string()),billing_interval_count:C(i.number().int()),quantity:i.number().int()}),mi=i.record(i.string(),i.any()),yi=i.object({name:i.string(),settings:C(mi)}),wt=i.object({provider:i.string(),processor_name:C(i.string()),metadata:C(i.record(i.string(),i.any()))}),_i=i.object({quantity:i.number()}),gi=i.object({id:C(i.string()),billing_interval:C(i.string()),billing_interval_count:C(i.number().int()),subscription_items:i.array(_i),trial_start:C(i.string()),trial_end:C(i.string())}),en=i.object({amount_atom:i.number()}),vi=i.object({amount_atom:i.number(),amount_atom_considering_discount_applied:i.number(),currency:i.string(),discount_amount_atoms:i.array(en),subscription_item_id:i.string()}),wi=i.object({coupon:Qr}),bi=i.object({currency:i.string(),discounts:i.array(wi),hosted_invoice_url:C(i.string()),lines:i.array(vi),remaining_amount_atom:i.number(),tax_amount_atom:i.number(),total_amount_atom:i.number(),total_discount_amount_atoms:i.array(en)}),tn=i.object({created:i.array(gi),invoices:i.array(bi)}),rn=i.object({preview:tn,preview_post_trial:C(tn),coupons:i.array(Qr)}),nn=i.object({status:i.literal("open"),token:i.string(),email:C(i.string()),line_items:i.array(Xr),amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),brand:yi,subs_preview:C(rn),methods_available:i.array(wt)}),sn=i.discriminatedUnion("mode",[i.object({mode:i.literal("setup"),currency:i.nullable(i.undefined())}).extend(nn.shape),i.object({mode:i.enum(["payment","subscription"]),currency:i.string()}).extend(nn.shape)]),ki=i.object({status:i.literal("complete")}),Ei=i.object({status:i.literal("expired")});i.union([sn,ki,Ei]),i.object({logo:i.string(),icon:i.string(),primary_color:i.string(),secondary_color:i.string()}),i.object({secure_token:i.string(),pm_id:i.string()}),i.object({secure_token:i.string(),payment_input:i.any(),customer_first_name:i.string().optional(),customer_last_name:i.string().optional(),customer_email:i.string(),customer_zip_code:i.string(),customer_country:i.string(),line_items:i.array(Xr),total_amount_atom:i.number().int(),cancel_at_end:i.boolean(),checkout_payment_method:wt,promotion_code:i.string().optional(),do_not_use_legacy_cc_flow:i.boolean().optional(),use_confirmed_pm_id:C(i.string())});const Si=i.object({payment_method_id:i.string()});i.object({id:i.string(),return_url:i.string()});const Ci=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()});i.array(Ci);const xi=i.object({new_customer_email:i.string().optional(),new_customer_address:i.record(i.string(),i.any()).optional(),new_customer_first_name:i.string().optional(),new_customer_last_name:i.string().optional()}),Ai=i.object({price_id:i.string(),quantity:i.number().int()}),Pi=i.object({line_items:i.array(Ai),promotion_code:i.string().optional(),displayed_total_amount_atom:i.number().int()}),Ti=i.object({processor_specific_metadata:C(i.record(i.string(),i.any()))});i.object({payment_provider:i.string(),checkout_payment_method:wt,existing_cc_pm_id:i.string().optional(),their_existing_pm_id:i.string().optional(),use_pay_first_flow:i.boolean().optional(),pay_first_flow_cart_info:Pi.optional()}).extend(xi.shape).extend(Ti.shape);const on=i.object({required_user_actions:i.array(i.record(i.string(),i.any())),checkout_attempt_id:C(i.string())});i.object({fields:yo,checkoutPaymentMethod:wt}),i.object({session_id:i.string(),non_cde_form_fields:gt,checkout_payment_method:wt,extra_metadata:i.record(i.string(),i.any())});const Ii=i.object({required_user_actions:i.array(i.record(i.string(),i.any())),cc_pm_id:i.string()});i.record(i.any()),i.object({first_name:C(i.string()),last_name:C(i.string()),line1:C(i.string()),line2:C(i.string()),line3:C(i.string()),city:C(i.string()),state:C(i.string()),country:C(i.string()),zip_code:C(i.string()),email:C(i.string()),billing_email:C(i.string()),phone_number:C(i.string()),update_processor_customer:C(i.boolean())});const Oi=i.object({id:i.string(),email:C(i.string()),first_name:C(i.string()),last_name:C(i.string()),phone_number:C(i.string()),billing_email:C(i.string()),address:C(i.record(i.string(),i.any()))}),Ri=r=>r.reduce((e,t)=>e+t,0);function Ni(r,e){var t=Object.setPrototypeOf;t?t(r,e):r.__proto__=e}function Mi(r,e){e===void 0&&(e=r.constructor);var t=Error.captureStackTrace;t&&t(r,e)}var ji=function(){var r=function(t,n){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,o){s.__proto__=o}||function(s,o){for(var a in o)Object.prototype.hasOwnProperty.call(o,a)&&(s[a]=o[a])},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)}}(),Di=function(r){ji(e,r);function e(t,n){var s=this.constructor,o=r.call(this,t,n)||this;return Object.defineProperty(o,"name",{value:s.name,enumerable:!1,configurable:!0}),Ni(o,s.prototype),Mi(o),o}return e}(Error);class an extends Di{constructor(e){const t=`${e.message}`;super(t),this.response=e}get originalErrorMessage(){return this.response.message}}const W=async(r,e,t)=>{const n=await r.send(e);if(Fi(n))throw new an(n);if(!Li(n,t)){const s=t.safeParse(n);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",t,"Actual:",n),s.error)}return n},Li=(r,e)=>e.safeParse(r).success,Fi=r=>hi.safeParse(r).success,Ui=async(r,e)=>await W(r,{type:"get_checkout_preview",payload:e},rn),Pe=async r=>await W(r,{type:"get_prefill",payload:{}},sn),ar=async(r,e)=>await W(r,{type:"v2_start_payment_flow",payload:e},on),$i=async(r,e)=>await W(r,{type:"start_payment_flow_for_cc",payload:e},Ii),Zi=async(r,e)=>await W(r,{type:"start_payment_flow_for_pr",payload:e},on),Te=async(r,e)=>await W(r,{type:"confirm_payment_flow",payload:e},To),Vi=async(r,e)=>await W(r,{type:"check_if_popup_window_verified",payload:e},Po),zi=async(r,e,t)=>{const n=await Ui(r,{secure_token:e,promotion_code:t}),s=new Set(n.preview.invoices.map(c=>c.currency));if(s.size!==1)throw new Error(`Expected exactly one currency, got ${s.size}`);const o=s.values().next().value??"usd",a=Ri(n.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:o,amountAtom:a}},jt=async(r,e,t,n)=>{if(t)return{amountAtom:0,currency:"usd"};{n=n||void 0;const s=await zi(r,e,n);return{amountAtom:s.amountAtom,currency:s.currency}}},Bi=async(r,e)=>{if(r.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(r.values()).map(n=>W(n,{type:"tokenize_card",payload:e},Co)))},cn=async(r,e)=>{try{return await W(r,{type:"checkout_card_elements",payload:e},sr)}catch(t){throw console.error("[cde-client] Error during checkoutCardElements:",t,JSON.stringify(t)),t}},qi=async(r,e)=>await W(r,{type:"setup_payment_method",payload:e},Si),Dt=async(r,e)=>await W(r,{type:"checkout",payload:e},sr),ln=1e3,Gi=async(r,e)=>{console.log(e);const n=await Jr({iframe:r,debug:!0,timeout:ln,childOrigin:"*"}).promise,s=await W(n,{type:"ping-3ds-status"},xo);return console.log("🟢 CDE connection successful! Stopping polling... Result:",s),s},Yi=async(r,e)=>await W(r,{type:"update_checkout_customer",payload:e},Oi);function cr(r){throw new Error(`Unhandled case: ${r}`)}const lr=10,un=(r=0)=>e=>`\x1B[${e+r}m`,dn=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,fn=(r=0)=>(e,t,n)=>`\x1B[${38+r};2;${e};${t};${n}m`,R={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(R.modifier);const Wi=Object.keys(R.color),Hi=Object.keys(R.bgColor);[...Wi,...Hi];function Ki(){const r=new Map;for(const[e,t]of Object.entries(R)){for(const[n,s]of Object.entries(t))R[n]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},t[n]=R[n],r.set(s[0],s[1]);Object.defineProperty(R,e,{value:t,enumerable:!1})}return Object.defineProperty(R,"codes",{value:r,enumerable:!1}),R.color.close="\x1B[39m",R.bgColor.close="\x1B[49m",R.color.ansi=un(),R.color.ansi256=dn(),R.color.ansi16m=fn(),R.bgColor.ansi=un(lr),R.bgColor.ansi256=dn(lr),R.bgColor.ansi16m=fn(lr),Object.defineProperties(R,{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(o=>o+o).join(""));const s=Number.parseInt(n,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:e=>R.rgbToAnsi256(...R.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,s;if(e>=232)t=((e-232)*10+8)/255,n=t,s=t;else{e-=16;const c=e%36;t=Math.floor(e/36)/5,n=Math.floor(c/6)/5,s=c%6/5}const o=Math.max(t,n,s)*2;if(o===0)return 30;let a=30+(Math.round(s)<<2|Math.round(n)<<1|Math.round(t));return o===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>R.ansi256ToAnsi(R.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>R.ansi256ToAnsi(R.hexToAnsi256(e)),enumerable:!1}}),R}const ue=Ki(),Lt=(()=>{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=Lt!==0&&{level:Lt,hasBasic:!0,has256:Lt>=2,has16m:Lt>=3},Ji={stdout:pn,stderr:pn};function Qi(r,e,t){let n=r.indexOf(e);if(n===-1)return r;const s=e.length;let o=0,a="";do a+=r.slice(o,n)+e+t,o=n+s,n=r.indexOf(e,o);while(n!==-1);return a+=r.slice(o),a}function Xi(r,e,t,n){let s=0,o="";do{const a=r[n-1]==="\r";o+=r.slice(s,a?n-1:n)+e+(a?`\r
7
7
  `:`
8
8
  `)+t,s=n+1,n=r.indexOf(`
9
- `,s)}while(n!==-1);return o+=r.slice(s),o}const{stdout:pn,stderr:hn}=Ji,ur=Symbol("GENERATOR"),Ye=Symbol("STYLER"),bt=Symbol("IS_EMPTY"),mn=["ansi","ansi","ansi256","ansi16m"],We=Object.create(null),ea=(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=pn?pn.level:0;r.level=e.level===void 0?t:e.level},ta=r=>{const e=(...t)=>t.join(" ");return ea(e,r),Object.setPrototypeOf(e,kt.prototype),e};function kt(r){return ta(r)}Object.setPrototypeOf(kt.prototype,Function.prototype);for(const[r,e]of Object.entries(ce))We[r]={get(){const t=Ut(this,fr(e.open,e.close,this[Ye]),this[bt]);return Object.defineProperty(this,r,{value:t}),t}};We.visible={get(){const r=Ut(this,this[Ye],!0);return Object.defineProperty(this,"visible",{value:r}),r}};const dr=(r,e,t,...n)=>r==="rgb"?e==="ansi16m"?ce[t].ansi16m(...n):e==="ansi256"?ce[t].ansi256(ce.rgbToAnsi256(...n)):ce[t].ansi(ce.rgbToAnsi(...n)):r==="hex"?dr("rgb",e,t,...ce.hexToRgb(...n)):ce[t][r](...n),ra=["rgb","hex","ansi256"];for(const r of ra){We[r]={get(){const{level:t}=this;return function(...n){const s=fr(dr(r,mn[t],"color",...n),ce.color.close,this[Ye]);return Ut(this,s,this[bt])}}};const e="bg"+r[0].toUpperCase()+r.slice(1);We[e]={get(){const{level:t}=this;return function(...n){const s=fr(dr(r,mn[t],"bgColor",...n),ce.bgColor.close,this[Ye]);return Ut(this,s,this[bt])}}}}const na=Object.defineProperties(()=>{},{...We,level:{enumerable:!0,get(){return this[ur].level},set(r){this[ur].level=r}}}),fr=(r,e,t)=>{let n,s;return t===void 0?(n=r,s=e):(n=t.openAll+r,s=e+t.closeAll),{open:r,close:e,openAll:n,closeAll:s,parent:t}},Ut=(r,e,t)=>{const n=(...s)=>sa(n,s.length===1?""+s[0]:s.join(" "));return Object.setPrototypeOf(n,na),n[ur]=r,n[Ye]=e,n[bt]=t,n},sa=(r,e)=>{if(r.level<=0||!e)return r[bt]?"":e;let t=r[Ye];if(t===void 0)return e;const{openAll:n,closeAll:s}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Qi(e,t.close,t.open),t=t.parent;const o=e.indexOf(`
10
- `);return o!==-1&&(e=Xi(e,s,n,o)),n+e+s};Object.defineProperties(kt.prototype,We);const $t=kt();kt({level:hn?hn.level:0});const He=r=>async e=>{var t,n;try{(n=(t=e.formCallbacks.get).onCheckoutStarted)==null||n.call(t);const s=await r(e);if(s.mode==="setup")e.formCallbacks.get.onSetupPaymentMethodSuccess(s.result.payment_method_id);else if(s.mode==="checkout")e.formCallbacks.get.onCheckoutSuccess(s.result.invoice_urls,s.result.subscription_ids,s.result.customer_id);else throw new Error(`Unhandled mode: ${s}`)}catch(s){e.formCallbacks.get.onCheckoutError(he(s))}},Zt=r=>async e=>{try{return await r(e)}catch(t){const{err__:n}=F("init-error-catcher");return n(t),{isAvailable:!1,reason:he(t)}}},F=r=>{const e=(...n)=>{window.console.log(`${$t.green.bold("ojs/")}${$t.bold.gray(`${r}`)} `,...n)},t=(...n)=>{window.console.warn(`${$t.red.bold("ojs/")}${$t.bold.gray(`${r}`)} `,...n)};return{log:e,err:t,log__:e,err__:t}},{log__:ml,err__:oa}=F("common"),pr=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}},Ke=(r,e)=>{const t=r.find(n=>e.safeParse(n).success);if(!t)throw oa("No CPMs found for model. All models:",r),new Error("No CPMs found for model");return e.parse(t)},ia=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}),{log__:yn,err__:_n}=F("common-cc"),Je=(r,e,t)=>{if(t){yn(`Received default field values: ${JSON.stringify(t)}`);for(const[s,o]of Object.entries(t))r[s]||(r[s]=o)}const n=gt.safeParse(r);if(!n.success){const s=n.error.format(),o=To(s);for(const[a,c]of Object.entries(o))e(a,c,a);throw _n("Got validation errors in non-CDE form fields",o),new Error("Got validation errors in non-CDE form fields")}return n.data},aa=(r,e)=>{for(const t of r)if(t.success===!1)throw t.errors.forEach(n=>{const s=Zr.safeParse(n.elementType);if(!s.success)_n(`Unknown field name in onValidationError: ${n.elementType}. Error object:`,n);else{const o=s.data;e(o,n.errors)}}),yn(`Error tokenizing card: got validation errors: ${JSON.stringify(t.errors)}`),new Error("Got validation errors while tokenizing card")},gn="ojs-stripe-link-btn",{log__:U,err__:ca}=F("stripe-link"),la=i.object({provider:i.literal("stripe_link"),processor_name:i.literal("stripe"),metadata:i.object({stripe_pk:i.string()})}),ua=i.array(i.object({our_existing_pm_id:i.string()})).length(1),da=Zt(async({context:r,formCallbacks:e})=>{const t=r.customInitParams.stripeLink;U("Checking if there are any CPMs for Stripe Link...");const n=Ke(r.checkoutPaymentMethods,la);U("Starting stripe link flow...");const s=r.anyCdeConnection,o=await Ae(s),a=o.mode==="setup";U("Creating stripe elements...");const c=await Dt(s,o.token,a,void 0),{elements:u,stripe:l}=await No(n.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});U("Creating express checkout...");const d=u.create("expressCheckout",{buttonHeight:t==null?void 0:t.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),h=()=>{d.mount(`#${gn}`)},w=()=>{d.unmount()};return t!=null&&t.doNotMountOnInit?U("NOT mounting stripe link button (doNotMountOnInit is true)"):(U("Mounting stripe link button..."),h()),d.on("click",async m=>{if(U("Stripe Link button clicked"),t!=null&&t.overrideLinkSubmit&&!await t.overrideLinkSubmit()){U("Stripe Link submit aborted by overrideLinkSubmit");return}m.resolve()}),d.on("confirm",async m=>{U("Stripe Link window confirmed",m);const g=await l.createPaymentMethod({elements:u,params:{billing_details:m.billingDetails}});g.error?(ca("error",g.error),e.get.onCheckoutError(g.error.message??"Stripe Link unknown error")):(U("paymentMethod",g.paymentMethod),te.stripeLink.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:Ge(r.formDiv),formCallbacks:e,customParams:{stripePM:g.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:h,dismountButton:w,waitForButtonToMount:async()=>await ha(gn)}}}),fa=He(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{U("Running Stripe Link flow...");const o=r.anyCdeConnection;U("Merging PM fields with form fields...");const a=pa(t,s.stripePM),c=Je(a,n.get.onValidationError);U("Starting payment flow...");const u=await jt(o,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:s.stripePM.id,new_customer_email:c[p.EMAIL],new_customer_first_name:c[p.FIRST_NAME],new_customer_last_name:c[p.LAST_NAME],new_customer_address:{zip_code:c[p.ZIP_CODE],country:c[p.COUNTRY]}});U("Start payment flow response",u);const d=ua.parse(u.required_user_actions)[0].our_existing_pm_id,h=await Ae(o);if(h.mode==="setup"){U("Doing payment setup...");const w=await Pe(o,{secure_token:h.token,existing_cc_pm_id:d});return{mode:"setup",result:pr(w)}}else{U("Doing checkout...");const w={secure_token:h.token,payment_input:{provider_type:e.provider},customer_email:c[p.EMAIL],customer_zip_code:c[p.ZIP_CODE],customer_country:c[p.COUNTRY],promotion_code:c[p.PROMOTION_CODE],line_items:h.line_items,total_amount_atom:h.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Lt(o,w)}}}),pa=(r,e)=>{var a,c,u,l,d;const t={...r},[n,...s]=((c=(a=e.billing_details.name)==null?void 0:a.trim())==null?void 0:c.split(/\s+/))??[],o=s.join(" ")||void 0;return t[p.FIRST_NAME]=t[p.FIRST_NAME]||n||"_OP_UNKNOWN",t[p.LAST_NAME]=t[p.LAST_NAME]||o||"_OP_UNKNOWN",t[p.EMAIL]=t[p.EMAIL]||((u=e.link)==null?void 0:u.email)||e.billing_details.email||"op_unfilled@getopenpay.com",t[p.ZIP_CODE]=t[p.ZIP_CODE]||((l=e.billing_details.address)==null?void 0:l.postal_code)||"00000",t[p.COUNTRY]=t[p.COUNTRY]||((d=e.billing_details.address)==null?void 0:d.country)||"US",U("Final form inputs:",t),t},ha=r=>new Promise(e=>{const t=()=>{const n=document.getElementById(r);n?e(n):requestAnimationFrame(t)};t()}),ma="@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}",ya=r=>{const e=document.createElement("template");e.innerHTML=`
9
+ `,s)}while(n!==-1);return o+=r.slice(s),o}const{stdout:hn,stderr:mn}=Ji,ur=Symbol("GENERATOR"),Ye=Symbol("STYLER"),bt=Symbol("IS_EMPTY"),yn=["ansi","ansi","ansi256","ansi16m"],We=Object.create(null),ea=(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=hn?hn.level:0;r.level=e.level===void 0?t:e.level},ta=r=>{const e=(...t)=>t.join(" ");return ea(e,r),Object.setPrototypeOf(e,kt.prototype),e};function kt(r){return ta(r)}Object.setPrototypeOf(kt.prototype,Function.prototype);for(const[r,e]of Object.entries(ue))We[r]={get(){const t=Ft(this,fr(e.open,e.close,this[Ye]),this[bt]);return Object.defineProperty(this,r,{value:t}),t}};We.visible={get(){const r=Ft(this,this[Ye],!0);return Object.defineProperty(this,"visible",{value:r}),r}};const dr=(r,e,t,...n)=>r==="rgb"?e==="ansi16m"?ue[t].ansi16m(...n):e==="ansi256"?ue[t].ansi256(ue.rgbToAnsi256(...n)):ue[t].ansi(ue.rgbToAnsi(...n)):r==="hex"?dr("rgb",e,t,...ue.hexToRgb(...n)):ue[t][r](...n),ra=["rgb","hex","ansi256"];for(const r of ra){We[r]={get(){const{level:t}=this;return function(...n){const s=fr(dr(r,yn[t],"color",...n),ue.color.close,this[Ye]);return Ft(this,s,this[bt])}}};const e="bg"+r[0].toUpperCase()+r.slice(1);We[e]={get(){const{level:t}=this;return function(...n){const s=fr(dr(r,yn[t],"bgColor",...n),ue.bgColor.close,this[Ye]);return Ft(this,s,this[bt])}}}}const na=Object.defineProperties(()=>{},{...We,level:{enumerable:!0,get(){return this[ur].level},set(r){this[ur].level=r}}}),fr=(r,e,t)=>{let n,s;return t===void 0?(n=r,s=e):(n=t.openAll+r,s=e+t.closeAll),{open:r,close:e,openAll:n,closeAll:s,parent:t}},Ft=(r,e,t)=>{const n=(...s)=>sa(n,s.length===1?""+s[0]:s.join(" "));return Object.setPrototypeOf(n,na),n[ur]=r,n[Ye]=e,n[bt]=t,n},sa=(r,e)=>{if(r.level<=0||!e)return r[bt]?"":e;let t=r[Ye];if(t===void 0)return e;const{openAll:n,closeAll:s}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Qi(e,t.close,t.open),t=t.parent;const o=e.indexOf(`
10
+ `);return o!==-1&&(e=Xi(e,s,n,o)),n+e+s};Object.defineProperties(kt.prototype,We);const Ut=kt();kt({level:mn?mn.level:0});const He=r=>async e=>{var t,n;try{(n=(t=e.formCallbacks.get).onCheckoutStarted)==null||n.call(t);const s=await r(e);if(s.mode==="setup")e.formCallbacks.get.onSetupPaymentMethodSuccess(s.result.payment_method_id);else if(s.mode==="checkout")e.formCallbacks.get.onCheckoutSuccess(s.result.invoice_urls,s.result.subscription_ids,s.result.customer_id);else throw new Error(`Unhandled mode: ${s}`)}catch(s){e.formCallbacks.get.onCheckoutError(ye(s))}},$t=r=>async e=>{try{return await r(e)}catch(t){const{err__:n}=U("init-error-catcher");return n(t),{isAvailable:!1,reason:ye(t)}}},U=r=>{const e=(...n)=>{window.console.log(`${Ut.green.bold("ojs/")}${Ut.bold.gray(`${r}`)} `,...n)},t=(...n)=>{window.console.warn(`${Ut.red.bold("ojs/")}${Ut.bold.gray(`${r}`)} `,...n)};return{log:e,err:t,log__:e,err__:t}},{log__:ml,err__:oa}=U("common"),pr=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}},Ke=(r,e)=>{const t=r.find(n=>e.safeParse(n).success);if(!t)throw oa("No CPMs found for model. All models:",r),new Error("No CPMs found for model");return e.parse(t)},ia=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}),{log__:_n,err__:gn}=U("common-cc"),Je=(r,e,t)=>{if(t){_n(`Received default field values: ${JSON.stringify(t)}`);for(const[s,o]of Object.entries(t))r[s]||(r[s]=o)}const n=gt.safeParse(r);if(!n.success){const s=n.error.format(),o=Io(s);for(const[a,c]of Object.entries(o))e(a,c,a);throw gn("Got validation errors in non-CDE form fields",o),new Error("Got validation errors in non-CDE form fields")}return n.data},aa=(r,e)=>{for(const t of r)if(t.success===!1)throw t.errors.forEach(n=>{const s=Zr.safeParse(n.elementType);if(!s.success)gn(`Unknown field name in onValidationError: ${n.elementType}. Error object:`,n);else{const o=s.data;e(o,n.errors)}}),_n(`Error tokenizing card: got validation errors: ${JSON.stringify(t.errors)}`),new Error("Got validation errors while tokenizing card")},vn="ojs-stripe-link-btn",{log__:$,err__:ca}=U("stripe-link"),la=i.object({provider:i.literal("stripe_link"),processor_name:i.literal("stripe"),metadata:i.object({stripe_pk:i.string()})}),ua=i.array(i.object({our_existing_pm_id:i.string()})).length(1),da=$t(async({context:r,formCallbacks:e})=>{const t=r.customInitParams.stripeLink;$("Checking if there are any CPMs for Stripe Link...");const n=Ke(r.checkoutPaymentMethods,la);$("Starting stripe link flow...");const s=r.anyCdeConnection,o=await Pe(s),a=o.mode==="setup";$("Creating stripe elements...");const c=await jt(s,o.token,a,void 0),{elements:u,stripe:l}=await Mo(n.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});$("Creating express checkout...");const d=u.create("expressCheckout",{buttonHeight:t==null?void 0:t.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),h=()=>{d.mount(`#${vn}`)},w=()=>{d.unmount()};return t!=null&&t.doNotMountOnInit?$("NOT mounting stripe link button (doNotMountOnInit is true)"):($("Mounting stripe link button..."),h()),d.on("click",async m=>{if($("Stripe Link button clicked"),t!=null&&t.overrideLinkSubmit&&!await t.overrideLinkSubmit()){$("Stripe Link submit aborted by overrideLinkSubmit");return}m.resolve()}),d.on("confirm",async m=>{$("Stripe Link window confirmed",m);const g=await l.createPaymentMethod({elements:u,params:{billing_details:m.billingDetails}});g.error?(ca("error",g.error),e.get.onCheckoutError(g.error.message??"Stripe Link unknown error")):($("paymentMethod",g.paymentMethod),re.stripeLink.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:Ge(r.formDiv),formCallbacks:e,customParams:{stripePM:g.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:h,dismountButton:w,waitForButtonToMount:async()=>await ha(vn)}}}),fa=He(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{$("Running Stripe Link flow...");const o=r.anyCdeConnection;$("Merging PM fields with form fields...");const a=pa(t,s.stripePM),c=Je(a,n.get.onValidationError);$("Starting payment flow...");const u=await ar(o,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:s.stripePM.id,new_customer_email:c[p.EMAIL],new_customer_first_name:c[p.FIRST_NAME],new_customer_last_name:c[p.LAST_NAME],new_customer_address:{zip_code:c[p.ZIP_CODE],country:c[p.COUNTRY]}});$("Start payment flow response",u);const d=ua.parse(u.required_user_actions)[0].our_existing_pm_id,h=await Pe(o);if(h.mode==="setup"){$("Doing payment setup...");const w=await Te(o,{secure_token:h.token,existing_cc_pm_id:d});return{mode:"setup",result:pr(w)}}else{$("Doing checkout...");const w={secure_token:h.token,payment_input:{provider_type:e.provider},customer_email:c[p.EMAIL],customer_zip_code:c[p.ZIP_CODE],customer_country:c[p.COUNTRY],promotion_code:c[p.PROMOTION_CODE],line_items:h.line_items,total_amount_atom:h.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Dt(o,w)}}}),pa=(r,e)=>{var a,c,u,l,d;const t={...r},[n,...s]=((c=(a=e.billing_details.name)==null?void 0:a.trim())==null?void 0:c.split(/\s+/))??[],o=s.join(" ")||void 0;return t[p.FIRST_NAME]=t[p.FIRST_NAME]||n||"_OP_UNKNOWN",t[p.LAST_NAME]=t[p.LAST_NAME]||o||"_OP_UNKNOWN",t[p.EMAIL]=t[p.EMAIL]||((u=e.link)==null?void 0:u.email)||e.billing_details.email||"op_unfilled@getopenpay.com",t[p.ZIP_CODE]=t[p.ZIP_CODE]||((l=e.billing_details.address)==null?void 0:l.postal_code)||"00000",t[p.COUNTRY]=t[p.COUNTRY]||((d=e.billing_details.address)==null?void 0:d.country)||"US",$("Final form inputs:",t),t},ha=r=>new Promise(e=>{const t=()=>{const n=document.getElementById(r);n?e(n):requestAnimationFrame(t)};t()}),ma="@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}",ya=r=>{const e=document.createElement("template");e.innerHTML=`
11
11
  <style>
12
12
  ${ma}
13
13
  </style>
@@ -17,9 +17,9 @@ ${r.message}`),r.message)}else return sr(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 s=n.querySelector("#three-ds-iframe"),o=n.querySelector(".cancel-button");return document.body.appendChild(t),{host:t,iframe:s,cancelButton:o}};function _a(r,e,t){const n=async()=>{try{const o=await Gi(r,t);o&&(clearInterval(s),e(o))}catch{}};n();const s=setInterval(n,cn);return s}function ga({elements:r,pollingInterval:e,resolve:t}){const n=()=>{clearInterval(e),r.host.remove(),t({status:ee.CANCELLED})};return r.cancelButton.addEventListener("click",n),()=>{r.cancelButton.removeEventListener("click",n)}}async function Vt(r){const{url:e,baseUrl:t}=r,n=ya(e);return new Promise(s=>{const o=u=>{setTimeout(()=>{n.host.remove()},1e3),s(u),c==null||c()},a=_a(n.iframe,o,new URL(t).origin),c=ga({elements:n,pollingInterval:a,resolve:s})})}const vn=async r=>{const e=await Vt(r);if(e.status===ee.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===ee.FAILURE)throw new Error("3DS verification failed");return e.status!==ee.SUCCESS&&cr(e.status),{href:e.href}},va=(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},wa=async(r,e,t,n)=>{const{err__:s}=F("popup-verify");return new Promise((o,a)=>{const c=va(r,n),u=setInterval(async()=>{try{const l=await Vi(e,t);if(l.present)clearInterval(u),c.close(),o({href:l.href});else if(c.closed)throw new Error(`${r} payment cancelled`)}catch(l){s(he(l)),clearInterval(u),a(he(l))}},1e3)})},{log__:ba,err__:wn}=F("pockyt-cc"),ka=i.object({"op-pockyt-3ds-url":i.string(),"op-pockyt-txn-no":i.string(),"op-pockyt-ref-no":i.string()}),Ea=r=>{const e=ka.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 wn(n),new Error(t)}return e.data},bn=r=>{try{const e=new URL(r??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return ba(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const t="Error verifying 3DS verification result.";throw wn(t,`Resulting URL: ${r}.
21
- Error: ${he(e)}`),new Error(t)}},Sa=r=>(r==null?void 0:r["op-pockyt-3ds-url"])!==void 0,Ca=async(r,e)=>{const t=Ea(e),n=await vn({url:t["op-pockyt-3ds-url"],baseUrl:r});return{existing_cc:{vault_id:bn(n.href??""),transaction_no:t["op-pockyt-txn-no"],reference_no:t["op-pockyt-ref-no"]}}},{log__:xa,err__:hr}=F("airwallex-cc"),Aa=i.object({"op-airwallex-3ds-url":i.string(),"op-airwallex-initial-intent-id":i.string(),"op-airwallex-consent-id":i.string()}),Pa=r=>{const e=Aa.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 hr(n),new Error(t)}return e.data},Ta=r=>(r==null?void 0:r["op-airwallex-3ds-url"])!==void 0,Ia=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 xa(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const t="Error verifying Airwallex 3DS verification result.";throw hr(t,`Resulting URL: ${r}.
22
- Error: ${he(e)}`),new Error(t)}},Oa=async(r,e)=>{const t=Pa(e),n=await vn({url:t["op-airwallex-3ds-url"],baseUrl:r}),s=Ia(n.href??""),o=t["op-airwallex-initial-intent-id"];if(o!==s){const c="Unable to process your credit card. Please contact support for assistance.",u=`Intent ID from callback (${s}) does not match the initial intent ID (${o}).`;throw hr(u),new Error(c)}return{existing_cc:{initial_intent_id:s,consent_id:t["op-airwallex-consent-id"]}}},{log__:N,err__:kn}=F("common-cc"),{log__:En}=F("stripe-cc");i.array(i.object({our_existing_pm_id:i.string()})).length(1);const Ra=He(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{var l;N("├ Running common CC flow...",{checkoutPaymentMethod:e});const o=r.anyCdeConnection,a=await Ae(o);N(`├ Validating non-CDE form fields [Mode: ${a.mode}]`);const c=Je(t,n.get.onValidationError),u={session_id:r.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{}};try{N(`├ Tokenizing card info in CDE [Session: ${r.elementsSessionId}]`);const d=await Bi(s.currentCdeConnections,{session_id:r.elementsSessionId});if(aa(d,n.get.onValidationError),a.mode==="setup"){N(`├ Setting up payment method in CDE [Token: ${a.token}]`);const h=await qi(o,u);return N(`╰ Setup completed successfully [PM ID: ${h.payment_method_id}]`),{mode:"setup",result:h}}else{N(`├ Initial checkout flow. Checking out card info in CDE [Session: ${r.elementsSessionId}]`);const h=await an(o,u);return N("╰ Checkout completed successfully."),{mode:"checkout",result:h}}}catch(d){if(d instanceof on&&d.originalErrorMessage.includes("3DS_REQUIRED")){N("├ Card requires 3DS, starting non-legacy payment flow"),N("Received 3DS error response headers:",d.response.headers);const h=Sa(d.response.headers);if(h){N("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const A=await Ca(r.baseUrl,d.response.headers);u.extra_metadata.pockyt=A}if(Ta(d.response.headers)){N("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const A=await Oa(r.baseUrl,d.response.headers);u.extra_metadata.airwallex=A}const m=await $i(o,u);N("├ Payment flow result:",m);const g=((l=d.response.headers)==null?void 0:l["op-should-use-new-flow"])!=="true";h?N("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):g?(N("├ Using stripe 3DS flow"),await Da(m)):(N("├ Using common 3DS flow"),await ja(m,r.baseUrl));const b=m.cc_pm_id;if(a.mode==="setup"){N(`├ Confirming payment flow [cc_pm_id: ${b}]`);const A=await Pe(o,{secure_token:a.token,existing_cc_pm_id:b});N("├ Confirm payment flow result received Result:",A);const O=pr(A);return N(`╰ Setup completed successfully [PM ID: ${O.payment_method_id}]`),{mode:"setup",result:O}}else{N(`├ Checking out after 3DS flow [Flow: ${g?"legacy":"new"}]`);const A=await an(o,{...u,existing_cc_pm_id:b,do_not_use_legacy_cc_flow:g});return N("╰ Checkout completed successfully."),{mode:"checkout",result:A}}}throw kn("╰ Error checking out card info in CDE"),kn(d),d}}),Na=r=>{const e=r.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Io.parse(e)},Ma=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 xo.parse(e)},ja=async(r,e)=>{const t=Ma(r);if(t.type==="airwallex_payment_consent"&&t.redirect_url==="3DS_COMPLETE"){N("├ Airwallex 3DS flow completed successfully");return}N(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const{status:n}=await Vt({url:t.redirect_url,baseUrl:e});if(N(`╰ 3DS verification completed [Status: ${n}]`),n===ee.CANCELLED)throw new Error("3DS verification cancelled");if(n===ee.FAILURE)throw new Error("3DS verification failed")},Da=async r=>{const e=Na(r);En(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Lo(e),En("╰ Stripe 3DS flow completed successfully")},{log__:B,err__:La}=F("stripe-pr"),Fa=i.object({provider:i.union([i.literal("apple_pay"),i.literal("google_pay")]),processor_name:i.literal("stripe"),metadata:i.object({stripe_pk:i.string()})}),Ua=Zt(async({context:r})=>{B("Checking if there are any CPMs for Stripe PR...");const e=Ke(r.checkoutPaymentMethods,Fa);B("Initializing Stripe PR flow...");const t=r.anyCdeConnection,n=await Ae(t),s=n.mode==="setup";B("Getting initial preview amount");const o=await Dt(t,n.token,s,void 0),a=await Mo(e.metadata.stripe_pk,o.amountAtom,o.currency,s);B("Checking if can make payment");const c=await a.canMakePayment();return c===null?(La("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"}):(B("Stripe PR flow initialized successfully. Can make payment",c),{isAvailable:!0,pr:a,availableProviders:{applePay:c.applePay,googlePay:c.googlePay}})}),$a=He(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s,initResult:o})=>{if(B("Running Stripe PR flow..."),s.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${s.provider}, got ${e.provider}`);const a=r.anyCdeConnection,c=o.pr;if(s!=null&&s.overridePaymentRequest){const g=s.overridePaymentRequest;B("Overriding PR amount with",g),Va(c,g.amount,g.pending,g.stripeApplePay)}B("Showing PR dialog..."),c.show();const u=await jo(c);B("Stripe PM added event:",u),B("Merging PM fields with form fields...");const l=Za(t,u),d=Je(l,n.get.onValidationError);B("PR dialog finished. Starting payment flow...",d);const h=await Zi(a,{fields:d,checkoutPaymentMethod:e}),w=za(h);B("Confirming PR with Stripe..."),await Do(w,u);const m=await Ae(a);if(m.mode==="setup"){B("Confirming payment flow for setup...");const g=await Pe(a,{secure_token:m.token});return{mode:"setup",result:pr(g)}}else{B("Performing checkout...");const g={secure_token:m.token,payment_input:{provider_type:e.provider},customer_first_name:d[p.FIRST_NAME],customer_last_name:d[p.LAST_NAME],customer_email:d[p.EMAIL],customer_zip_code:d[p.ZIP_CODE],customer_country:d[p.COUNTRY],promotion_code:d[p.PROMOTION_CODE],line_items:m.line_items,total_amount_atom:m.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Lt(a,g)}}}),Za=(r,e)=>{var u,l,d,h;const t={...r},[n,...s]=((l=(u=e.payerName)==null?void 0:u.trim())==null?void 0:l.split(/\s+/))??[],o=s.join(" ")||void 0,a=(h=(d=e.paymentMethod)==null?void 0:d.billing_details)==null?void 0:h.address,c=e.shippingAddress;return t[p.FIRST_NAME]=t[p.FIRST_NAME]||n||"_OP_UNKNOWN",t[p.LAST_NAME]=t[p.LAST_NAME]||o||"_OP_UNKNOWN",t[p.EMAIL]=t[p.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[p.ZIP_CODE]=t[p.ZIP_CODE]||(a==null?void 0:a.postal_code)||(c==null?void 0:c.postalCode)||"00000",t[p.COUNTRY]=t[p.COUNTRY]||(a==null?void 0:a.country)||(c==null?void 0:c.country)||"US",B("Final form inputs:",t),t},Va=(r,e,t,n)=>{r.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency,applePay:n})},za=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 Oo.parse(r.required_user_actions[0])},{log__:me,err__:Sn}=F("pockyt-paypal"),Ba=i.object({processor_name:i.literal("pockyt"),provider:i.literal("paypal")}),qa=i.array(i.object({paypal_iframe_url:i.string(),verify_token:i.string()})).length(1),Ga=He(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{var g,b;me("Running Pockyt Paypal flow...");const o=r.anyCdeConnection,a=await Ae(o);me("Verifying CPM...");const c=Ba.parse(e);me("├ Validating non-CDE form fields");const u=s==null?void 0:s.settings,l=Je(t,n.get.onValidationError,u==null?void 0:u.defaultFieldValues),d=ia(l);me(`Starting payment flow... Mode: ${a.mode}`);const h=a.mode!=="setup",w=await jt(o,{payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:h,pay_first_flow_cart_info:h?{line_items:a.line_items,displayed_total_amount_atom:a.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((g=s==null?void 0:s.settings)!=null&&g.useRedirectFlow)},...d});if(me("Start payment flow response",w),!w.checkout_attempt_id)throw Sn("Checkout attempt ID not found in response:",w),new Error("An error occurred during checkout, please try again with another payment method.");const m=qa.parse(w.required_user_actions)[0];if((b=s==null?void 0:s.settings)!=null&&b.useRedirectFlow)throw window.location.href=m.paypal_iframe_url,await zr(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");{me("Opening paypal iframe...");const A=await wa("PayPal",o,m.verify_token,m.paypal_iframe_url);me("Paypal flow result",A);const O=bn(A.href);me(`Confirming payment flow using vault ID ${O}`);const T=await Pe(o,{secure_token:a.token,their_pm_id:O,checkout_attempt_id:h?w.checkout_attempt_id:void 0});if(me("Confirm payment flow result",T),a.mode==="setup")return{mode:"setup",result:{payment_method_id:T.payment_methods[0].id}};if(!T.pay_first_success_response)throw Sn("Checkout failed, no pay-first success response:",T),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:T.pay_first_success_response}}}),Cn=({gateway:r,gatewayMerchantId:e,merchantName:t,merchantId:n,initialPreview:s,overridePaymentRequest:o})=>{var d,h;const a=((d=o==null?void 0:o.amount)==null?void 0:d.amountAtom)??(s==null?void 0:s.amountAtom)??0,c=Math.max(a/100,0),u=(((h=o==null?void 0:o.amount)==null?void 0:h.currency)??(s==null?void 0:s.currency)??"USD").toUpperCase(),l={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:o!=null&&o.pending?"ESTIMATED":"FINAL",totalPrice:c.toFixed(2)}};return o!=null&&o.googlePayPaymentRequest?{...l,...o.googlePayPaymentRequest}:l},Ya=()=>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)}),Wa=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");return e?Vr.parse(e):null},Ha=(r,e)=>{var s,o,a,c;const t={...r},n=(o=(s=e.paymentMethodData)==null?void 0:s.info)==null?void 0:o.billingAddress;if(n){const[u,...l]=((c=(a=n.name)==null?void 0:a.trim())==null?void 0:c.split(/\s+/))??[],d=l.join(" ")||void 0;t[p.EMAIL]=t[p.EMAIL]||e.email||"op_unfilled@getopenpay.com",t[p.COUNTRY]=t[p.COUNTRY]||n.countryCode||"US",t[p.ADDRESS]=t[p.ADDRESS]||n.address1||"",t[p.CITY]=t[p.CITY]||n.locality||"",t[p.ZIP_CODE]=t[p.ZIP_CODE]||n.postalCode||"00000",t[p.STATE]=t[p.STATE]||n.administrativeArea||"",t[p.FIRST_NAME]=t[p.FIRST_NAME]||u||"_OP_UNKNOWN",t[p.LAST_NAME]=t[p.LAST_NAME]||d||"_OP_UNKNOWN"}return t},{log__:H,err__:Qe}=F("awx-google-pay");let mr=null;const xn=r=>r===Fe||r===window.location.origin?"PRODUCTION":"TEST",An=(r,e)=>{const t=xn(r);return mr===null&&(mr=new window.google.payments.api.PaymentsClient({environment:t,merchantInfo:e.merchantInfo})),mr},Pn=i.object({provider:i.literal("google_pay"),processor_name:i.literal("airwallex"),metadata:i.object({processor_account_id:i.string(),processor_account_name:i.string(),google_pay_merchant_id:i.string().nullish()})}),Ka=Zt(async({context:r,formCallbacks:e})=>{var a,c;const t=Ke(r.checkoutPaymentMethods,Pn);if(!t)return{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};H("Google Pay CPM",t);const n=t.metadata;if(!n.processor_account_id)return Qe("No gateway merchant ID found in processor account"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};if(H("Loading Google Pay SDK..."),await Ya(),!((c=(a=window.google)==null?void 0:a.payments)!=null&&c.api))return Qe("Google Pay SDK not loaded properly"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};if(xn(r.baseUrl)==="PRODUCTION"&&!n.google_pay_merchant_id)return Qe("Google Pay merchant ID is required for production environment"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};H("Google Pay SDK loaded",window.google.payments);try{const u=Cn({gateway:"airwallex",gatewayMerchantId:n.processor_account_id,merchantName:n.processor_account_name,merchantId:n.google_pay_merchant_id??"",initialPreview:void 0}),{result:l}=await An(r.baseUrl,u).isReadyToPay(u);if(!l)return H("Google Pay is not available for this user"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}}}catch(u){return Qe("Error checking Google Pay availability",u),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}}}return{isAvailable:!0,isLoading:!1,startFlow:async u=>{try{te.airwallexGooglePay.run({context:r,checkoutPaymentMethod:t,nonCdeFormInputs:Ge(r.formDiv),formCallbacks:e,initResult:void 0,customParams:u??{}})}catch(l){Qe("Google Pay payment error",l),e.get.onCheckoutError((l==null?void 0:l.message)??"Unknown error")}}}}),Ja=He(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{var h,w,m,g,b,A,O;H("Starting Google Pay flow...");const o=Ke(r.checkoutPaymentMethods,Pn),a=r.anyCdeConnection,c=await Ae(a),u=o.metadata;if(!u.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const l=Cn({gateway:"airwallex",gatewayMerchantId:u.processor_account_id,merchantName:u.processor_account_name,merchantId:u.google_pay_merchant_id??"",initialPreview:await Dt(a,c.token,c.mode==="setup",void 0),overridePaymentRequest:s==null?void 0:s.overridePaymentRequest}),d=An(r.baseUrl,l);try{const T=await d.loadPaymentData(l);H("Google Pay Payment data",T);const M=Ha(t,T),j=Je(M,n.get.onValidationError,s==null?void 0:s.defaultFieldValues),W=(w=(h=T.paymentMethodData)==null?void 0:h.tokenizationData)==null?void 0:w.token;if(!W)throw new Error("No payment token received from Google Pay");const Ie=await jt(a,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:j[p.EMAIL],new_customer_first_name:j[p.FIRST_NAME],new_customer_last_name:j[p.LAST_NAME],new_customer_address:{postal_code:j[p.ZIP_CODE],country_code:j[p.COUNTRY]}}),ue=Wa(Ie);H("Start flow next actions",ue);const we=await Pe(a,{secure_token:c.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:ue==null?void 0:ue.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:W}}}});H("[1st] Confirm payment flow response",we);let ne=(g=(m=we.payment_methods)==null?void 0:m[0])==null?void 0:g.id;const Le=(b=we.required_user_actions)==null?void 0:b.find(de=>de.type==="airwallex_payment_consent");if(Le&&Le.redirect_url){H("3DS Required, starting verification...",Le);const{status:de}=await Vt({url:Le.redirect_url,baseUrl:r.baseUrl});if(H(`╰ 3DS verification completed [Status: ${de}]`),de===ee.CANCELLED)throw new Error("3DS verification cancelled");if(de===ee.FAILURE)throw new Error("3DS verification failed")}if(Le&&!ne){const de=await Pe(a,{secure_token:c.token,their_pm_id:Le.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Le.consent_id}});H("[2nd] Confirm payment flow response",de),ne=(O=(A=de.payment_methods)==null?void 0:A[0])==null?void 0:O.id}if(!ne)throw new Error("No PM ID found");if(c.mode==="setup")return{mode:"setup",result:{payment_method_id:ne}};{H("Starting one-time payment flow...");const de={secure_token:c.token,payment_input:{provider_type:e.provider},do_not_use_legacy_cc_flow:!0,use_confirmed_pm_id:ne,line_items:c.line_items,total_amount_atom:c.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e,customer_email:j[p.EMAIL],customer_zip_code:j[p.ZIP_CODE],customer_country:j[p.COUNTRY],promotion_code:j[p.PROMOTION_CODE],customer_first_name:j[p.FIRST_NAME],customer_last_name:j[p.LAST_NAME]};return{mode:"checkout",result:await Lt(a,de)}}}catch(T){throw Qe("Google Pay payment error",T),new Error((T==null?void 0:T.message)??"Unknown error")}}),Qa=()=>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)}),Xa=(r,e)=>{const t=e.token.paymentMethod.billingContact,n=e.billingContact,s=e.shippingContact,o={...r};return(t||n||s)&&(o[p.EMAIL]=o[p.EMAIL]||(t==null?void 0:t.emailAddress)||(n==null?void 0:n.emailAddress)||(s==null?void 0:s.emailAddress)||"op_unfilled@email.com",o[p.COUNTRY]=o[p.COUNTRY]||(t==null?void 0:t.countryCode)||(n==null?void 0:n.countryCode)||(s==null?void 0:s.countryCode)||"US",o[p.ZIP_CODE]=o[p.ZIP_CODE]||(t==null?void 0:t.postalCode)||(n==null?void 0:n.postalCode)||(s==null?void 0:s.postalCode)||"00000",o[p.FIRST_NAME]=o[p.FIRST_NAME]||(t==null?void 0:t.givenName)||(n==null?void 0:n.givenName)||(s==null?void 0:s.givenName)||"_OP_UNKNOWN",o[p.LAST_NAME]=o[p.LAST_NAME]||(t==null?void 0:t.familyName)||(n==null?void 0:n.familyName)||(s==null?void 0:s.familyName)||"_OP_UNKNOWN"),o},ec=i.object({data:i.object({messageHeaders:i.record(i.string(),i.any()),errors:i.array(i.any()),messageType:i.string(),messageBody:i.record(i.string(),i.any())}),origin:i.literal("https://applepay.cdn-apple.com")}),tc=r=>ec.safeParse(r).data,rc=r=>{const e=new AbortController;return window.addEventListener("message",t=>{var s;const n=tc(t);((s=n==null?void 0:n.data)==null?void 0:s.messageType)==="windowclosing"&&(r(),e.abort())},{signal:e.signal}),{cleanupCancelListener:()=>e.abort()}},{log__:zt}=F("awx-apple-pay");async function nc(r,e){try{const n=(await jt(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:e.nonCdeFormInputs[p.EMAIL],new_customer_first_name:e.nonCdeFormInputs[p.FIRST_NAME],new_customer_last_name:e.nonCdeFormInputs[p.LAST_NAME],processor_specific_metadata:{airwallex_payment_session:{validation_url:r.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).required_user_actions[0],s=n.payment_session,o=n.consent_id;if(!s)throw new Error("No session data received from payment flow");if(!o)throw new Error("No consent ID received from payment flow");return e.session.completeMerchantValidation(s),o}catch(t){throw e.session.abort(),t}}async function sc(r,e){var s,o;if(!r.redirect_url)throw new Error("No redirect URL found");zt("3DS Required, starting verification...",r);const{status:t}=await Vt({url:r.redirect_url,baseUrl:e.baseUrl});if(zt(`╰ 3DS verification completed [Status: ${t}]`),t===ee.CANCELLED)throw new Error("3DS verification cancelled");if(t===ee.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 zt("[2nd] Confirm payment flow response",n),(o=(s=n.payment_methods)==null?void 0:s[0])==null?void 0:o.id}async function oc(r,e,t){return{mode:"checkout",result:await Lt(t.connection,{secure_token:t.prefill.token,payment_input:{provider_type:t.checkoutPaymentMethod.provider},do_not_use_legacy_cc_flow:!0,use_confirmed_pm_id:r,line_items:t.prefill.line_items,total_amount_atom:t.prefill.amount_total_atom,cancel_at_end:!1,checkout_payment_method:t.checkoutPaymentMethod,customer_email:e[p.EMAIL],customer_zip_code:e[p.ZIP_CODE],customer_country:e[p.COUNTRY],promotion_code:e[p.PROMOTION_CODE]})}}async function ic(r,e,t){var n,s,o;try{const a=r.payment,c=Xa(e.nonCdeFormInputs,a),u=Je(c,e.formCallbacks.get.onValidationError,e.defaultFieldValues);await Yi(e.connection,{email:u[p.EMAIL],first_name:u[p.FIRST_NAME],last_name:u[p.LAST_NAME],zip_code:u[p.ZIP_CODE],country:u[p.COUNTRY],update_processor_customer:!0});const l=await Pe(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:t,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(a.token)}}}});zt("[1st] Confirm payment flow response",l);let d=(s=(n=l.payment_methods)==null?void 0:n[0])==null?void 0:s.id;const h=(o=l.required_user_actions)==null?void 0:o.find(m=>m.type==="airwallex_payment_consent");if(h!=null&&h.redirect_url&&h.consent_id&&h.their_pm_id&&(d=await sc(h,e)),!d)throw new Error("No PM ID found");const w={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(w),e.isSetupMode?{mode:"setup",result:{payment_method_id:d}}:await oc(d,u,e)}catch(a){const c={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(c),a}}const{log__:ye,err__:yr}=F("awx-apple-pay"),Tn=i.object({provider:i.literal("apple_pay"),processor_name:i.literal("airwallex"),metadata:i.object({processor_account_id:i.string(),processor_account_name:i.string()})}),ac=Zt(async({context:r,formCallbacks:e})=>{const t=Ke(r.checkoutPaymentMethods,Tn);if(!t)return{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};ye("Loading Apple Pay SDK...");try{await Qa(),ye("Apple Pay SDK loaded successfully")}catch(d){return yr("Failed to load Apple Pay SDK",d),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}}}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return ye("Apple Pay is not available on this device/browser"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};if(ye("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return ye("No active cards available for Apple Pay"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};const s=r.anyCdeConnection,o=await Ae(s),a=o.mode==="setup",c=await Dt(s,o.token,a,void 0),u=t.metadata;if(ye("processorAccount",u),!u.processor_account_id)throw new Error("No gateway merchant ID found in processor account");return{isAvailable:!0,isLoading:!1,startFlow:async d=>{var h;try{await te.airwallexApplePay.run({context:r,checkoutPaymentMethod:t,nonCdeFormInputs:Ge(r.formDiv),formCallbacks:e,customParams:{isSetupMode:a,prefill:o,initialPreview:((h=d==null?void 0:d.overridePaymentRequest)==null?void 0:h.amount)??c,overridePaymentRequest:d==null?void 0:d.overridePaymentRequest},initResult:void 0})}catch(w){yr("Apple Pay payment error",w),e.get.onCheckoutError((w==null?void 0:w.message)??"Unknown error")}}}}),cc=He(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:s})=>{var T,M;const o=Ke(r.checkoutPaymentMethods,Tn),{initialPreview:a,isSetupMode:c,prefill:u,overridePaymentRequest:l}=n,d=(((T=l==null?void 0:l.amount)==null?void 0:T.currency)??a.currency??"USD").toUpperCase(),w=((((M=l==null?void 0:l.amount)==null?void 0:M.amountAtom)??a.amountAtom??0)/100).toFixed(2),m={label:(l==null?void 0:l.label)??"Total",type:l!=null&&l.pending?"pending":"final",amount:w},g={countryCode:"US",currencyCode:d,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:m,...(l==null?void 0:l.applePayPaymentRequest)??{}};ye("Payment Request",g);const b=new ApplePaySession(3,g);ye("ApplePaySession",b);const A={session:b,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:o.metadata,prefill:u,isSetupMode:c,baseUrl:r.baseUrl,formCallbacks:s,defaultFieldValues:n==null?void 0:n.defaultFieldValues};let O;return new Promise((j,W)=>{const Ie=()=>{ye("Payment cancelled by user"),W(new Error("Payment cancelled by user"))},{cleanupCancelListener:ue}=rc(Ie);b.oncancel=Ie,b.onvalidatemerchant=async we=>{try{O=await nc(we,A)}catch(ne){W(ne)}},b.onpaymentmethodselected=()=>{const we={newTotal:{...m}};b.completePaymentMethodSelection(we)},b.onpaymentauthorized=async we=>{try{const ne=await ic(we,A,O);ue(),j(ne)}catch(ne){W(ne)}},b.begin()}).catch(j=>{throw yr("Apple Pay payment error",j),j})}),_r=(r,e,t)=>{const n=r.filter(s=>{const o=t===void 0?!0:s.processor_name===t,a=s.provider===e;return o&&a});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]},te={commonCC:{init:async()=>{},run:Ra},stripePR:{init:Ua,run:$a},stripeLink:{init:da,run:fa},pockytPaypal:{run:Ga},airwallexGooglePay:{init:Ka,run:Ja},airwallexApplePay:{init:ac,run:cc}};var gr=function(r,e){return gr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])},gr(r,e)};function Te(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");gr(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function lc(r,e,t,n){function s(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function c(d){try{l(n.next(d))}catch(h){a(h)}}function u(d){try{l(n.throw(d))}catch(h){a(h)}}function l(d){d.done?o(d.value):s(d.value).then(c,u)}l((n=n.apply(r,e||[])).next())})}function In(r,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,s,o,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=c(0),a.throw=c(1),a.return=c(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function c(l){return function(d){return u([l,d])}}function u(l){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(t=0)),t;)try{if(n=1,s&&(o=l[0]&2?s.return:l[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,l[1])).done)return o;switch(s=0,o&&(l=[l[0]&2,o.value]),l[0]){case 0:case 1:o=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,s=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!o||l[1]>o[0]&&l[1]<o[3])){t.label=l[1];break}if(l[0]===6&&t.label<o[1]){t.label=o[1],o=l;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(l);break}o[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(d){l=[6,d],s=0}finally{n=o=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Xe(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 Bt(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(c){a={error:c}}finally{try{s&&!s.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o}function qt(r,e,t){if(t||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return r.concat(o||Array.prototype.slice.call(e))}function et(r){return this instanceof et?(this.v=r,this):new et(r)}function uc(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),s,o=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",a),s[Symbol.asyncIterator]=function(){return this},s;function a(m){return function(g){return Promise.resolve(g).then(m,h)}}function c(m,g){n[m]&&(s[m]=function(b){return new Promise(function(A,O){o.push([m,b,A,O])>1||u(m,b)})},g&&(s[m]=g(s[m])))}function u(m,g){try{l(n[m](g))}catch(b){w(o[0][3],b)}}function l(m){m.value instanceof et?Promise.resolve(m.value.v).then(d,h):w(o[0][2],m)}function d(m){u("next",m)}function h(m){u("throw",m)}function w(m,g){m(g),o.shift(),o.length&&u(o[0][0],o[0][1])}}function dc(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 Xe=="function"?Xe(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(o){t[o]=r[o]&&function(a){return new Promise(function(c,u){a=r[o](a),s(c,u,a.done,a.value)})}}function s(o,a,c,u){Promise.resolve(u).then(function(l){o({value:l,done:c})},a)}}typeof SuppressedError=="function"&&SuppressedError;function $(r){return typeof r=="function"}function Gt(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 vr=Gt(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 s=n.querySelector("#three-ds-iframe"),o=n.querySelector(".cancel-button");return document.body.appendChild(t),{host:t,iframe:s,cancelButton:o}};function _a(r,e,t){const n=async()=>{try{const o=await Gi(r,t);o&&(clearInterval(s),e(o))}catch{}};n();const s=setInterval(n,ln);return s}function ga({elements:r,pollingInterval:e,resolve:t}){const n=()=>{clearInterval(e),r.host.remove(),t({status:te.CANCELLED})};return r.cancelButton.addEventListener("click",n),()=>{r.cancelButton.removeEventListener("click",n)}}async function Zt(r){const{url:e,baseUrl:t}=r,n=ya(e);return new Promise(s=>{const o=u=>{setTimeout(()=>{n.host.remove()},1e3),s(u),c==null||c()},a=_a(n.iframe,o,new URL(t).origin),c=ga({elements:n,pollingInterval:a,resolve:s})})}const wn=async r=>{const e=await Zt(r);if(e.status===te.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===te.FAILURE)throw new Error("3DS verification failed");return e.status!==te.SUCCESS&&cr(e.status),{href:e.href}},va=(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},wa=async(r,e,t,n)=>{const{err__:s}=U("popup-verify");return new Promise((o,a)=>{const c=va(r,n),u=setInterval(async()=>{try{const l=await Vi(e,t);if(l.present)clearInterval(u),c.close(),o({href:l.href});else if(c.closed)throw new Error(`${r} payment cancelled`)}catch(l){s(ye(l)),clearInterval(u),a(ye(l))}},1e3)})},{log__:ba,err__:bn}=U("pockyt-cc"),ka=i.object({"op-pockyt-3ds-url":i.string(),"op-pockyt-txn-no":i.string(),"op-pockyt-ref-no":i.string()}),Ea=r=>{const e=ka.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 bn(n),new Error(t)}return e.data},kn=r=>{try{const e=new URL(r??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return ba(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const t="Error verifying 3DS verification result.";throw bn(t,`Resulting URL: ${r}.
21
+ Error: ${ye(e)}`),new Error(t)}},Sa=(r,e)=>new URL(r).searchParams.get(e),Ca=r=>(r==null?void 0:r["op-pockyt-3ds-url"])!==void 0,xa=async(r,e)=>{const t=Ea(e),n=await wn({url:t["op-pockyt-3ds-url"],baseUrl:r});return{existing_cc:{vault_id:kn(n.href??""),transaction_no:t["op-pockyt-txn-no"],reference_no:t["op-pockyt-ref-no"]}}},{log__:Aa,err__:hr}=U("airwallex-cc"),Pa=i.object({"op-airwallex-3ds-url":i.string(),"op-airwallex-initial-intent-id":i.string(),"op-airwallex-consent-id":i.string()}),Ta=r=>{const e=Pa.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 hr(n),new Error(t)}return e.data},Ia=r=>(r==null?void 0:r["op-airwallex-3ds-url"])!==void 0,Oa=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 Aa(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const t="Error verifying Airwallex 3DS verification result.";throw hr(t,`Resulting URL: ${r}.
22
+ Error: ${ye(e)}`),new Error(t)}},Ra=async(r,e)=>{const t=Ta(e),n=await wn({url:t["op-airwallex-3ds-url"],baseUrl:r}),s=Oa(n.href??""),o=t["op-airwallex-initial-intent-id"];if(o!==s){const c="Unable to process your credit card. Please contact support for assistance.",u=`Intent ID from callback (${s}) does not match the initial intent ID (${o}).`;throw hr(u),new Error(c)}return{existing_cc:{initial_intent_id:s,consent_id:t["op-airwallex-consent-id"]}}},{log__:j,err__:En}=U("common-cc"),{log__:Sn}=U("stripe-cc");i.array(i.object({our_existing_pm_id:i.string()})).length(1);const Na=He(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{var l;j("├ Running common CC flow...",{checkoutPaymentMethod:e});const o=r.anyCdeConnection,a=await Pe(o);j(`├ Validating non-CDE form fields [Mode: ${a.mode}]`);const c=Je(t,n.get.onValidationError),u={session_id:r.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{}};try{j(`├ Tokenizing card info in CDE [Session: ${r.elementsSessionId}]`);const d=await Bi(s.currentCdeConnections,{session_id:r.elementsSessionId});if(aa(d,n.get.onValidationError),a.mode==="setup"){j(`├ Setting up payment method in CDE [Token: ${a.token}]`);const h=await qi(o,u);return j(`╰ Setup completed successfully [PM ID: ${h.payment_method_id}]`),{mode:"setup",result:h}}else{j(`├ Initial checkout flow. Checking out card info in CDE [Session: ${r.elementsSessionId}]`);const h=await cn(o,u);return j("╰ Checkout completed successfully."),{mode:"checkout",result:h}}}catch(d){if(d instanceof an&&d.originalErrorMessage.includes("3DS_REQUIRED")){j("├ Card requires 3DS, starting non-legacy payment flow"),j("Received 3DS error response headers:",d.response.headers);const h=Ca(d.response.headers);if(h){j("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const A=await xa(r.baseUrl,d.response.headers);u.extra_metadata.pockyt=A}if(Ia(d.response.headers)){j("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const A=await Ra(r.baseUrl,d.response.headers);u.extra_metadata.airwallex=A}const m=await $i(o,u);j("├ Payment flow result:",m);const g=((l=d.response.headers)==null?void 0:l["op-should-use-new-flow"])!=="true";h?j("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):g?(j("├ Using stripe 3DS flow"),await La(m)):(j("├ Using common 3DS flow"),await Da(m,r.baseUrl));const k=m.cc_pm_id;if(a.mode==="setup"){j(`├ Confirming payment flow [cc_pm_id: ${k}]`);const A=await Te(o,{secure_token:a.token,existing_cc_pm_id:k});j("├ Confirm payment flow result received Result:",A);const N=pr(A);return j(`╰ Setup completed successfully [PM ID: ${N.payment_method_id}]`),{mode:"setup",result:N}}else{j(`├ Checking out after 3DS flow [Flow: ${g?"legacy":"new"}]`);const A=await cn(o,{...u,existing_cc_pm_id:k,do_not_use_legacy_cc_flow:g});return j("╰ Checkout completed successfully."),{mode:"checkout",result:A}}}throw En("╰ Error checking out card info in CDE"),En(d),d}}),Ma=r=>{const e=r.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Oo.parse(e)},ja=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 Ao.parse(e)},Da=async(r,e)=>{const t=ja(r);if(t.type==="airwallex_payment_consent"&&t.redirect_url==="3DS_COMPLETE"){j("├ Airwallex 3DS flow completed successfully");return}j(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const{status:n}=await Zt({url:t.redirect_url,baseUrl:e});if(j(`╰ 3DS verification completed [Status: ${n}]`),n===te.CANCELLED)throw new Error("3DS verification cancelled");if(n===te.FAILURE)throw new Error("3DS verification failed")},La=async r=>{const e=Ma(r);Sn(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Fo(e),Sn("╰ Stripe 3DS flow completed successfully")},{log__:q,err__:Fa}=U("stripe-pr"),Ua=i.object({provider:i.union([i.literal("apple_pay"),i.literal("google_pay")]),processor_name:i.literal("stripe"),metadata:i.object({stripe_pk:i.string()})}),$a=$t(async({context:r})=>{q("Checking if there are any CPMs for Stripe PR...");const e=Ke(r.checkoutPaymentMethods,Ua);q("Initializing Stripe PR flow...");const t=r.anyCdeConnection,n=await Pe(t),s=n.mode==="setup";q("Getting initial preview amount");const o=await jt(t,n.token,s,void 0),a=await jo(e.metadata.stripe_pk,o.amountAtom,o.currency,s);q("Checking if can make payment");const c=await a.canMakePayment();return c===null?(Fa("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"}):(q("Stripe PR flow initialized successfully. Can make payment",c),{isAvailable:!0,pr:a,availableProviders:{applePay:c.applePay,googlePay:c.googlePay}})}),Za=He(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s,initResult:o})=>{if(q("Running Stripe PR flow..."),s.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${s.provider}, got ${e.provider}`);const a=r.anyCdeConnection,c=o.pr;if(s!=null&&s.overridePaymentRequest){const g=s.overridePaymentRequest;q("Overriding PR amount with",g),za(c,g.amount,g.pending,g.stripeApplePay)}q("Showing PR dialog..."),c.show();const u=await Do(c);q("Stripe PM added event:",u),q("Merging PM fields with form fields...");const l=Va(t,u),d=Je(l,n.get.onValidationError);q("PR dialog finished. Starting payment flow...",d);const h=await Zi(a,{fields:d,checkoutPaymentMethod:e}),w=Ba(h);q("Confirming PR with Stripe..."),await Lo(w,u);const m=await Pe(a);if(m.mode==="setup"){q("Confirming payment flow for setup...");const g=await Te(a,{secure_token:m.token});return{mode:"setup",result:pr(g)}}else{q("Performing checkout...");const g={secure_token:m.token,payment_input:{provider_type:e.provider},customer_first_name:d[p.FIRST_NAME],customer_last_name:d[p.LAST_NAME],customer_email:d[p.EMAIL],customer_zip_code:d[p.ZIP_CODE],customer_country:d[p.COUNTRY],promotion_code:d[p.PROMOTION_CODE],line_items:m.line_items,total_amount_atom:m.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Dt(a,g)}}}),Va=(r,e)=>{var u,l,d,h;const t={...r},[n,...s]=((l=(u=e.payerName)==null?void 0:u.trim())==null?void 0:l.split(/\s+/))??[],o=s.join(" ")||void 0,a=(h=(d=e.paymentMethod)==null?void 0:d.billing_details)==null?void 0:h.address,c=e.shippingAddress;return t[p.FIRST_NAME]=t[p.FIRST_NAME]||n||"_OP_UNKNOWN",t[p.LAST_NAME]=t[p.LAST_NAME]||o||"_OP_UNKNOWN",t[p.EMAIL]=t[p.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[p.ZIP_CODE]=t[p.ZIP_CODE]||(a==null?void 0:a.postal_code)||(c==null?void 0:c.postalCode)||"00000",t[p.COUNTRY]=t[p.COUNTRY]||(a==null?void 0:a.country)||(c==null?void 0:c.country)||"US",q("Final form inputs:",t),t},za=(r,e,t,n)=>{r.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency,applePay:n})},Ba=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 Ro.parse(r.required_user_actions[0])},{log__:de,err__:Cn}=U("pockyt-paypal"),qa=i.object({processor_name:i.literal("pockyt"),provider:i.literal("paypal")});i.array(i.object({paypal_iframe_url:i.string(),verify_token:i.string()})).length(1);const Ga=He(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{var se,H;de("Running Pockyt Paypal flow...");const o=r.anyCdeConnection,a=await Pe(o);de("Verifying CPM...");const c=qa.parse(e);de("├ Validating non-CDE form fields");const u=s==null?void 0:s.settings,l=Je(t,n.get.onValidationError,u==null?void 0:u.defaultFieldValues),d=ia(l);de(`Starting payment flow... Mode: ${a.mode}`);const h=Gr(),w=a.mode!=="setup",m={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:w,pay_first_flow_cart_info:w?{line_items:a.line_items,displayed_total_amount_atom:a.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((se=s==null?void 0:s.settings)!=null&&se.useRedirectFlow),frontend_token_for_redirect_flow:h},...d},g=new URL("/app/pre-action/start/",r.baseUrl).toString(),k=btoa(JSON.stringify(m)),A=new URLSearchParams({st:a.token,r:k}),N=`${g}?${A.toString()}`;if((H=s==null?void 0:s.settings)!=null&&H.useRedirectFlow)throw de("Starting redirect mode for PayPal..."),window.location.href=N,await zr(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");de("Starting popup mode for PayPal..."),de("Opening paypal iframe...");const T=await wa("PayPal",o,h,N);de("Paypal flow result",T);const I=kn(T.href),O=Sa(T.href,"catt");if(!O)throw Cn("Checkout attempt ID not found in redirect URL:",T.href),new Error("Checkout attempt ID not found in redirect URL");de(`Confirming payment flow using vault ID ${I}`);const L=await Te(o,{secure_token:a.token,their_pm_id:I,checkout_attempt_id:w?O:void 0});if(de("Confirm payment flow result",L),a.mode==="setup")return{mode:"setup",result:{payment_method_id:L.payment_methods[0].id}};if(!L.pay_first_success_response)throw Cn("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}}),xn=({gateway:r,gatewayMerchantId:e,merchantName:t,merchantId:n,initialPreview:s,overridePaymentRequest:o})=>{var d,h;const a=((d=o==null?void 0:o.amount)==null?void 0:d.amountAtom)??(s==null?void 0:s.amountAtom)??0,c=Math.max(a/100,0),u=(((h=o==null?void 0:o.amount)==null?void 0:h.currency)??(s==null?void 0:s.currency)??"USD").toUpperCase(),l={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:o!=null&&o.pending?"ESTIMATED":"FINAL",totalPrice:c.toFixed(2)}};return o!=null&&o.googlePayPaymentRequest?{...l,...o.googlePayPaymentRequest}:l},Ya=()=>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)}),Wa=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");return e?Vr.parse(e):null},Ha=(r,e)=>{var s,o,a,c;const t={...r},n=(o=(s=e.paymentMethodData)==null?void 0:s.info)==null?void 0:o.billingAddress;if(n){const[u,...l]=((c=(a=n.name)==null?void 0:a.trim())==null?void 0:c.split(/\s+/))??[],d=l.join(" ")||void 0;t[p.EMAIL]=t[p.EMAIL]||e.email||"op_unfilled@getopenpay.com",t[p.COUNTRY]=t[p.COUNTRY]||n.countryCode||"US",t[p.ADDRESS]=t[p.ADDRESS]||n.address1||"",t[p.CITY]=t[p.CITY]||n.locality||"",t[p.ZIP_CODE]=t[p.ZIP_CODE]||n.postalCode||"00000",t[p.STATE]=t[p.STATE]||n.administrativeArea||"",t[p.FIRST_NAME]=t[p.FIRST_NAME]||u||"_OP_UNKNOWN",t[p.LAST_NAME]=t[p.LAST_NAME]||d||"_OP_UNKNOWN"}return t},{log__:K,err__:Qe}=U("awx-google-pay");let mr=null;const An=r=>r===Fe||r===window.location.origin?"PRODUCTION":"TEST",Pn=(r,e)=>{const t=An(r);return mr===null&&(mr=new window.google.payments.api.PaymentsClient({environment:t,merchantInfo:e.merchantInfo})),mr},Tn=i.object({provider:i.literal("google_pay"),processor_name:i.literal("airwallex"),metadata:i.object({processor_account_id:i.string(),processor_account_name:i.string(),google_pay_merchant_id:i.string().nullish()})}),Ka=$t(async({context:r,formCallbacks:e})=>{var a,c;const t=Ke(r.checkoutPaymentMethods,Tn);if(!t)return{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};K("Google Pay CPM",t);const n=t.metadata;if(!n.processor_account_id)return Qe("No gateway merchant ID found in processor account"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};if(K("Loading Google Pay SDK..."),await Ya(),!((c=(a=window.google)==null?void 0:a.payments)!=null&&c.api))return Qe("Google Pay SDK not loaded properly"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};if(An(r.baseUrl)==="PRODUCTION"&&!n.google_pay_merchant_id)return Qe("Google Pay merchant ID is required for production environment"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};K("Google Pay SDK loaded",window.google.payments);try{const u=xn({gateway:"airwallex",gatewayMerchantId:n.processor_account_id,merchantName:n.processor_account_name,merchantId:n.google_pay_merchant_id??"",initialPreview:void 0}),{result:l}=await Pn(r.baseUrl,u).isReadyToPay(u);if(!l)return K("Google Pay is not available for this user"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}}}catch(u){return Qe("Error checking Google Pay availability",u),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}}}return{isAvailable:!0,isLoading:!1,startFlow:async u=>{try{re.airwallexGooglePay.run({context:r,checkoutPaymentMethod:t,nonCdeFormInputs:Ge(r.formDiv),formCallbacks:e,initResult:void 0,customParams:u??{}})}catch(l){Qe("Google Pay payment error",l),e.get.onCheckoutError((l==null?void 0:l.message)??"Unknown error")}}}}),Ja=He(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{var h,w,m,g,k,A,N;K("Starting Google Pay flow...");const o=Ke(r.checkoutPaymentMethods,Tn),a=r.anyCdeConnection,c=await Pe(a),u=o.metadata;if(!u.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const l=xn({gateway:"airwallex",gatewayMerchantId:u.processor_account_id,merchantName:u.processor_account_name,merchantId:u.google_pay_merchant_id??"",initialPreview:await jt(a,c.token,c.mode==="setup",void 0),overridePaymentRequest:s==null?void 0:s.overridePaymentRequest}),d=Pn(r.baseUrl,l);try{const T=await d.loadPaymentData(l);K("Google Pay Payment data",T);const I=Ha(t,T),O=Je(I,n.get.onValidationError,s==null?void 0:s.defaultFieldValues),L=(w=(h=T.paymentMethodData)==null?void 0:h.tokenizationData)==null?void 0:w.token;if(!L)throw new Error("No payment token received from Google Pay");const se=await ar(a,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:O[p.EMAIL],new_customer_first_name:O[p.FIRST_NAME],new_customer_last_name:O[p.LAST_NAME],new_customer_address:{postal_code:O[p.ZIP_CODE],country_code:O[p.COUNTRY]}}),H=Wa(se);K("Start flow next actions",H);const be=await Te(a,{secure_token:c.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:H==null?void 0:H.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:L}}}});K("[1st] Confirm payment flow response",be);let oe=(g=(m=be.payment_methods)==null?void 0:m[0])==null?void 0:g.id;const Le=(k=be.required_user_actions)==null?void 0:k.find(pe=>pe.type==="airwallex_payment_consent");if(Le&&Le.redirect_url){K("3DS Required, starting verification...",Le);const{status:pe}=await Zt({url:Le.redirect_url,baseUrl:r.baseUrl});if(K(`╰ 3DS verification completed [Status: ${pe}]`),pe===te.CANCELLED)throw new Error("3DS verification cancelled");if(pe===te.FAILURE)throw new Error("3DS verification failed")}if(Le&&!oe){const pe=await Te(a,{secure_token:c.token,their_pm_id:Le.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Le.consent_id}});K("[2nd] Confirm payment flow response",pe),oe=(N=(A=pe.payment_methods)==null?void 0:A[0])==null?void 0:N.id}if(!oe)throw new Error("No PM ID found");if(c.mode==="setup")return{mode:"setup",result:{payment_method_id:oe}};{K("Starting one-time payment flow...");const pe={secure_token:c.token,payment_input:{provider_type:e.provider},do_not_use_legacy_cc_flow:!0,use_confirmed_pm_id:oe,line_items:c.line_items,total_amount_atom:c.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e,customer_email:O[p.EMAIL],customer_zip_code:O[p.ZIP_CODE],customer_country:O[p.COUNTRY],promotion_code:O[p.PROMOTION_CODE],customer_first_name:O[p.FIRST_NAME],customer_last_name:O[p.LAST_NAME]};return{mode:"checkout",result:await Dt(a,pe)}}}catch(T){throw Qe("Google Pay payment error",T),new Error((T==null?void 0:T.message)??"Unknown error")}}),Qa=()=>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)}),Xa=(r,e)=>{const t=e.token.paymentMethod.billingContact,n=e.billingContact,s=e.shippingContact,o={...r};return(t||n||s)&&(o[p.EMAIL]=o[p.EMAIL]||(t==null?void 0:t.emailAddress)||(n==null?void 0:n.emailAddress)||(s==null?void 0:s.emailAddress)||"op_unfilled@email.com",o[p.COUNTRY]=o[p.COUNTRY]||(t==null?void 0:t.countryCode)||(n==null?void 0:n.countryCode)||(s==null?void 0:s.countryCode)||"US",o[p.ZIP_CODE]=o[p.ZIP_CODE]||(t==null?void 0:t.postalCode)||(n==null?void 0:n.postalCode)||(s==null?void 0:s.postalCode)||"00000",o[p.FIRST_NAME]=o[p.FIRST_NAME]||(t==null?void 0:t.givenName)||(n==null?void 0:n.givenName)||(s==null?void 0:s.givenName)||"_OP_UNKNOWN",o[p.LAST_NAME]=o[p.LAST_NAME]||(t==null?void 0:t.familyName)||(n==null?void 0:n.familyName)||(s==null?void 0:s.familyName)||"_OP_UNKNOWN"),o},ec=i.object({data:i.object({messageHeaders:i.record(i.string(),i.any()),errors:i.array(i.any()),messageType:i.string(),messageBody:i.record(i.string(),i.any())}),origin:i.literal("https://applepay.cdn-apple.com")}),tc=r=>ec.safeParse(r).data,rc=r=>{const e=new AbortController;return window.addEventListener("message",t=>{var s;const n=tc(t);((s=n==null?void 0:n.data)==null?void 0:s.messageType)==="windowclosing"&&(r(),e.abort())},{signal:e.signal}),{cleanupCancelListener:()=>e.abort()}},{log__:Vt}=U("awx-apple-pay");async function nc(r,e){try{const n=(await ar(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:e.nonCdeFormInputs[p.EMAIL],new_customer_first_name:e.nonCdeFormInputs[p.FIRST_NAME],new_customer_last_name:e.nonCdeFormInputs[p.LAST_NAME],processor_specific_metadata:{airwallex_payment_session:{validation_url:r.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).required_user_actions[0],s=n.payment_session,o=n.consent_id;if(!s)throw new Error("No session data received from payment flow");if(!o)throw new Error("No consent ID received from payment flow");return e.session.completeMerchantValidation(s),o}catch(t){throw e.session.abort(),t}}async function sc(r,e){var s,o;if(!r.redirect_url)throw new Error("No redirect URL found");Vt("3DS Required, starting verification...",r);const{status:t}=await Zt({url:r.redirect_url,baseUrl:e.baseUrl});if(Vt(`╰ 3DS verification completed [Status: ${t}]`),t===te.CANCELLED)throw new Error("3DS verification cancelled");if(t===te.FAILURE)throw new Error("3DS verification failed");const n=await Te(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 Vt("[2nd] Confirm payment flow response",n),(o=(s=n.payment_methods)==null?void 0:s[0])==null?void 0:o.id}async function oc(r,e,t){return{mode:"checkout",result:await Dt(t.connection,{secure_token:t.prefill.token,payment_input:{provider_type:t.checkoutPaymentMethod.provider},do_not_use_legacy_cc_flow:!0,use_confirmed_pm_id:r,line_items:t.prefill.line_items,total_amount_atom:t.prefill.amount_total_atom,cancel_at_end:!1,checkout_payment_method:t.checkoutPaymentMethod,customer_email:e[p.EMAIL],customer_zip_code:e[p.ZIP_CODE],customer_country:e[p.COUNTRY],promotion_code:e[p.PROMOTION_CODE]})}}async function ic(r,e,t){var n,s,o;try{const a=r.payment,c=Xa(e.nonCdeFormInputs,a),u=Je(c,e.formCallbacks.get.onValidationError,e.defaultFieldValues);await Yi(e.connection,{email:u[p.EMAIL],first_name:u[p.FIRST_NAME],last_name:u[p.LAST_NAME],zip_code:u[p.ZIP_CODE],country:u[p.COUNTRY],update_processor_customer:!0});const l=await Te(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:t,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(a.token)}}}});Vt("[1st] Confirm payment flow response",l);let d=(s=(n=l.payment_methods)==null?void 0:n[0])==null?void 0:s.id;const h=(o=l.required_user_actions)==null?void 0:o.find(m=>m.type==="airwallex_payment_consent");if(h!=null&&h.redirect_url&&h.consent_id&&h.their_pm_id&&(d=await sc(h,e)),!d)throw new Error("No PM ID found");const w={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(w),e.isSetupMode?{mode:"setup",result:{payment_method_id:d}}:await oc(d,u,e)}catch(a){const c={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(c),a}}const{log__:_e,err__:yr}=U("awx-apple-pay"),In=i.object({provider:i.literal("apple_pay"),processor_name:i.literal("airwallex"),metadata:i.object({processor_account_id:i.string(),processor_account_name:i.string()})}),ac=$t(async({context:r,formCallbacks:e})=>{const t=Ke(r.checkoutPaymentMethods,In);if(!t)return{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};_e("Loading Apple Pay SDK...");try{await Qa(),_e("Apple Pay SDK loaded successfully")}catch(d){return yr("Failed to load Apple Pay SDK",d),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}}}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return _e("Apple Pay is not available on this device/browser"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};if(_e("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return _e("No active cards available for Apple Pay"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};const s=r.anyCdeConnection,o=await Pe(s),a=o.mode==="setup",c=await jt(s,o.token,a,void 0),u=t.metadata;if(_e("processorAccount",u),!u.processor_account_id)throw new Error("No gateway merchant ID found in processor account");return{isAvailable:!0,isLoading:!1,startFlow:async d=>{var h;try{await re.airwallexApplePay.run({context:r,checkoutPaymentMethod:t,nonCdeFormInputs:Ge(r.formDiv),formCallbacks:e,customParams:{isSetupMode:a,prefill:o,initialPreview:((h=d==null?void 0:d.overridePaymentRequest)==null?void 0:h.amount)??c,overridePaymentRequest:d==null?void 0:d.overridePaymentRequest},initResult:void 0})}catch(w){yr("Apple Pay payment error",w),e.get.onCheckoutError((w==null?void 0:w.message)??"Unknown error")}}}}),cc=He(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:s})=>{var T,I;const o=Ke(r.checkoutPaymentMethods,In),{initialPreview:a,isSetupMode:c,prefill:u,overridePaymentRequest:l}=n,d=(((T=l==null?void 0:l.amount)==null?void 0:T.currency)??a.currency??"USD").toUpperCase(),w=((((I=l==null?void 0:l.amount)==null?void 0:I.amountAtom)??a.amountAtom??0)/100).toFixed(2),m={label:(l==null?void 0:l.label)??"Total",type:l!=null&&l.pending?"pending":"final",amount:w},g={countryCode:"US",currencyCode:d,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:m,...(l==null?void 0:l.applePayPaymentRequest)??{}};_e("Payment Request",g);const k=new ApplePaySession(3,g);_e("ApplePaySession",k);const A={session:k,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:o.metadata,prefill:u,isSetupMode:c,baseUrl:r.baseUrl,formCallbacks:s,defaultFieldValues:n==null?void 0:n.defaultFieldValues};let N;return new Promise((O,L)=>{const se=()=>{_e("Payment cancelled by user"),L(new Error("Payment cancelled by user"))},{cleanupCancelListener:H}=rc(se);k.oncancel=se,k.onvalidatemerchant=async be=>{try{N=await nc(be,A)}catch(oe){L(oe)}},k.onpaymentmethodselected=()=>{const be={newTotal:{...m}};k.completePaymentMethodSelection(be)},k.onpaymentauthorized=async be=>{try{const oe=await ic(be,A,N);H(),O(oe)}catch(oe){L(oe)}},k.begin()}).catch(O=>{throw yr("Apple Pay payment error",O),O})}),_r=(r,e,t)=>{const n=r.filter(s=>{const o=t===void 0?!0:s.processor_name===t,a=s.provider===e;return o&&a});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]},re={commonCC:{init:async()=>{},run:Na},stripePR:{init:$a,run:Za},stripeLink:{init:da,run:fa},pockytPaypal:{run:Ga},airwallexGooglePay:{init:Ka,run:Ja},airwallexApplePay:{init:ac,run:cc}};var gr=function(r,e){return gr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])},gr(r,e)};function Ie(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");gr(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function lc(r,e,t,n){function s(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function c(d){try{l(n.next(d))}catch(h){a(h)}}function u(d){try{l(n.throw(d))}catch(h){a(h)}}function l(d){d.done?o(d.value):s(d.value).then(c,u)}l((n=n.apply(r,e||[])).next())})}function On(r,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,s,o,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=c(0),a.throw=c(1),a.return=c(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function c(l){return function(d){return u([l,d])}}function u(l){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(t=0)),t;)try{if(n=1,s&&(o=l[0]&2?s.return:l[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,l[1])).done)return o;switch(s=0,o&&(l=[l[0]&2,o.value]),l[0]){case 0:case 1:o=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,s=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!o||l[1]>o[0]&&l[1]<o[3])){t.label=l[1];break}if(l[0]===6&&t.label<o[1]){t.label=o[1],o=l;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(l);break}o[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(d){l=[6,d],s=0}finally{n=o=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Xe(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 zt(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(c){a={error:c}}finally{try{s&&!s.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o}function Bt(r,e,t){if(t||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return r.concat(o||Array.prototype.slice.call(e))}function et(r){return this instanceof et?(this.v=r,this):new et(r)}function uc(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),s,o=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",a),s[Symbol.asyncIterator]=function(){return this},s;function a(m){return function(g){return Promise.resolve(g).then(m,h)}}function c(m,g){n[m]&&(s[m]=function(k){return new Promise(function(A,N){o.push([m,k,A,N])>1||u(m,k)})},g&&(s[m]=g(s[m])))}function u(m,g){try{l(n[m](g))}catch(k){w(o[0][3],k)}}function l(m){m.value instanceof et?Promise.resolve(m.value.v).then(d,h):w(o[0][2],m)}function d(m){u("next",m)}function h(m){u("throw",m)}function w(m,g){m(g),o.shift(),o.length&&u(o[0][0],o[0][1])}}function dc(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 Xe=="function"?Xe(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(o){t[o]=r[o]&&function(a){return new Promise(function(c,u){a=r[o](a),s(c,u,a.done,a.value)})}}function s(o,a,c,u){Promise.resolve(u).then(function(l){o({value:l,done:c})},a)}}typeof SuppressedError=="function"&&SuppressedError;function Z(r){return typeof r=="function"}function qt(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 vr=qt(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
24
24
  `+t.map(function(n,s){return s+1+") "+n.toString()}).join(`
25
- `):"",this.name="UnsubscriptionError",this.errors=t}});function Yt(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var Et=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,s,o;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var c=Xe(a),u=c.next();!u.done;u=c.next()){var l=u.value;l.remove(this)}}catch(b){e={error:b}}finally{try{u&&!u.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else a.remove(this);var d=this.initialTeardown;if($(d))try{d()}catch(b){o=b instanceof vr?b.errors:[b]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var w=Xe(h),m=w.next();!m.done;m=w.next()){var g=m.value;try{Nn(g)}catch(b){o=o??[],b instanceof vr?o=qt(qt([],Bt(o)),Bt(b.errors)):o.push(b)}}}catch(b){n={error:b}}finally{try{m&&!m.done&&(s=w.return)&&s.call(w)}finally{if(n)throw n.error}}}if(o)throw new vr(o)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Nn(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)&&Yt(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&Yt(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),On=Et.EMPTY;function Rn(r){return r instanceof Et||r&&"closed"in r&&$(r.remove)&&$(r.add)&&$(r.unsubscribe)}function Nn(r){$(r)?r():r.unsubscribe()}var Mn={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},jn={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,qt([r,e],Bt(t)))},clearTimeout:function(r){var e=jn.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function Dn(r){jn.setTimeout(function(){throw r})}function Ln(){}function Wt(r){r()}var wr=function(r){Te(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,Rn(t)&&t.add(n)):n.destination=mc,n}return e.create=function(t,n,s){return new kr(t,n,s)},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}(Et),fc=Function.prototype.bind;function br(r,e){return fc.call(r,e)}var pc=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){Ht(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){Ht(n)}else Ht(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Ht(t)}},r}(),kr=function(r){Te(e,r);function e(t,n,s){var o=r.call(this)||this,a;if($(t)||!t)a={next:t??void 0,error:n??void 0,complete:s??void 0};else{var c;o&&Mn.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return o.unsubscribe()},a={next:t.next&&br(t.next,c),error:t.error&&br(t.error,c),complete:t.complete&&br(t.complete,c)}):a=t}return o.destination=new pc(a),o}return e}(wr);function Ht(r){Dn(r)}function hc(r){throw r}var mc={closed:!0,next:Ln,error:hc,complete:Ln},Er=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function yc(r){return r}function _c(r){return r.length===0?yc:r.length===1?r[0]:function(t){return r.reduce(function(n,s){return s(n)},t)}}var _e=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 s=this,o=vc(e)?e:new kr(e,t,n);return Wt(function(){var a=s,c=a.operator,u=a.source;o.add(c?c.call(o,u):u?s._subscribe(o):s._trySubscribe(o))}),o},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=Fn(t),new t(function(s,o){var a=new kr({next:function(c){try{e(c)}catch(u){o(u),a.unsubscribe()}},error:o,complete:s});n.subscribe(a)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Er]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return _c(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=Fn(e),new e(function(n,s){var o;t.subscribe(function(a){return o=a},function(a){return s(a)},function(){return n(o)})})},r.create=function(e){return new r(e)},r}();function Fn(r){var e;return(e=r??Mn.Promise)!==null&&e!==void 0?e:Promise}function gc(r){return r&&$(r.next)&&$(r.error)&&$(r.complete)}function vc(r){return r&&r instanceof wr||gc(r)&&Rn(r)}function wc(r){return $(r==null?void 0:r.lift)}function bc(r){return function(e){if(wc(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 kc(r,e,t,n,s){return new Ec(r,e,t,n,s)}var Ec=function(r){Te(e,r);function e(t,n,s,o,a,c){var u=r.call(this,t)||this;return u.onFinalize=a,u.shouldUnsubscribe=c,u._next=n?function(l){try{n(l)}catch(d){t.error(d)}}:r.prototype._next,u._error=o?function(l){try{o(l)}catch(d){t.error(d)}finally{this.unsubscribe()}}:r.prototype._error,u._complete=s?function(){try{s()}catch(l){t.error(l)}finally{this.unsubscribe()}}:r.prototype._complete,u}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}(wr),Sc=Gt(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Un=function(r){Te(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 $n(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new Sc},e.prototype.next=function(t){var n=this;Wt(function(){var s,o;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var a=Xe(n.currentObservers),c=a.next();!c.done;c=a.next()){var u=c.value;u.next(t)}}catch(l){s={error:l}}finally{try{c&&!c.done&&(o=a.return)&&o.call(a)}finally{if(s)throw s.error}}}})},e.prototype.error=function(t){var n=this;Wt(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=t;for(var s=n.observers;s.length;)s.shift().error(t)}})},e.prototype.complete=function(){var t=this;Wt(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,s=this,o=s.hasError,a=s.isStopped,c=s.observers;return o||a?On:(this.currentObservers=null,c.push(t),new Et(function(){n.currentObservers=null,Yt(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,s=n.hasError,o=n.thrownError,a=n.isStopped;s?t.error(o):a&&t.complete()},e.prototype.asObservable=function(){var t=new _e;return t.source=this,t},e.create=function(t,n){return new $n(t,n)},e}(_e),$n=function(r){Te(e,r);function e(t,n){var s=r.call(this)||this;return s.destination=t,s.source=n,s}return e.prototype.next=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.next)===null||s===void 0||s.call(n,t)},e.prototype.error=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.error)===null||s===void 0||s.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,s;return(s=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&s!==void 0?s:On},e}(Un),Cc={now:function(){return Date.now()},delegate:void 0},xc=function(r){Te(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(Et),Zn={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,qt([r,e],Bt(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},Ac=function(r){Te(e,r);function e(t,n){var s=r.call(this,t,n)||this;return s.scheduler=t,s.work=n,s.pending=!1,s}return e.prototype.schedule=function(t,n){var s;if(n===void 0&&(n=0),this.closed)return this;this.state=t;var o=this.id,a=this.scheduler;return o!=null&&(this.id=this.recycleAsyncId(a,o,n)),this.pending=!0,this.delay=n,this.id=(s=this.id)!==null&&s!==void 0?s:this.requestAsyncId(a,this.id,n),this},e.prototype.requestAsyncId=function(t,n,s){return s===void 0&&(s=0),Zn.setInterval(t.flush.bind(t,this),s)},e.prototype.recycleAsyncId=function(t,n,s){if(s===void 0&&(s=0),s!=null&&this.delay===s&&this.pending===!1)return n;n!=null&&Zn.clearInterval(n)},e.prototype.execute=function(t,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var s=this._execute(t,n);if(s)return s;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,n){var s=!1,o;try{this.work(t)}catch(a){s=!0,o=a||new Error("Scheduled action threw falsy error")}if(s)return this.unsubscribe(),o},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,s=t.scheduler,o=s.actions;this.work=this.state=this.scheduler=null,this.pending=!1,Yt(o,this),n!=null&&(this.id=this.recycleAsyncId(s,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(xc),Vn=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=Cc.now,r}(),Pc=function(r){Te(e,r);function e(t,n){n===void 0&&(n=Vn.now);var s=r.call(this,t,n)||this;return s.actions=[],s._active=!1,s}return e.prototype.flush=function(t){var n=this.actions;if(this._active){n.push(t);return}var s;this._active=!0;do if(s=t.execute(t.state,t.delay))break;while(t=n.shift());if(this._active=!1,s){for(;t=n.shift();)t.unsubscribe();throw s}},e}(Vn),Tc=new Pc(Ac),Ic=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function Oc(r){return $(r==null?void 0:r.then)}function Rc(r){return $(r[Er])}function Nc(r){return Symbol.asyncIterator&&$(r==null?void 0:r[Symbol.asyncIterator])}function Mc(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 jc(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Dc=jc();function Lc(r){return $(r==null?void 0:r[Dc])}function Fc(r){return uc(this,arguments,function(){var t,n,s,o;return In(this,function(a){switch(a.label){case 0:t=r.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,et(t.read())];case 3:return n=a.sent(),s=n.value,o=n.done,o?[4,et(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,et(s)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Uc(r){return $(r==null?void 0:r.getReader)}function $c(r){if(r instanceof _e)return r;if(r!=null){if(Rc(r))return Zc(r);if(Ic(r))return Vc(r);if(Oc(r))return zc(r);if(Nc(r))return zn(r);if(Lc(r))return Bc(r);if(Uc(r))return qc(r)}throw Mc(r)}function Zc(r){return new _e(function(e){var t=r[Er]();if($(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Vc(r){return new _e(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function zc(r){return new _e(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,Dn)})}function Bc(r){return new _e(function(e){var t,n;try{for(var s=Xe(r),o=s.next();!o.done;o=s.next()){var a=o.value;if(e.next(a),e.closed)return}}catch(c){t={error:c}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}e.complete()})}function zn(r){return new _e(function(e){Gc(r,e).catch(function(t){return e.error(t)})})}function qc(r){return zn(Fc(r))}function Gc(r,e){var t,n,s,o;return lc(this,void 0,void 0,function(){var a,c;return In(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),t=dc(r),u.label=1;case 1:return[4,t.next()];case 2:if(n=u.sent(),!!n.done)return[3,4];if(a=n.value,e.next(a),e.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=u.sent(),s={error:c},[3,11];case 6:return u.trys.push([6,,9,10]),n&&!n.done&&(o=t.return)?[4,o.call(t)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(s)throw s.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Yc(r,e,t,n,s){n===void 0&&(n=0),s===void 0&&(s=!1);var o=e.schedule(function(){t(),s?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(o),!s)return o}function Wc(r,e){var t=$(r)?r:function(){return r},n=function(s){return s.error(t())};return new _e(n)}var Hc=Gt(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function Kc(r,e){return new Promise(function(t,n){var s=!1,o;r.subscribe({next:function(a){o=a,s=!0},error:n,complete:function(){s?t(o):n(new Hc)}})})}function Jc(r){return r instanceof Date&&!isNaN(r)}var Qc=Gt(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Xc(r,e){var t=Jc(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,s=t.each,o=t.with,a=o===void 0?el:o,c=t.scheduler,u=c===void 0?Tc:c,l=t.meta,d=l===void 0?null:l;if(n==null&&s==null)throw new TypeError("No timeout provided.");return bc(function(h,w){var m,g,b=null,A=0,O=function(T){g=Yc(w,u,function(){try{m.unsubscribe(),$c(a({meta:d,lastValue:b,seen:A})).subscribe(w)}catch(M){w.error(M)}},T)};m=h.subscribe(kc(w,function(T){g==null||g.unsubscribe(),A++,w.next(b=T),s>0&&O(s)},void 0,void 0,function(){g!=null&&g.closed||g==null||g.unsubscribe(),b=null})),!A&&O(n!=null?typeof n=="number"?n:+n-u.now():s)})}function el(r){throw new Qc(r)}class Kt{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"&&cr(this._current);const t={first:e.timeoutSec*1e3,with:()=>Wc(()=>new Error(e.timeoutErrMsg))};return Kc(this._subject.pipe(Xc(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new Un}get current(){return this._current}}const{log__:tl,err__:rl}=F("init-flows"),Jt=(r,e)=>{const t=new Kt;return{publisher:t,initialize:async n=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const s=await e(n);tl(`✔ ${r} flow initialized successfully. Result:`,s),t.set(s)}catch(s){rl(`𝙭 ${r} flow initialization failed. Error:`,he(s),"Details:",s),t.throw(s,he(s))}}}},nl=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},sl=()=>({stripePR:Jt("Stripe PR",te.stripePR.init),stripeLink:Jt("Stripe Link",te.stripeLink.init),airwallexGooglePay:Jt("Airwallex GPay",te.airwallexGooglePay.init),airwallexApplePay:Jt("Airwallex ApplePay",te.airwallexApplePay.init)}),{err__:ol}=F("form-callbacks"),re=i.function().optional(),Bn=i.object({onFocus:re,onBlur:re,onChange:re,onLoad:re,onLoadError:re,onValidationError:re,onCheckoutStarted:re,onCheckoutSuccess:re,onSetupPaymentMethodSuccess:re,onCheckoutError:re,onPaymentRequestLoad:re}),le=class le{constructor(){this.setCallbacks=e=>{this._callbacks=le.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const s=Xs(t,n??le.NOOP,ol);this._callbacks[t]=s})},this._callbacks=le.createEmptyCallbacks()}get get(){return{...this._callbacks}}};le.NOOP=()=>{},le.createEmptyCallbacks=()=>{const e={};return Object.keys(Bn.keyof().enum).forEach(t=>{e[t]=le.NOOP}),e},le.fromObject=e=>{const t=new le;return t.setCallbacks(Bn.parse(e)),t};let Sr=le;class il{constructor(e,t,n,s){this.handleMessage=o=>{if(!o.source)throw new Error("No source found");if(qn(o.origin)!==qn(this.baseUrl)||typeof o.data=="object"&&o.data.penpal)return;let a=null;try{a=Bo(JSON.parse(o.data))}catch(h){console.warn("[OJS] Unknown event. Ignoring:",h);return}if(!this.validateEvent(a))return;const{elementId:u,payload:l}=a,d=l.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(l.height?`${l.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(u,l.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(u,l.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(u,l.elementType,l.errors);break;case"LOADED":this.eventTargets[u]=o.source,this.internalCallbacks.onCdeLoaded(l);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(l.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(l.elementType,l.errors,u);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=o=>o.formId!==this.formId||!o.elementId?(console.log("[OJS] formId",this.formId,o.formId),console.warn("[form] Ignoring unknown event:",o),!1):this.nonces.has(o.nonce)?(console.warn("[form] Ignoring duplicate event:",o),!1):(this.nonces.add(o.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=n,this.internalCallbacks=s}}const qn=r=>new URL(r).origin;async function al(r,e){const n=await Kr({iframe:r,debug:!1,childOrigin:e}).promise,s=await fi(n);if(!pi(n,s))throw new Error("Got invalid CDE connection object");return n}class cl{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 ll=(r,e,t)=>{const{stripePR:n}=r;n.publisher.subscribe(s=>{if(s.isSuccess){const o=s.loadedValue,a=o.isAvailable&&o.availableProviders.applePay,c=o.isAvailable&&o.availableProviders.googlePay,u={apple_pay:{isLoading:!1,isAvailable:a,startFlow:async l=>{a&&Gn("apple_pay",o,e,t,l)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async l=>{c&&Gn("google_pay",o,e,t,l)}}};t.get.onPaymentRequestLoad(u)}})},Gn=(r,e,t,n,s)=>te.stripePR.run({context:t,checkoutPaymentMethod:_r(t.checkoutPaymentMethods,r),nonCdeFormInputs:Ge(t.formDiv),formCallbacks:n,customParams:{provider:r,overridePaymentRequest:s==null?void 0:s.overridePaymentRequest},initResult:e}),Yn="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:ge,err__:De}=F("op-form"),ve=class ve{constructor(e){this.cdeLoadEvent=new Kt,this.anyCdeConn=new Kt,this.context=new Kt,this.initFlows=sl(),this.startFormInit=async()=>{try{ge("Initializing OpenPay form:"),ge("├ Waiting for CDE load event...");const t=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Yn});ge("├ CDE load event received"),ge("├ Waiting for CDE connection...");const n=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Yn});ge("├ CDE connection received"),ge("├ Creating OJS context, setting up handlers...");const s=ve.buildOjsFlowContext(this.config,t,n,this.getFormDiv());this.context.set(s),ll(this.initFlows,s,this.formCallbacks),ge("├ Starting OJS init flows..."),await nl(this.initFlows,s,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),ge("╰ Done initializing OJS flows.")}catch(t){const n=he(t);De("╰ 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 s=eo.parse(t),o=document.createElement("iframe"),a=this.buildQueryString(n);o.name=`${s}-element`;const c=new URL(`/app/v1/${o.name}/`,this.config.baseUrl);return c.search=a.toString(),o.src=c.href,o.style.border="none",o.style.width="100%",this.registerIframe(s,o)},this.registerIframe=(t,n)=>{const s={type:t,node:n,mount:o=>{var a;return(a=document.querySelector(o))==null?void 0:a.appendChild(n)}};return this.connectToElement({type:s.type,node:s.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]=s,s},this.buildQueryString=t=>{const n=new URLSearchParams;return n.append("referer",this.referrer),n.append("formId",this.formId),t.styles&&n.append("styles",Fo(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{al(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>De("[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){De("Please wait for the form to finish loading before submitting.");return}te.commonCC.run({context:t,checkoutPaymentMethod:_r(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:Ge(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){De("Please wait for the form to finish loading before getting available payment methods.");return}return Object.entries(this.initFlows).map(([n,s])=>({name:n,...s.publisher.getValueIfLoadedElse(null)}))},this.generalSubmit=(t,n)=>{const s=this.context.getValueIfLoadedElse(null);if(!s){De("Please wait for the form to finish loading before submitting.");return}switch(t){case"pockyt-paypal":return te.pockytPaypal.run({context:s,checkoutPaymentMethod:_r(s.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:Ge(s.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:n},initResult:void 0});case"airwallex-google-pay":return this.initFlows.airwallexGooglePay.publisher.subscribe(o=>{o.isSuccess&&o.loadedValue.isAvailable?o.loadedValue.startFlow(n):De("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'")});case"airwallex-apple-pay":return this.initFlows.airwallexApplePay.publisher.subscribe(o=>{o.isSuccess&&o.loadedValue.isAvailable?o.loadedValue.startFlow(n):De("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'")});default:cr(t)}},this.submit=this.submitCard,this.destroy=()=>{ge("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)},ve.assignAsSingleton(this),this.ojsVersion="0.2.8",this.ojsReleaseVersion="0.2.8",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Sr.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${zo()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new cl,this.eventHandler=new il(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}};ve.ojsFlows=te,ve.assignAsSingleton=e=>{if(ve.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},ve.getInstance=()=>window.ojs??null,ve.buildOjsFlowContext=(e,t,n,s)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??Fe).origin,formDiv:s,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Cr=ve;Oe.FieldName=p,Oe.OpenPayForm=Cr,Object.defineProperty(Oe,Symbol.toStringTag,{value:"Module"})});
25
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function Gt(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var Et=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,s,o;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var c=Xe(a),u=c.next();!u.done;u=c.next()){var l=u.value;l.remove(this)}}catch(k){e={error:k}}finally{try{u&&!u.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else a.remove(this);var d=this.initialTeardown;if(Z(d))try{d()}catch(k){o=k instanceof vr?k.errors:[k]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var w=Xe(h),m=w.next();!m.done;m=w.next()){var g=m.value;try{Mn(g)}catch(k){o=o??[],k instanceof vr?o=Bt(Bt([],zt(o)),zt(k.errors)):o.push(k)}}}catch(k){n={error:k}}finally{try{m&&!m.done&&(s=w.return)&&s.call(w)}finally{if(n)throw n.error}}}if(o)throw new vr(o)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Mn(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)&&Gt(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&Gt(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),Rn=Et.EMPTY;function Nn(r){return r instanceof Et||r&&"closed"in r&&Z(r.remove)&&Z(r.add)&&Z(r.unsubscribe)}function Mn(r){Z(r)?r():r.unsubscribe()}var jn={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Dn={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,Bt([r,e],zt(t)))},clearTimeout:function(r){var e=Dn.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function Ln(r){Dn.setTimeout(function(){throw r})}function Fn(){}function Yt(r){r()}var wr=function(r){Ie(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,Nn(t)&&t.add(n)):n.destination=mc,n}return e.create=function(t,n,s){return new kr(t,n,s)},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}(Et),fc=Function.prototype.bind;function br(r,e){return fc.call(r,e)}var pc=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){Wt(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){Wt(n)}else Wt(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Wt(t)}},r}(),kr=function(r){Ie(e,r);function e(t,n,s){var o=r.call(this)||this,a;if(Z(t)||!t)a={next:t??void 0,error:n??void 0,complete:s??void 0};else{var c;o&&jn.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return o.unsubscribe()},a={next:t.next&&br(t.next,c),error:t.error&&br(t.error,c),complete:t.complete&&br(t.complete,c)}):a=t}return o.destination=new pc(a),o}return e}(wr);function Wt(r){Ln(r)}function hc(r){throw r}var mc={closed:!0,next:Fn,error:hc,complete:Fn},Er=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function yc(r){return r}function _c(r){return r.length===0?yc:r.length===1?r[0]:function(t){return r.reduce(function(n,s){return s(n)},t)}}var ge=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 s=this,o=vc(e)?e:new kr(e,t,n);return Yt(function(){var a=s,c=a.operator,u=a.source;o.add(c?c.call(o,u):u?s._subscribe(o):s._trySubscribe(o))}),o},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=Un(t),new t(function(s,o){var a=new kr({next:function(c){try{e(c)}catch(u){o(u),a.unsubscribe()}},error:o,complete:s});n.subscribe(a)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Er]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return _c(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=Un(e),new e(function(n,s){var o;t.subscribe(function(a){return o=a},function(a){return s(a)},function(){return n(o)})})},r.create=function(e){return new r(e)},r}();function Un(r){var e;return(e=r??jn.Promise)!==null&&e!==void 0?e:Promise}function gc(r){return r&&Z(r.next)&&Z(r.error)&&Z(r.complete)}function vc(r){return r&&r instanceof wr||gc(r)&&Nn(r)}function wc(r){return Z(r==null?void 0:r.lift)}function bc(r){return function(e){if(wc(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 kc(r,e,t,n,s){return new Ec(r,e,t,n,s)}var Ec=function(r){Ie(e,r);function e(t,n,s,o,a,c){var u=r.call(this,t)||this;return u.onFinalize=a,u.shouldUnsubscribe=c,u._next=n?function(l){try{n(l)}catch(d){t.error(d)}}:r.prototype._next,u._error=o?function(l){try{o(l)}catch(d){t.error(d)}finally{this.unsubscribe()}}:r.prototype._error,u._complete=s?function(){try{s()}catch(l){t.error(l)}finally{this.unsubscribe()}}:r.prototype._complete,u}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}(wr),Sc=qt(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),$n=function(r){Ie(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 Zn(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new Sc},e.prototype.next=function(t){var n=this;Yt(function(){var s,o;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var a=Xe(n.currentObservers),c=a.next();!c.done;c=a.next()){var u=c.value;u.next(t)}}catch(l){s={error:l}}finally{try{c&&!c.done&&(o=a.return)&&o.call(a)}finally{if(s)throw s.error}}}})},e.prototype.error=function(t){var n=this;Yt(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=t;for(var s=n.observers;s.length;)s.shift().error(t)}})},e.prototype.complete=function(){var t=this;Yt(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,s=this,o=s.hasError,a=s.isStopped,c=s.observers;return o||a?Rn:(this.currentObservers=null,c.push(t),new Et(function(){n.currentObservers=null,Gt(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,s=n.hasError,o=n.thrownError,a=n.isStopped;s?t.error(o):a&&t.complete()},e.prototype.asObservable=function(){var t=new ge;return t.source=this,t},e.create=function(t,n){return new Zn(t,n)},e}(ge),Zn=function(r){Ie(e,r);function e(t,n){var s=r.call(this)||this;return s.destination=t,s.source=n,s}return e.prototype.next=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.next)===null||s===void 0||s.call(n,t)},e.prototype.error=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.error)===null||s===void 0||s.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,s;return(s=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&s!==void 0?s:Rn},e}($n),Cc={now:function(){return Date.now()},delegate:void 0},xc=function(r){Ie(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(Et),Vn={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,Bt([r,e],zt(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},Ac=function(r){Ie(e,r);function e(t,n){var s=r.call(this,t,n)||this;return s.scheduler=t,s.work=n,s.pending=!1,s}return e.prototype.schedule=function(t,n){var s;if(n===void 0&&(n=0),this.closed)return this;this.state=t;var o=this.id,a=this.scheduler;return o!=null&&(this.id=this.recycleAsyncId(a,o,n)),this.pending=!0,this.delay=n,this.id=(s=this.id)!==null&&s!==void 0?s:this.requestAsyncId(a,this.id,n),this},e.prototype.requestAsyncId=function(t,n,s){return s===void 0&&(s=0),Vn.setInterval(t.flush.bind(t,this),s)},e.prototype.recycleAsyncId=function(t,n,s){if(s===void 0&&(s=0),s!=null&&this.delay===s&&this.pending===!1)return n;n!=null&&Vn.clearInterval(n)},e.prototype.execute=function(t,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var s=this._execute(t,n);if(s)return s;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,n){var s=!1,o;try{this.work(t)}catch(a){s=!0,o=a||new Error("Scheduled action threw falsy error")}if(s)return this.unsubscribe(),o},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,s=t.scheduler,o=s.actions;this.work=this.state=this.scheduler=null,this.pending=!1,Gt(o,this),n!=null&&(this.id=this.recycleAsyncId(s,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(xc),zn=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=Cc.now,r}(),Pc=function(r){Ie(e,r);function e(t,n){n===void 0&&(n=zn.now);var s=r.call(this,t,n)||this;return s.actions=[],s._active=!1,s}return e.prototype.flush=function(t){var n=this.actions;if(this._active){n.push(t);return}var s;this._active=!0;do if(s=t.execute(t.state,t.delay))break;while(t=n.shift());if(this._active=!1,s){for(;t=n.shift();)t.unsubscribe();throw s}},e}(zn),Tc=new Pc(Ac),Ic=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function Oc(r){return Z(r==null?void 0:r.then)}function Rc(r){return Z(r[Er])}function Nc(r){return Symbol.asyncIterator&&Z(r==null?void 0:r[Symbol.asyncIterator])}function Mc(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 jc(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Dc=jc();function Lc(r){return Z(r==null?void 0:r[Dc])}function Fc(r){return uc(this,arguments,function(){var t,n,s,o;return On(this,function(a){switch(a.label){case 0:t=r.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,et(t.read())];case 3:return n=a.sent(),s=n.value,o=n.done,o?[4,et(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,et(s)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Uc(r){return Z(r==null?void 0:r.getReader)}function $c(r){if(r instanceof ge)return r;if(r!=null){if(Rc(r))return Zc(r);if(Ic(r))return Vc(r);if(Oc(r))return zc(r);if(Nc(r))return Bn(r);if(Lc(r))return Bc(r);if(Uc(r))return qc(r)}throw Mc(r)}function Zc(r){return new ge(function(e){var t=r[Er]();if(Z(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Vc(r){return new ge(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function zc(r){return new ge(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,Ln)})}function Bc(r){return new ge(function(e){var t,n;try{for(var s=Xe(r),o=s.next();!o.done;o=s.next()){var a=o.value;if(e.next(a),e.closed)return}}catch(c){t={error:c}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}e.complete()})}function Bn(r){return new ge(function(e){Gc(r,e).catch(function(t){return e.error(t)})})}function qc(r){return Bn(Fc(r))}function Gc(r,e){var t,n,s,o;return lc(this,void 0,void 0,function(){var a,c;return On(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),t=dc(r),u.label=1;case 1:return[4,t.next()];case 2:if(n=u.sent(),!!n.done)return[3,4];if(a=n.value,e.next(a),e.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=u.sent(),s={error:c},[3,11];case 6:return u.trys.push([6,,9,10]),n&&!n.done&&(o=t.return)?[4,o.call(t)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(s)throw s.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Yc(r,e,t,n,s){n===void 0&&(n=0),s===void 0&&(s=!1);var o=e.schedule(function(){t(),s?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(o),!s)return o}function Wc(r,e){var t=Z(r)?r:function(){return r},n=function(s){return s.error(t())};return new ge(n)}var Hc=qt(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function Kc(r,e){return new Promise(function(t,n){var s=!1,o;r.subscribe({next:function(a){o=a,s=!0},error:n,complete:function(){s?t(o):n(new Hc)}})})}function Jc(r){return r instanceof Date&&!isNaN(r)}var Qc=qt(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Xc(r,e){var t=Jc(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,s=t.each,o=t.with,a=o===void 0?el:o,c=t.scheduler,u=c===void 0?Tc:c,l=t.meta,d=l===void 0?null:l;if(n==null&&s==null)throw new TypeError("No timeout provided.");return bc(function(h,w){var m,g,k=null,A=0,N=function(T){g=Yc(w,u,function(){try{m.unsubscribe(),$c(a({meta:d,lastValue:k,seen:A})).subscribe(w)}catch(I){w.error(I)}},T)};m=h.subscribe(kc(w,function(T){g==null||g.unsubscribe(),A++,w.next(k=T),s>0&&N(s)},void 0,void 0,function(){g!=null&&g.closed||g==null||g.unsubscribe(),k=null})),!A&&N(n!=null?typeof n=="number"?n:+n-u.now():s)})}function el(r){throw new Qc(r)}class Ht{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"&&cr(this._current);const t={first:e.timeoutSec*1e3,with:()=>Wc(()=>new Error(e.timeoutErrMsg))};return Kc(this._subject.pipe(Xc(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new $n}get current(){return this._current}}const{log__:tl,err__:rl}=U("init-flows"),Kt=(r,e)=>{const t=new Ht;return{publisher:t,initialize:async n=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const s=await e(n);tl(`✔ ${r} flow initialized successfully. Result:`,s),t.set(s)}catch(s){rl(`𝙭 ${r} flow initialization failed. Error:`,ye(s),"Details:",s),t.throw(s,ye(s))}}}},nl=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},sl=()=>({stripePR:Kt("Stripe PR",re.stripePR.init),stripeLink:Kt("Stripe Link",re.stripeLink.init),airwallexGooglePay:Kt("Airwallex GPay",re.airwallexGooglePay.init),airwallexApplePay:Kt("Airwallex ApplePay",re.airwallexApplePay.init)}),{err__:ol}=U("form-callbacks"),ne=i.function().optional(),qn=i.object({onFocus:ne,onBlur:ne,onChange:ne,onLoad:ne,onLoadError:ne,onValidationError:ne,onCheckoutStarted:ne,onCheckoutSuccess:ne,onSetupPaymentMethodSuccess:ne,onCheckoutError:ne,onPaymentRequestLoad:ne}),fe=class fe{constructor(){this.setCallbacks=e=>{this._callbacks=fe.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const s=eo(t,n??fe.NOOP,ol);this._callbacks[t]=s})},this._callbacks=fe.createEmptyCallbacks()}get get(){return{...this._callbacks}}};fe.NOOP=()=>{},fe.createEmptyCallbacks=()=>{const e={};return Object.keys(qn.keyof().enum).forEach(t=>{e[t]=fe.NOOP}),e},fe.fromObject=e=>{const t=new fe;return t.setCallbacks(qn.parse(e)),t};let Sr=fe;class il{constructor(e,t,n,s){this.handleMessage=o=>{if(!o.source)throw new Error("No source found");if(Gn(o.origin)!==Gn(this.baseUrl)||typeof o.data=="object"&&o.data.penpal)return;let a=null;try{a=Bo(JSON.parse(o.data))}catch(h){console.warn("[OJS] Unknown event. Ignoring:",h);return}if(!this.validateEvent(a))return;const{elementId:u,payload:l}=a,d=l.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(l.height?`${l.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(u,l.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(u,l.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(u,l.elementType,l.errors);break;case"LOADED":this.eventTargets[u]=o.source,this.internalCallbacks.onCdeLoaded(l);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(l.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(l.elementType,l.errors,u);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=o=>o.formId!==this.formId||!o.elementId?(console.log("[OJS] formId",this.formId,o.formId),console.warn("[form] Ignoring unknown event:",o),!1):this.nonces.has(o.nonce)?(console.warn("[form] Ignoring duplicate event:",o),!1):(this.nonces.add(o.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=n,this.internalCallbacks=s}}const Gn=r=>new URL(r).origin;async function al(r,e){const n=await Jr({iframe:r,debug:!1,childOrigin:e}).promise,s=await fi(n);if(!pi(n,s))throw new Error("Got invalid CDE connection object");return n}class cl{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 ll=(r,e,t)=>{const{stripePR:n}=r;n.publisher.subscribe(s=>{if(s.isSuccess){const o=s.loadedValue,a=o.isAvailable&&o.availableProviders.applePay,c=o.isAvailable&&o.availableProviders.googlePay,u={apple_pay:{isLoading:!1,isAvailable:a,startFlow:async l=>{a&&Yn("apple_pay",o,e,t,l)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async l=>{c&&Yn("google_pay",o,e,t,l)}}};t.get.onPaymentRequestLoad(u)}})},Yn=(r,e,t,n,s)=>re.stripePR.run({context:t,checkoutPaymentMethod:_r(t.checkoutPaymentMethods,r),nonCdeFormInputs:Ge(t.formDiv),formCallbacks:n,customParams:{provider:r,overridePaymentRequest:s==null?void 0:s.overridePaymentRequest},initResult:e}),Wn="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:ve,err__:De}=U("op-form"),we=class we{constructor(e){this.cdeLoadEvent=new Ht,this.anyCdeConn=new Ht,this.context=new Ht,this.initFlows=sl(),this.startFormInit=async()=>{try{ve("Initializing OpenPay form:"),ve("├ Waiting for CDE load event...");const t=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Wn});ve("├ CDE load event received"),ve("├ Waiting for CDE connection...");const n=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Wn});ve("├ CDE connection received"),ve("├ Creating OJS context, setting up handlers...");const s=we.buildOjsFlowContext(this.config,t,n,this.getFormDiv());this.context.set(s),ll(this.initFlows,s,this.formCallbacks),ve("├ Starting OJS init flows..."),await nl(this.initFlows,s,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),ve("╰ Done initializing OJS flows.")}catch(t){const n=ye(t);De("╰ 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 s=to.parse(t),o=document.createElement("iframe"),a=this.buildQueryString(n);o.name=`${s}-element`;const c=new URL(`/app/v1/${o.name}/`,this.config.baseUrl);return c.search=a.toString(),o.src=c.href,o.style.border="none",o.style.width="100%",this.registerIframe(s,o)},this.registerIframe=(t,n)=>{const s={type:t,node:n,mount:o=>{var a;return(a=document.querySelector(o))==null?void 0:a.appendChild(n)}};return this.connectToElement({type:s.type,node:s.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]=s,s},this.buildQueryString=t=>{const n=new URLSearchParams;return n.append("referer",this.referrer),n.append("formId",this.formId),t.styles&&n.append("styles",Uo(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{al(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>De("[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){De("Please wait for the form to finish loading before submitting.");return}re.commonCC.run({context:t,checkoutPaymentMethod:_r(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:Ge(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){De("Please wait for the form to finish loading before getting available payment methods.");return}return Object.entries(this.initFlows).map(([n,s])=>({name:n,...s.publisher.getValueIfLoadedElse(null)}))},this.generalSubmit=(t,n)=>{const s=this.context.getValueIfLoadedElse(null);if(!s){De("Please wait for the form to finish loading before submitting.");return}switch(t){case"pockyt-paypal":return re.pockytPaypal.run({context:s,checkoutPaymentMethod:_r(s.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:Ge(s.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:n},initResult:void 0});case"airwallex-google-pay":return this.initFlows.airwallexGooglePay.publisher.subscribe(o=>{o.isSuccess&&o.loadedValue.isAvailable?o.loadedValue.startFlow(n):De("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'")});case"airwallex-apple-pay":return this.initFlows.airwallexApplePay.publisher.subscribe(o=>{o.isSuccess&&o.loadedValue.isAvailable?o.loadedValue.startFlow(n):De("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'")});default:cr(t)}},this.submit=this.submitCard,this.destroy=()=>{ve("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)},we.assignAsSingleton(this),this.ojsVersion="0.2.10",this.ojsReleaseVersion="0.2.10",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Sr.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Gr()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new cl,this.eventHandler=new il(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}};we.ojsFlows=re,we.assignAsSingleton=e=>{if(we.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},we.getInstance=()=>window.ojs??null,we.buildOjsFlowContext=(e,t,n,s)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??Fe).origin,formDiv:s,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Cr=we;Oe.FieldName=p,Oe.OpenPayForm=Cr,Object.defineProperty(Oe,Symbol.toStringTag,{value:"Module"})});