@getopenpay/openpay-js 0.2.31 → 0.2.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,17 +1,17 @@
1
- (function(Ce,Ke){typeof exports=="object"&&typeof module<"u"?Ke(exports):typeof define=="function"&&define.amd?define(["exports"],Ke):(Ce=typeof globalThis<"u"?globalThis:Ce||self,Ke(Ce.OpenPay={}))})(this,function(Ce){"use strict";var Bo;const Ke="https://cde.getopenpay.com";var R;(function(t){t.assertEqual=o=>o;function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{const s={};for(const i of o)s[i]=i;return s},t.getValidEnumValues=o=>{const s=t.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),i={};for(const c of s)i[c]=o[c];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(const i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(R||(R={}));var vr;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(vr||(vr={}));const v=R.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Re=t=>{switch(typeof t){case"undefined":return v.undefined;case"string":return v.string;case"number":return isNaN(t)?v.nan:v.number;case"boolean":return v.boolean;case"function":return v.function;case"bigint":return v.bigint;case"symbol":return v.symbol;case"object":return Array.isArray(t)?v.array:t===null?v.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?v.promise:typeof Map<"u"&&t instanceof Map?v.map:typeof Set<"u"&&t instanceof Set?v.set:typeof Date<"u"&&t instanceof Date?v.date:v.object;default:return v.unknown}},y=R.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),qo=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class te extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let c=n,l=0;for(;l<i.path.length;){const u=i.path[l];l===i.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(r(i))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};return o(this),n}static assert(e){if(!(e instanceof te))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,R.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const o of this.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}te.create=t=>new te(t);const Je=(t,e)=>{let r;switch(t.code){case y.invalid_type:t.received===v.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case y.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,R.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:r=`Unrecognized key(s) in object: ${R.joinValues(t.keys,", ")}`;break;case y.invalid_union:r="Invalid input";break;case y.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${R.joinValues(t.options)}`;break;case y.invalid_enum_value:r=`Invalid enum value. Expected ${R.joinValues(t.options)}, received '${t.received}'`;break;case y.invalid_arguments:r="Invalid function arguments";break;case y.invalid_return_type:r="Invalid function return type";break;case y.invalid_date:r="Invalid date";break;case y.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:R.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case y.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case y.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case y.custom:r="Invalid input";break;case y.invalid_intersection_types:r="Intersection results could not be merged";break;case y.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case y.not_finite:r="Number must be finite";break;default:r=e.defaultError,R.assertNever(t)}return{message:r}};let Hr=Je;function Yo(t){Hr=t}function zt(){return Hr}const Gt=t=>{const{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=n.filter(u=>!!u).slice().reverse();for(const u of l)c=u(i,{data:e,defaultError:c}).message;return{...o,path:s,message:c}},Wo=[];function g(t,e){const r=zt(),n=Gt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Je?void 0:Je].filter(o=>!!o)});t.common.issues.push(n)}class H{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const o of r){if(o.status==="aborted")return S;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const o of r){const s=await o.key,i=await o.value;n.push({key:s,value:i})}return H.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const o of r){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return S;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}}const S=Object.freeze({status:"aborted"}),Qe=t=>({status:"dirty",value:t}),J=t=>({status:"valid",value:t}),wr=t=>t.status==="aborted",br=t=>t.status==="dirty",pt=t=>t.status==="valid",ft=t=>typeof Promise<"u"&&t instanceof Promise;function Bt(t,e,r,n){if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function Kr(t,e,r,n,o){if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,r),r}typeof SuppressedError=="function"&&SuppressedError;var b;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(b||(b={}));var mt,ht;class fe{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Jr=(t,e)=>{if(pt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new te(t.common.issues);return this._error=r,this._error}}};function A(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,c)=>{var l,u;const{message:d}=t;return i.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(l=d??n)!==null&&l!==void 0?l:c.defaultError}:i.code!=="invalid_type"?{message:c.defaultError}:{message:(u=d??r)!==null&&u!==void 0?u:c.defaultError}},description:o}}class T{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return Re(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new H,ctx:{common:e.parent.common,data:e.data,parsedType:Re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(ft(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){var n;const o={common:{issues:[],async:(n=r==null?void 0:r.async)!==null&&n!==void 0?n:!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)},s=this._parseSync({data:e,path:o.path,parent:o});return Jr(o,s)}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ft(o)?o:Promise.resolve(o));return Jr(n,s)}refine(e,r){const n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{const i=e(o),c=()=>s.addIssue({code:y.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(c(),!1)):i?!0:(c(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new ae({schema:this,typeName:C.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return he.create(this,this._def)}nullable(){return De.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return se.create(this,this._def)}promise(){return rt.create(this,this._def)}or(e){return vt.create([this,e],this._def)}and(e){return wt.create(this,e,this._def)}transform(e){return new ae({...A(this._def),schema:this,typeName:C.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new St({...A(this._def),innerType:this,defaultValue:r,typeName:C.ZodDefault})}brand(){return new Cr({typeName:C.ZodBranded,type:this,...A(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new Pt({...A(this._def),innerType:this,catchValue:r,typeName:C.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return At.create(this,e)}readonly(){return Tt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ho=/^c[^\s-]{8,}$/i,Ko=/^[0-9a-z]+$/,Jo=/^[0-9A-HJKMNP-TV-Z]{26}$/,Qo=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Xo=/^[a-z0-9_-]{21}$/i,es=/^[-+]?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)?)??$/,ts=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,rs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Er;const ns=/^(?:(?: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])$/,os=/^(([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})))$/,ss=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Qr="((\\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])))",as=new RegExp(`^${Qr}$`);function Xr(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function is(t){return new RegExp(`^${Xr(t)}$`)}function en(t){let e=`${Qr}T${Xr(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function cs(t,e){return!!((e==="v4"||!e)&&ns.test(t)||(e==="v6"||!e)&&os.test(t))}class oe extends T{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==v.string){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.string,received:s.parsedType}),S}const n=new H;let o;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const i=e.data.length>s.value,c=e.data.length<s.value;(i||c)&&(o=this._getOrReturnCtx(e,o),i?g(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&g(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")ts.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"email",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Er||(Er=new RegExp(rs,"u")),Er.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"emoji",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Qo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"uuid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Xo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"nanoid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Ho.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Ko.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid2",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Jo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ulid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),g(o,{validation:"url",code:y.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"regex",code:y.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?en(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?as.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?is(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?es.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"duration",code:y.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?cs(e.data,s.version)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ip",code:y.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?ss.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"base64",code:y.invalid_string,message:s.message}),n.dirty()):R.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:y.invalid_string,...b.errToObj(n)})}_addCheck(e){return new oe({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...b.errToObj(e)})}url(e){return this._addCheck({kind:"url",...b.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...b.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...b.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...b.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...b.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...b.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...b.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...b.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...b.errToObj(e)})}datetime(e){var r,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:(r=e==null?void 0:e.offset)!==null&&r!==void 0?r:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...b.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...b.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...b.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...b.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...b.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...b.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...b.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...b.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...b.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...b.errToObj(r)})}nonempty(e){return this.min(1,b.errToObj(e))}trim(){return new oe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new oe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new oe({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}oe.create=t=>{var e;return new oe({checks:[],typeName:C.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...A(t)})};function ls(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=parseInt(t.toFixed(o).replace(".","")),i=parseInt(e.toFixed(o).replace(".",""));return s%i/Math.pow(10,o)}class Ne extends T{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==v.number){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.number,received:s.parsedType}),S}let n;const o=new H;for(const s of this._def.checks)s.kind==="int"?R.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:y.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?ls(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:y.not_finite,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,b.toString(r))}gt(e,r){return this.setLimit("min",e,!1,b.toString(r))}lte(e,r){return this.setLimit("max",e,!0,b.toString(r))}lt(e,r){return this.setLimit("max",e,!1,b.toString(r))}setLimit(e,r,n,o){return new Ne({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:b.toString(o)}]})}_addCheck(e){return new Ne({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:b.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:b.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&R.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}Ne.create=t=>new Ne({checks:[],typeName:C.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...A(t)});class Oe extends T{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==v.bigint){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.bigint,received:s.parsedType}),S}let n;const o=new H;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,b.toString(r))}gt(e,r){return this.setLimit("min",e,!1,b.toString(r))}lte(e,r){return this.setLimit("max",e,!0,b.toString(r))}lt(e,r){return this.setLimit("max",e,!1,b.toString(r))}setLimit(e,r,n,o){return new Oe({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:b.toString(o)}]})}_addCheck(e){return new Oe({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}Oe.create=t=>{var e;return new Oe({checks:[],typeName:C.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...A(t)})};class yt extends T{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==v.boolean){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.boolean,received:n.parsedType}),S}return J(e.data)}}yt.create=t=>new yt({typeName:C.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...A(t)});class $e extends T{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==v.date){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.date,received:s.parsedType}),S}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_date}),S}const n=new H;let o;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):R.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new $e({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:b.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:b.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}$e.create=t=>new $e({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:C.ZodDate,...A(t)});class qt extends T{_parse(e){if(this._getType(e)!==v.symbol){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.symbol,received:n.parsedType}),S}return J(e.data)}}qt.create=t=>new qt({typeName:C.ZodSymbol,...A(t)});class _t extends T{_parse(e){if(this._getType(e)!==v.undefined){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.undefined,received:n.parsedType}),S}return J(e.data)}}_t.create=t=>new _t({typeName:C.ZodUndefined,...A(t)});class gt extends T{_parse(e){if(this._getType(e)!==v.null){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.null,received:n.parsedType}),S}return J(e.data)}}gt.create=t=>new gt({typeName:C.ZodNull,...A(t)});class Xe extends T{constructor(){super(...arguments),this._any=!0}_parse(e){return J(e.data)}}Xe.create=t=>new Xe({typeName:C.ZodAny,...A(t)});class Ze extends T{constructor(){super(...arguments),this._unknown=!0}_parse(e){return J(e.data)}}Ze.create=t=>new Ze({typeName:C.ZodUnknown,...A(t)});class Se extends T{_parse(e){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.never,received:r.parsedType}),S}}Se.create=t=>new Se({typeName:C.ZodNever,...A(t)});class Yt extends T{_parse(e){if(this._getType(e)!==v.undefined){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.void,received:n.parsedType}),S}return J(e.data)}}Yt.create=t=>new Yt({typeName:C.ZodVoid,...A(t)});class se extends T{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==v.array)return g(r,{code:y.invalid_type,expected:v.array,received:r.parsedType}),S;if(o.exactLength!==null){const i=r.data.length>o.exactLength.value,c=r.data.length<o.exactLength.value;(i||c)&&(g(r,{code:i?y.too_big:y.too_small,minimum:c?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(g(r,{code:y.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(g(r,{code:y.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,c)=>o.type._parseAsync(new fe(r,i,r.path,c)))).then(i=>H.mergeArray(n,i));const s=[...r.data].map((i,c)=>o.type._parseSync(new fe(r,i,r.path,c)));return H.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new se({...this._def,minLength:{value:e,message:b.toString(r)}})}max(e,r){return new se({...this._def,maxLength:{value:e,message:b.toString(r)}})}length(e,r){return new se({...this._def,exactLength:{value:e,message:b.toString(r)}})}nonempty(e){return this.min(1,e)}}se.create=(t,e)=>new se({type:t,minLength:null,maxLength:null,exactLength:null,typeName:C.ZodArray,...A(e)});function et(t){if(t instanceof j){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=he.create(et(n))}return new j({...t._def,shape:()=>e})}else return t instanceof se?new se({...t._def,type:et(t.element)}):t instanceof he?he.create(et(t.unwrap())):t instanceof De?De.create(et(t.unwrap())):t instanceof me?me.create(t.items.map(e=>et(e))):t}class j extends T{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(),r=R.objectKeys(e);return this._cached={shape:e,keys:r}}_parse(e){if(this._getType(e)!==v.object){const u=this._getOrReturnCtx(e);return g(u,{code:y.invalid_type,expected:v.object,received:u.parsedType}),S}const{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof Se&&this._def.unknownKeys==="strip"))for(const u in o.data)i.includes(u)||c.push(u);const l=[];for(const u of i){const d=s[u],p=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new fe(o,p,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Se){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of c)l.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(u==="strict")c.length>0&&(g(o,{code:y.unrecognized_keys,keys:c}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const d of c){const p=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new fe(o,p,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of l){const p=await d.key,_=await d.value;u.push({key:p,value:_,alwaysSet:d.alwaysSet})}return u}).then(u=>H.mergeObjectSync(n,u)):H.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return b.errToObj,new j({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{var o,s,i,c;const l=(i=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,r,n).message)!==null&&i!==void 0?i:n.defaultError;return r.code==="unrecognized_keys"?{message:(c=b.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new j({...this._def,unknownKeys:"strip"})}passthrough(){return new j({...this._def,unknownKeys:"passthrough"})}extend(e){return new j({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new j({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:C.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new j({...this._def,catchall:e})}pick(e){const r={};return R.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new j({...this._def,shape:()=>r})}omit(e){const r={};return R.objectKeys(this.shape).forEach(n=>{e[n]||(r[n]=this.shape[n])}),new j({...this._def,shape:()=>r})}deepPartial(){return et(this)}partial(e){const r={};return R.objectKeys(this.shape).forEach(n=>{const o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}),new j({...this._def,shape:()=>r})}required(e){const r={};return R.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof he;)s=s._def.innerType;r[n]=s}}),new j({...this._def,shape:()=>r})}keyof(){return tn(R.objectKeys(this.shape))}}j.create=(t,e)=>new j({shape:()=>t,unknownKeys:"strip",catchall:Se.create(),typeName:C.ZodObject,...A(e)}),j.strictCreate=(t,e)=>new j({shape:()=>t,unknownKeys:"strict",catchall:Se.create(),typeName:C.ZodObject,...A(e)}),j.lazycreate=(t,e)=>new j({shape:t,unknownKeys:"strip",catchall:Se.create(),typeName:C.ZodObject,...A(e)});class vt extends T{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return r.common.issues.push(...c.ctx.common.issues),c.result;const i=s.map(c=>new te(c.ctx.common.issues));return g(r,{code:y.invalid_union,unionErrors:i}),S}if(r.common.async)return Promise.all(n.map(async s=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s;const i=[];for(const l of n){const u={...r,common:{...r.common,issues:[]},parent:null},d=l._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const c=i.map(l=>new te(l));return g(r,{code:y.invalid_union,unionErrors:c}),S}}get options(){return this._def.options}}vt.create=(t,e)=>new vt({options:t,typeName:C.ZodUnion,...A(e)});const Pe=t=>t instanceof Et?Pe(t.schema):t instanceof ae?Pe(t.innerType()):t instanceof kt?[t.value]:t instanceof Me?t.options:t instanceof Ct?R.objectValues(t.enum):t instanceof St?Pe(t._def.innerType):t instanceof _t?[void 0]:t instanceof gt?[null]:t instanceof he?[void 0,...Pe(t.unwrap())]:t instanceof De?[null,...Pe(t.unwrap())]:t instanceof Cr||t instanceof Tt?Pe(t.unwrap()):t instanceof Pt?Pe(t._def.innerType):[];class Wt extends T{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==v.object)return g(r,{code:y.invalid_type,expected:v.object,received:r.parsedType}),S;const n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(g(r,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const o=new Map;for(const s of r){const i=Pe(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const c of i){if(o.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);o.set(c,s)}}return new Wt({typeName:C.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...A(n)})}}function kr(t,e){const r=Re(t),n=Re(e);if(t===e)return{valid:!0,data:t};if(r===v.object&&n===v.object){const o=R.objectKeys(e),s=R.objectKeys(t).filter(c=>o.indexOf(c)!==-1),i={...t,...e};for(const c of s){const l=kr(t[c],e[c]);if(!l.valid)return{valid:!1};i[c]=l.data}return{valid:!0,data:i}}else if(r===v.array&&n===v.array){if(t.length!==e.length)return{valid:!1};const o=[];for(let s=0;s<t.length;s++){const i=t[s],c=e[s],l=kr(i,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===v.date&&n===v.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class wt extends T{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(wr(s)||wr(i))return S;const c=kr(s.value,i.value);return c.valid?((br(s)||br(i))&&r.dirty(),{status:r.value,value:c.data}):(g(n,{code:y.invalid_intersection_types}),S)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}wt.create=(t,e,r)=>new wt({left:t,right:e,typeName:C.ZodIntersection,...A(r)});class me extends T{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.array)return g(n,{code:y.invalid_type,expected:v.array,received:n.parsedType}),S;if(n.data.length<this._def.items.length)return g(n,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&n.data.length>this._def.items.length&&(g(n,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((i,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new fe(n,i,n.path,c)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>H.mergeArray(r,i)):H.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new me({...this._def,rest:e})}}me.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new me({items:t,typeName:C.ZodTuple,rest:null,...A(e)})};class bt extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.object)return g(n,{code:y.invalid_type,expected:v.object,received:n.parsedType}),S;const o=[],s=this._def.keyType,i=this._def.valueType;for(const c in n.data)o.push({key:s._parse(new fe(n,c,n.path,c)),value:i._parse(new fe(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?H.mergeObjectAsync(r,o):H.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof T?new bt({keyType:e,valueType:r,typeName:C.ZodRecord,...A(n)}):new bt({keyType:oe.create(),valueType:e,typeName:C.ZodRecord,...A(r)})}}class Ht extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.map)return g(n,{code:y.invalid_type,expected:v.map,received:n.parsedType}),S;const o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([c,l],u)=>({key:o._parse(new fe(n,c,n.path,[u,"key"])),value:s._parse(new fe(n,l,n.path,[u,"value"]))}));if(n.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of i){const u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return S;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),c.set(u.value,d.value)}return{status:r.value,value:c}})}else{const c=new Map;for(const l of i){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return S;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),c.set(u.value,d.value)}return{status:r.value,value:c}}}}Ht.create=(t,e,r)=>new Ht({valueType:e,keyType:t,typeName:C.ZodMap,...A(r)});class Ve extends T{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.set)return g(n,{code:y.invalid_type,expected:v.set,received:n.parsedType}),S;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(g(n,{code:y.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(g(n,{code:y.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const s=this._def.valueType;function i(l){const u=new Set;for(const d of l){if(d.status==="aborted")return S;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}const c=[...n.data.values()].map((l,u)=>s._parse(new fe(n,l,n.path,u)));return n.common.async?Promise.all(c).then(l=>i(l)):i(c)}min(e,r){return new Ve({...this._def,minSize:{value:e,message:b.toString(r)}})}max(e,r){return new Ve({...this._def,maxSize:{value:e,message:b.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}Ve.create=(t,e)=>new Ve({valueType:t,minSize:null,maxSize:null,typeName:C.ZodSet,...A(e)});class tt extends T{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==v.function)return g(r,{code:y.invalid_type,expected:v.function,received:r.parsedType}),S;function n(c,l){return Gt({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,zt(),Je].filter(u=>!!u),issueData:{code:y.invalid_arguments,argumentsError:l}})}function o(c,l){return Gt({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,zt(),Je].filter(u=>!!u),issueData:{code:y.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof rt){const c=this;return J(async function(...l){const u=new te([]),d=await c._def.args.parseAsync(l,s).catch(f=>{throw u.addIssue(n(l,f)),u}),p=await Reflect.apply(i,this,d);return await c._def.returns._def.type.parseAsync(p,s).catch(f=>{throw u.addIssue(o(p,f)),u})})}else{const c=this;return J(function(...l){const u=c._def.args.safeParse(l,s);if(!u.success)throw new te([n(l,u.error)]);const d=Reflect.apply(i,this,u.data),p=c._def.returns.safeParse(d,s);if(!p.success)throw new te([o(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new tt({...this._def,args:me.create(e).rest(Ze.create())})}returns(e){return new tt({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new tt({args:e||me.create([]).rest(Ze.create()),returns:r||Ze.create(),typeName:C.ZodFunction,...A(n)})}}class Et extends T{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}Et.create=(t,e)=>new Et({getter:t,typeName:C.ZodLazy,...A(e)});class kt extends T{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return g(r,{received:r.data,code:y.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:e.data}}get value(){return this._def.value}}kt.create=(t,e)=>new kt({value:t,typeName:C.ZodLiteral,...A(e)});function tn(t,e){return new Me({values:t,typeName:C.ZodEnum,...A(e)})}class Me extends T{constructor(){super(...arguments),mt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return g(r,{expected:R.joinValues(n),received:r.parsedType,code:y.invalid_type}),S}if(Bt(this,mt)||Kr(this,mt,new Set(this._def.values)),!Bt(this,mt).has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return g(r,{received:r.data,code:y.invalid_enum_value,options:n}),S}return J(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Me.create(e,{...this._def,...r})}exclude(e,r=this._def){return Me.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}mt=new WeakMap,Me.create=tn;class Ct extends T{constructor(){super(...arguments),ht.set(this,void 0)}_parse(e){const r=R.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==v.string&&n.parsedType!==v.number){const o=R.objectValues(r);return g(n,{expected:R.joinValues(o),received:n.parsedType,code:y.invalid_type}),S}if(Bt(this,ht)||Kr(this,ht,new Set(R.getValidEnumValues(this._def.values))),!Bt(this,ht).has(e.data)){const o=R.objectValues(r);return g(n,{received:n.data,code:y.invalid_enum_value,options:o}),S}return J(e.data)}get enum(){return this._def.values}}ht=new WeakMap,Ct.create=(t,e)=>new Ct({values:t,typeName:C.ZodNativeEnum,...A(e)});class rt extends T{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==v.promise&&r.common.async===!1)return g(r,{code:y.invalid_type,expected:v.promise,received:r.parsedType}),S;const n=r.parsedType===v.promise?r.data:Promise.resolve(r.data);return J(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}rt.create=(t,e)=>new rt({type:t,typeName:C.ZodPromise,...A(e)});class ae extends T{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===C.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{g(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async c=>{if(r.value==="aborted")return S;const l=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return l.status==="aborted"?S:l.status==="dirty"||r.value==="dirty"?Qe(l.value):l});{if(r.value==="aborted")return S;const c=this._def.schema._parseSync({data:i,path:n.path,parent:n});return c.status==="aborted"?S:c.status==="dirty"||r.value==="dirty"?Qe(c.value):c}}if(o.type==="refinement"){const i=c=>{const l=o.refinement(c,s);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){const c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?S:(c.status==="dirty"&&r.dirty(),i(c.value),{status:r.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?S:(c.status==="dirty"&&r.dirty(),i(c.value).then(()=>({status:r.value,value:c.value}))))}if(o.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!pt(i))return i;const c=o.transform(i.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>pt(i)?Promise.resolve(o.transform(i.value,s)).then(c=>({status:r.value,value:c})):i);R.assertNever(o)}}ae.create=(t,e,r)=>new ae({schema:t,typeName:C.ZodEffects,effect:e,...A(r)}),ae.createWithPreprocess=(t,e,r)=>new ae({schema:e,effect:{type:"preprocess",transform:t},typeName:C.ZodEffects,...A(r)});class he extends T{_parse(e){return this._getType(e)===v.undefined?J(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}he.create=(t,e)=>new he({innerType:t,typeName:C.ZodOptional,...A(e)});class De extends T{_parse(e){return this._getType(e)===v.null?J(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}De.create=(t,e)=>new De({innerType:t,typeName:C.ZodNullable,...A(e)});class St extends T{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===v.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}St.create=(t,e)=>new St({innerType:t,typeName:C.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...A(e)});class Pt extends T{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ft(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new te(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new te(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Pt.create=(t,e)=>new Pt({innerType:t,typeName:C.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...A(e)});class Kt extends T{_parse(e){if(this._getType(e)!==v.nan){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.nan,received:n.parsedType}),S}return{status:"valid",value:e.data}}}Kt.create=t=>new Kt({typeName:C.ZodNaN,...A(t)});const us=Symbol("zod_brand");class Cr extends T{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class At extends T{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?S:s.status==="dirty"?(r.dirty(),Qe(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?S:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new At({in:e,out:r,typeName:C.ZodPipeline})}}class Tt extends T{_parse(e){const r=this._def.innerType._parse(e),n=o=>(pt(o)&&(o.value=Object.freeze(o.value)),o);return ft(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}}Tt.create=(t,e)=>new Tt({innerType:t,typeName:C.ZodReadonly,...A(e)});function rn(t,e={},r){return t?Xe.create().superRefine((n,o)=>{var s,i;if(!t(n)){const c=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,l=(i=(s=c.fatal)!==null&&s!==void 0?s:r)!==null&&i!==void 0?i:!0,u=typeof c=="string"?{message:c}:c;o.addIssue({code:"custom",...u,fatal:l})}}):Xe.create()}const ds={object:j.lazycreate};var C;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(C||(C={}));const ps=(t,e={message:`Input not instance of ${t.name}`})=>rn(r=>r instanceof t,e),nn=oe.create,on=Ne.create,fs=Kt.create,ms=Oe.create,sn=yt.create,hs=$e.create,ys=qt.create,_s=_t.create,gs=gt.create,vs=Xe.create,ws=Ze.create,bs=Se.create,Es=Yt.create,ks=se.create,Cs=j.create,Ss=j.strictCreate,Ps=vt.create,As=Wt.create,Ts=wt.create,xs=me.create,Is=bt.create,Rs=Ht.create,Ns=Ve.create,Os=tt.create,Ms=Et.create,Ds=kt.create,Ls=Me.create,js=Ct.create,Fs=rt.create,an=ae.create,Us=he.create,$s=De.create,Zs=ae.createWithPreprocess,Vs=At.create;var a=Object.freeze({__proto__:null,defaultErrorMap:Je,setErrorMap:Yo,getErrorMap:zt,makeIssue:Gt,EMPTY_PATH:Wo,addIssueToContext:g,ParseStatus:H,INVALID:S,DIRTY:Qe,OK:J,isAborted:wr,isDirty:br,isValid:pt,isAsync:ft,get util(){return R},get objectUtil(){return vr},ZodParsedType:v,getParsedType:Re,ZodType:T,datetimeRegex:en,ZodString:oe,ZodNumber:Ne,ZodBigInt:Oe,ZodBoolean:yt,ZodDate:$e,ZodSymbol:qt,ZodUndefined:_t,ZodNull:gt,ZodAny:Xe,ZodUnknown:Ze,ZodNever:Se,ZodVoid:Yt,ZodArray:se,ZodObject:j,ZodUnion:vt,ZodDiscriminatedUnion:Wt,ZodIntersection:wt,ZodTuple:me,ZodRecord:bt,ZodMap:Ht,ZodSet:Ve,ZodFunction:tt,ZodLazy:Et,ZodLiteral:kt,ZodEnum:Me,ZodNativeEnum:Ct,ZodPromise:rt,ZodEffects:ae,ZodTransformer:ae,ZodOptional:he,ZodNullable:De,ZodDefault:St,ZodCatch:Pt,ZodNaN:Kt,BRAND:us,ZodBranded:Cr,ZodPipeline:At,ZodReadonly:Tt,custom:rn,Schema:T,ZodSchema:T,late:ds,get ZodFirstPartyTypeKind(){return C},coerce:{string:t=>oe.create({...t,coerce:!0}),number:t=>Ne.create({...t,coerce:!0}),boolean:t=>yt.create({...t,coerce:!0}),bigint:t=>Oe.create({...t,coerce:!0}),date:t=>$e.create({...t,coerce:!0})},any:vs,array:ks,bigint:ms,boolean:sn,date:hs,discriminatedUnion:As,effect:an,enum:Ls,function:Os,instanceof:ps,intersection:Ts,lazy:Ms,literal:Ds,map:Rs,nan:fs,nativeEnum:js,never:bs,null:gs,nullable:$s,number:on,object:Cs,oboolean:()=>sn().optional(),onumber:()=>on().optional(),optional:Us,ostring:()=>nn().optional(),pipeline:Vs,preprocess:Zs,promise:Fs,record:Is,set:Ns,strictObject:Ss,string:nn,symbol:ys,transformer:an,tuple:xs,undefined:_s,union:Ps,unknown:ws,void:Es,NEVER:S,ZodIssueCode:y,quotelessJson:qo,ZodError:te});const zs=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()}),Gs=a.array(zs),Bs=a.object({code:a.string(),message:a.string(),path:a.array(a.string())}),qs=a.array(Bs),Ys={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},Sr=t=>{const e=t.toLowerCase().trim();return Ys[e]??t},Ws=t=>{try{return typeof JSON.parse(t)=="object"}catch{return!1}},Hs=t=>t.length===1?Sr(t[0].msg):`Please fix the following errors:
2
- ${t.map(r=>`• ${Sr(r.msg)}`).join(`
3
- `)}`,Ks=t=>`Encountered the following errors:
1
+ (function(Ce,He){typeof exports=="object"&&typeof module<"u"?He(exports):typeof define=="function"&&define.amd?define(["exports"],He):(Ce=typeof globalThis<"u"?globalThis:Ce||self,He(Ce.OpenPay={}))})(this,function(Ce){"use strict";var Go;const He="https://cde.getopenpay.com";var R;(function(t){t.assertEqual=o=>o;function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{const s={};for(const i of o)s[i]=i;return s},t.getValidEnumValues=o=>{const s=t.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),i={};for(const c of s)i[c]=o[c];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(const i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(R||(R={}));var gr;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(gr||(gr={}));const v=R.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Re=t=>{switch(typeof t){case"undefined":return v.undefined;case"string":return v.string;case"number":return isNaN(t)?v.nan:v.number;case"boolean":return v.boolean;case"function":return v.function;case"bigint":return v.bigint;case"symbol":return v.symbol;case"object":return Array.isArray(t)?v.array:t===null?v.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?v.promise:typeof Map<"u"&&t instanceof Map?v.map:typeof Set<"u"&&t instanceof Set?v.set:typeof Date<"u"&&t instanceof Date?v.date:v.object;default:return v.unknown}},y=R.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Bo=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class te extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let c=n,l=0;for(;l<i.path.length;){const u=i.path[l];l===i.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(r(i))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};return o(this),n}static assert(e){if(!(e instanceof te))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,R.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const o of this.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}te.create=t=>new te(t);const Ke=(t,e)=>{let r;switch(t.code){case y.invalid_type:t.received===v.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case y.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,R.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:r=`Unrecognized key(s) in object: ${R.joinValues(t.keys,", ")}`;break;case y.invalid_union:r="Invalid input";break;case y.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${R.joinValues(t.options)}`;break;case y.invalid_enum_value:r=`Invalid enum value. Expected ${R.joinValues(t.options)}, received '${t.received}'`;break;case y.invalid_arguments:r="Invalid function arguments";break;case y.invalid_return_type:r="Invalid function return type";break;case y.invalid_date:r="Invalid date";break;case y.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:R.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case y.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case y.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case y.custom:r="Invalid input";break;case y.invalid_intersection_types:r="Intersection results could not be merged";break;case y.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case y.not_finite:r="Number must be finite";break;default:r=e.defaultError,R.assertNever(t)}return{message:r}};let Wr=Ke;function qo(t){Wr=t}function Vt(){return Wr}const zt=t=>{const{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=n.filter(u=>!!u).slice().reverse();for(const u of l)c=u(i,{data:e,defaultError:c}).message;return{...o,path:s,message:c}},Yo=[];function g(t,e){const r=Vt(),n=zt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ke?void 0:Ke].filter(o=>!!o)});t.common.issues.push(n)}class H{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const o of r){if(o.status==="aborted")return S;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const o of r){const s=await o.key,i=await o.value;n.push({key:s,value:i})}return H.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const o of r){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return S;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}}const S=Object.freeze({status:"aborted"}),Je=t=>({status:"dirty",value:t}),J=t=>({status:"valid",value:t}),vr=t=>t.status==="aborted",wr=t=>t.status==="dirty",dt=t=>t.status==="valid",pt=t=>typeof Promise<"u"&&t instanceof Promise;function Gt(t,e,r,n){if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function Hr(t,e,r,n,o){if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,r),r}typeof SuppressedError=="function"&&SuppressedError;var b;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(b||(b={}));var ft,mt;class fe{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Kr=(t,e)=>{if(dt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new te(t.common.issues);return this._error=r,this._error}}};function A(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,c)=>{var l,u;const{message:d}=t;return i.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(l=d??n)!==null&&l!==void 0?l:c.defaultError}:i.code!=="invalid_type"?{message:c.defaultError}:{message:(u=d??r)!==null&&u!==void 0?u:c.defaultError}},description:o}}class T{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return Re(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new H,ctx:{common:e.parent.common,data:e.data,parsedType:Re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(pt(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){var n;const o={common:{issues:[],async:(n=r==null?void 0:r.async)!==null&&n!==void 0?n:!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)},s=this._parseSync({data:e,path:o.path,parent:o});return Kr(o,s)}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(pt(o)?o:Promise.resolve(o));return Kr(n,s)}refine(e,r){const n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{const i=e(o),c=()=>s.addIssue({code:y.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(c(),!1)):i?!0:(c(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new ae({schema:this,typeName:C.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return he.create(this,this._def)}nullable(){return De.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return se.create(this,this._def)}promise(){return tt.create(this,this._def)}or(e){return gt.create([this,e],this._def)}and(e){return vt.create(this,e,this._def)}transform(e){return new ae({...A(this._def),schema:this,typeName:C.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Ct({...A(this._def),innerType:this,defaultValue:r,typeName:C.ZodDefault})}brand(){return new kr({typeName:C.ZodBranded,type:this,...A(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new St({...A(this._def),innerType:this,catchValue:r,typeName:C.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Pt.create(this,e)}readonly(){return At.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Wo=/^c[^\s-]{8,}$/i,Ho=/^[0-9a-z]+$/,Ko=/^[0-9A-HJKMNP-TV-Z]{26}$/,Jo=/^[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,Qo=/^[a-z0-9_-]{21}$/i,Xo=/^[-+]?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)?)??$/,es=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ts="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let br;const rs=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ns=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,os=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Jr="((\\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])))",ss=new RegExp(`^${Jr}$`);function Qr(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function as(t){return new RegExp(`^${Qr(t)}$`)}function Xr(t){let e=`${Jr}T${Qr(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function is(t,e){return!!((e==="v4"||!e)&&rs.test(t)||(e==="v6"||!e)&&ns.test(t))}class oe extends T{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==v.string){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.string,received:s.parsedType}),S}const n=new H;let o;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const i=e.data.length>s.value,c=e.data.length<s.value;(i||c)&&(o=this._getOrReturnCtx(e,o),i?g(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&g(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")es.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"email",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")br||(br=new RegExp(ts,"u")),br.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"emoji",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Jo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"uuid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Qo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"nanoid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Wo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Ho.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid2",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Ko.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ulid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),g(o,{validation:"url",code:y.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"regex",code:y.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Xr(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?ss.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?as(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Xo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"duration",code:y.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?is(e.data,s.version)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ip",code:y.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?os.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"base64",code:y.invalid_string,message:s.message}),n.dirty()):R.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:y.invalid_string,...b.errToObj(n)})}_addCheck(e){return new oe({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...b.errToObj(e)})}url(e){return this._addCheck({kind:"url",...b.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...b.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...b.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...b.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...b.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...b.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...b.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...b.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...b.errToObj(e)})}datetime(e){var r,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:(r=e==null?void 0:e.offset)!==null&&r!==void 0?r:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...b.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...b.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...b.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...b.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...b.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...b.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...b.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...b.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...b.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...b.errToObj(r)})}nonempty(e){return this.min(1,b.errToObj(e))}trim(){return new oe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new oe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new oe({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}oe.create=t=>{var e;return new oe({checks:[],typeName:C.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...A(t)})};function cs(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=parseInt(t.toFixed(o).replace(".","")),i=parseInt(e.toFixed(o).replace(".",""));return s%i/Math.pow(10,o)}class Ne extends T{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==v.number){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.number,received:s.parsedType}),S}let n;const o=new H;for(const s of this._def.checks)s.kind==="int"?R.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:y.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?cs(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:y.not_finite,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,b.toString(r))}gt(e,r){return this.setLimit("min",e,!1,b.toString(r))}lte(e,r){return this.setLimit("max",e,!0,b.toString(r))}lt(e,r){return this.setLimit("max",e,!1,b.toString(r))}setLimit(e,r,n,o){return new Ne({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:b.toString(o)}]})}_addCheck(e){return new Ne({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:b.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:b.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&R.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}Ne.create=t=>new Ne({checks:[],typeName:C.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...A(t)});class Oe extends T{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==v.bigint){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.bigint,received:s.parsedType}),S}let n;const o=new H;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,b.toString(r))}gt(e,r){return this.setLimit("min",e,!1,b.toString(r))}lte(e,r){return this.setLimit("max",e,!0,b.toString(r))}lt(e,r){return this.setLimit("max",e,!1,b.toString(r))}setLimit(e,r,n,o){return new Oe({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:b.toString(o)}]})}_addCheck(e){return new Oe({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}Oe.create=t=>{var e;return new Oe({checks:[],typeName:C.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...A(t)})};class ht extends T{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==v.boolean){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.boolean,received:n.parsedType}),S}return J(e.data)}}ht.create=t=>new ht({typeName:C.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...A(t)});class Ue extends T{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==v.date){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.date,received:s.parsedType}),S}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_date}),S}const n=new H;let o;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):R.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ue({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:b.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:b.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}Ue.create=t=>new Ue({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:C.ZodDate,...A(t)});class Bt extends T{_parse(e){if(this._getType(e)!==v.symbol){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.symbol,received:n.parsedType}),S}return J(e.data)}}Bt.create=t=>new Bt({typeName:C.ZodSymbol,...A(t)});class yt extends T{_parse(e){if(this._getType(e)!==v.undefined){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.undefined,received:n.parsedType}),S}return J(e.data)}}yt.create=t=>new yt({typeName:C.ZodUndefined,...A(t)});class _t extends T{_parse(e){if(this._getType(e)!==v.null){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.null,received:n.parsedType}),S}return J(e.data)}}_t.create=t=>new _t({typeName:C.ZodNull,...A(t)});class Qe extends T{constructor(){super(...arguments),this._any=!0}_parse(e){return J(e.data)}}Qe.create=t=>new Qe({typeName:C.ZodAny,...A(t)});class $e extends T{constructor(){super(...arguments),this._unknown=!0}_parse(e){return J(e.data)}}$e.create=t=>new $e({typeName:C.ZodUnknown,...A(t)});class Se extends T{_parse(e){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.never,received:r.parsedType}),S}}Se.create=t=>new Se({typeName:C.ZodNever,...A(t)});class qt extends T{_parse(e){if(this._getType(e)!==v.undefined){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.void,received:n.parsedType}),S}return J(e.data)}}qt.create=t=>new qt({typeName:C.ZodVoid,...A(t)});class se extends T{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==v.array)return g(r,{code:y.invalid_type,expected:v.array,received:r.parsedType}),S;if(o.exactLength!==null){const i=r.data.length>o.exactLength.value,c=r.data.length<o.exactLength.value;(i||c)&&(g(r,{code:i?y.too_big:y.too_small,minimum:c?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(g(r,{code:y.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(g(r,{code:y.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,c)=>o.type._parseAsync(new fe(r,i,r.path,c)))).then(i=>H.mergeArray(n,i));const s=[...r.data].map((i,c)=>o.type._parseSync(new fe(r,i,r.path,c)));return H.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new se({...this._def,minLength:{value:e,message:b.toString(r)}})}max(e,r){return new se({...this._def,maxLength:{value:e,message:b.toString(r)}})}length(e,r){return new se({...this._def,exactLength:{value:e,message:b.toString(r)}})}nonempty(e){return this.min(1,e)}}se.create=(t,e)=>new se({type:t,minLength:null,maxLength:null,exactLength:null,typeName:C.ZodArray,...A(e)});function Xe(t){if(t instanceof j){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=he.create(Xe(n))}return new j({...t._def,shape:()=>e})}else return t instanceof se?new se({...t._def,type:Xe(t.element)}):t instanceof he?he.create(Xe(t.unwrap())):t instanceof De?De.create(Xe(t.unwrap())):t instanceof me?me.create(t.items.map(e=>Xe(e))):t}class j extends T{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(),r=R.objectKeys(e);return this._cached={shape:e,keys:r}}_parse(e){if(this._getType(e)!==v.object){const u=this._getOrReturnCtx(e);return g(u,{code:y.invalid_type,expected:v.object,received:u.parsedType}),S}const{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof Se&&this._def.unknownKeys==="strip"))for(const u in o.data)i.includes(u)||c.push(u);const l=[];for(const u of i){const d=s[u],p=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new fe(o,p,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Se){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of c)l.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(u==="strict")c.length>0&&(g(o,{code:y.unrecognized_keys,keys:c}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const d of c){const p=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new fe(o,p,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of l){const p=await d.key,_=await d.value;u.push({key:p,value:_,alwaysSet:d.alwaysSet})}return u}).then(u=>H.mergeObjectSync(n,u)):H.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return b.errToObj,new j({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{var o,s,i,c;const l=(i=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,r,n).message)!==null&&i!==void 0?i:n.defaultError;return r.code==="unrecognized_keys"?{message:(c=b.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new j({...this._def,unknownKeys:"strip"})}passthrough(){return new j({...this._def,unknownKeys:"passthrough"})}extend(e){return new j({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new j({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:C.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new j({...this._def,catchall:e})}pick(e){const r={};return R.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new j({...this._def,shape:()=>r})}omit(e){const r={};return R.objectKeys(this.shape).forEach(n=>{e[n]||(r[n]=this.shape[n])}),new j({...this._def,shape:()=>r})}deepPartial(){return Xe(this)}partial(e){const r={};return R.objectKeys(this.shape).forEach(n=>{const o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}),new j({...this._def,shape:()=>r})}required(e){const r={};return R.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof he;)s=s._def.innerType;r[n]=s}}),new j({...this._def,shape:()=>r})}keyof(){return en(R.objectKeys(this.shape))}}j.create=(t,e)=>new j({shape:()=>t,unknownKeys:"strip",catchall:Se.create(),typeName:C.ZodObject,...A(e)}),j.strictCreate=(t,e)=>new j({shape:()=>t,unknownKeys:"strict",catchall:Se.create(),typeName:C.ZodObject,...A(e)}),j.lazycreate=(t,e)=>new j({shape:t,unknownKeys:"strip",catchall:Se.create(),typeName:C.ZodObject,...A(e)});class gt extends T{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return r.common.issues.push(...c.ctx.common.issues),c.result;const i=s.map(c=>new te(c.ctx.common.issues));return g(r,{code:y.invalid_union,unionErrors:i}),S}if(r.common.async)return Promise.all(n.map(async s=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s;const i=[];for(const l of n){const u={...r,common:{...r.common,issues:[]},parent:null},d=l._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const c=i.map(l=>new te(l));return g(r,{code:y.invalid_union,unionErrors:c}),S}}get options(){return this._def.options}}gt.create=(t,e)=>new gt({options:t,typeName:C.ZodUnion,...A(e)});const Pe=t=>t instanceof bt?Pe(t.schema):t instanceof ae?Pe(t.innerType()):t instanceof Et?[t.value]:t instanceof Me?t.options:t instanceof kt?R.objectValues(t.enum):t instanceof Ct?Pe(t._def.innerType):t instanceof yt?[void 0]:t instanceof _t?[null]:t instanceof he?[void 0,...Pe(t.unwrap())]:t instanceof De?[null,...Pe(t.unwrap())]:t instanceof kr||t instanceof At?Pe(t.unwrap()):t instanceof St?Pe(t._def.innerType):[];class Yt extends T{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==v.object)return g(r,{code:y.invalid_type,expected:v.object,received:r.parsedType}),S;const n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(g(r,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const o=new Map;for(const s of r){const i=Pe(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const c of i){if(o.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);o.set(c,s)}}return new Yt({typeName:C.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...A(n)})}}function Er(t,e){const r=Re(t),n=Re(e);if(t===e)return{valid:!0,data:t};if(r===v.object&&n===v.object){const o=R.objectKeys(e),s=R.objectKeys(t).filter(c=>o.indexOf(c)!==-1),i={...t,...e};for(const c of s){const l=Er(t[c],e[c]);if(!l.valid)return{valid:!1};i[c]=l.data}return{valid:!0,data:i}}else if(r===v.array&&n===v.array){if(t.length!==e.length)return{valid:!1};const o=[];for(let s=0;s<t.length;s++){const i=t[s],c=e[s],l=Er(i,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===v.date&&n===v.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class vt extends T{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(vr(s)||vr(i))return S;const c=Er(s.value,i.value);return c.valid?((wr(s)||wr(i))&&r.dirty(),{status:r.value,value:c.data}):(g(n,{code:y.invalid_intersection_types}),S)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}vt.create=(t,e,r)=>new vt({left:t,right:e,typeName:C.ZodIntersection,...A(r)});class me extends T{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.array)return g(n,{code:y.invalid_type,expected:v.array,received:n.parsedType}),S;if(n.data.length<this._def.items.length)return g(n,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&n.data.length>this._def.items.length&&(g(n,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((i,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new fe(n,i,n.path,c)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>H.mergeArray(r,i)):H.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new me({...this._def,rest:e})}}me.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new me({items:t,typeName:C.ZodTuple,rest:null,...A(e)})};class wt extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.object)return g(n,{code:y.invalid_type,expected:v.object,received:n.parsedType}),S;const o=[],s=this._def.keyType,i=this._def.valueType;for(const c in n.data)o.push({key:s._parse(new fe(n,c,n.path,c)),value:i._parse(new fe(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?H.mergeObjectAsync(r,o):H.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof T?new wt({keyType:e,valueType:r,typeName:C.ZodRecord,...A(n)}):new wt({keyType:oe.create(),valueType:e,typeName:C.ZodRecord,...A(r)})}}class Wt extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.map)return g(n,{code:y.invalid_type,expected:v.map,received:n.parsedType}),S;const o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([c,l],u)=>({key:o._parse(new fe(n,c,n.path,[u,"key"])),value:s._parse(new fe(n,l,n.path,[u,"value"]))}));if(n.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of i){const u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return S;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),c.set(u.value,d.value)}return{status:r.value,value:c}})}else{const c=new Map;for(const l of i){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return S;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),c.set(u.value,d.value)}return{status:r.value,value:c}}}}Wt.create=(t,e,r)=>new Wt({valueType:e,keyType:t,typeName:C.ZodMap,...A(r)});class Ze extends T{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.set)return g(n,{code:y.invalid_type,expected:v.set,received:n.parsedType}),S;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(g(n,{code:y.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(g(n,{code:y.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const s=this._def.valueType;function i(l){const u=new Set;for(const d of l){if(d.status==="aborted")return S;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}const c=[...n.data.values()].map((l,u)=>s._parse(new fe(n,l,n.path,u)));return n.common.async?Promise.all(c).then(l=>i(l)):i(c)}min(e,r){return new Ze({...this._def,minSize:{value:e,message:b.toString(r)}})}max(e,r){return new Ze({...this._def,maxSize:{value:e,message:b.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}Ze.create=(t,e)=>new Ze({valueType:t,minSize:null,maxSize:null,typeName:C.ZodSet,...A(e)});class et extends T{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==v.function)return g(r,{code:y.invalid_type,expected:v.function,received:r.parsedType}),S;function n(c,l){return zt({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Vt(),Ke].filter(u=>!!u),issueData:{code:y.invalid_arguments,argumentsError:l}})}function o(c,l){return zt({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Vt(),Ke].filter(u=>!!u),issueData:{code:y.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof tt){const c=this;return J(async function(...l){const u=new te([]),d=await c._def.args.parseAsync(l,s).catch(f=>{throw u.addIssue(n(l,f)),u}),p=await Reflect.apply(i,this,d);return await c._def.returns._def.type.parseAsync(p,s).catch(f=>{throw u.addIssue(o(p,f)),u})})}else{const c=this;return J(function(...l){const u=c._def.args.safeParse(l,s);if(!u.success)throw new te([n(l,u.error)]);const d=Reflect.apply(i,this,u.data),p=c._def.returns.safeParse(d,s);if(!p.success)throw new te([o(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new et({...this._def,args:me.create(e).rest($e.create())})}returns(e){return new et({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new et({args:e||me.create([]).rest($e.create()),returns:r||$e.create(),typeName:C.ZodFunction,...A(n)})}}class bt extends T{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}bt.create=(t,e)=>new bt({getter:t,typeName:C.ZodLazy,...A(e)});class Et extends T{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return g(r,{received:r.data,code:y.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:e.data}}get value(){return this._def.value}}Et.create=(t,e)=>new Et({value:t,typeName:C.ZodLiteral,...A(e)});function en(t,e){return new Me({values:t,typeName:C.ZodEnum,...A(e)})}class Me extends T{constructor(){super(...arguments),ft.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return g(r,{expected:R.joinValues(n),received:r.parsedType,code:y.invalid_type}),S}if(Gt(this,ft)||Hr(this,ft,new Set(this._def.values)),!Gt(this,ft).has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return g(r,{received:r.data,code:y.invalid_enum_value,options:n}),S}return J(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Me.create(e,{...this._def,...r})}exclude(e,r=this._def){return Me.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}ft=new WeakMap,Me.create=en;class kt extends T{constructor(){super(...arguments),mt.set(this,void 0)}_parse(e){const r=R.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==v.string&&n.parsedType!==v.number){const o=R.objectValues(r);return g(n,{expected:R.joinValues(o),received:n.parsedType,code:y.invalid_type}),S}if(Gt(this,mt)||Hr(this,mt,new Set(R.getValidEnumValues(this._def.values))),!Gt(this,mt).has(e.data)){const o=R.objectValues(r);return g(n,{received:n.data,code:y.invalid_enum_value,options:o}),S}return J(e.data)}get enum(){return this._def.values}}mt=new WeakMap,kt.create=(t,e)=>new kt({values:t,typeName:C.ZodNativeEnum,...A(e)});class tt extends T{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==v.promise&&r.common.async===!1)return g(r,{code:y.invalid_type,expected:v.promise,received:r.parsedType}),S;const n=r.parsedType===v.promise?r.data:Promise.resolve(r.data);return J(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}tt.create=(t,e)=>new tt({type:t,typeName:C.ZodPromise,...A(e)});class ae extends T{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===C.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{g(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async c=>{if(r.value==="aborted")return S;const l=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return l.status==="aborted"?S:l.status==="dirty"||r.value==="dirty"?Je(l.value):l});{if(r.value==="aborted")return S;const c=this._def.schema._parseSync({data:i,path:n.path,parent:n});return c.status==="aborted"?S:c.status==="dirty"||r.value==="dirty"?Je(c.value):c}}if(o.type==="refinement"){const i=c=>{const l=o.refinement(c,s);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){const c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?S:(c.status==="dirty"&&r.dirty(),i(c.value),{status:r.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?S:(c.status==="dirty"&&r.dirty(),i(c.value).then(()=>({status:r.value,value:c.value}))))}if(o.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!dt(i))return i;const c=o.transform(i.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>dt(i)?Promise.resolve(o.transform(i.value,s)).then(c=>({status:r.value,value:c})):i);R.assertNever(o)}}ae.create=(t,e,r)=>new ae({schema:t,typeName:C.ZodEffects,effect:e,...A(r)}),ae.createWithPreprocess=(t,e,r)=>new ae({schema:e,effect:{type:"preprocess",transform:t},typeName:C.ZodEffects,...A(r)});class he extends T{_parse(e){return this._getType(e)===v.undefined?J(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}he.create=(t,e)=>new he({innerType:t,typeName:C.ZodOptional,...A(e)});class De extends T{_parse(e){return this._getType(e)===v.null?J(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}De.create=(t,e)=>new De({innerType:t,typeName:C.ZodNullable,...A(e)});class Ct extends T{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===v.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}Ct.create=(t,e)=>new Ct({innerType:t,typeName:C.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...A(e)});class St extends T{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return pt(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new te(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new te(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}St.create=(t,e)=>new St({innerType:t,typeName:C.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...A(e)});class Ht extends T{_parse(e){if(this._getType(e)!==v.nan){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.nan,received:n.parsedType}),S}return{status:"valid",value:e.data}}}Ht.create=t=>new Ht({typeName:C.ZodNaN,...A(t)});const ls=Symbol("zod_brand");class kr extends T{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Pt extends T{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?S:s.status==="dirty"?(r.dirty(),Je(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?S:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new Pt({in:e,out:r,typeName:C.ZodPipeline})}}class At extends T{_parse(e){const r=this._def.innerType._parse(e),n=o=>(dt(o)&&(o.value=Object.freeze(o.value)),o);return pt(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}}At.create=(t,e)=>new At({innerType:t,typeName:C.ZodReadonly,...A(e)});function tn(t,e={},r){return t?Qe.create().superRefine((n,o)=>{var s,i;if(!t(n)){const c=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,l=(i=(s=c.fatal)!==null&&s!==void 0?s:r)!==null&&i!==void 0?i:!0,u=typeof c=="string"?{message:c}:c;o.addIssue({code:"custom",...u,fatal:l})}}):Qe.create()}const us={object:j.lazycreate};var C;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(C||(C={}));const ds=(t,e={message:`Input not instance of ${t.name}`})=>tn(r=>r instanceof t,e),rn=oe.create,nn=Ne.create,ps=Ht.create,fs=Oe.create,on=ht.create,ms=Ue.create,hs=Bt.create,ys=yt.create,_s=_t.create,gs=Qe.create,vs=$e.create,ws=Se.create,bs=qt.create,Es=se.create,ks=j.create,Cs=j.strictCreate,Ss=gt.create,Ps=Yt.create,As=vt.create,Ts=me.create,xs=wt.create,Is=Wt.create,Rs=Ze.create,Ns=et.create,Os=bt.create,Ms=Et.create,Ds=Me.create,Ls=kt.create,js=tt.create,sn=ae.create,Fs=he.create,Us=De.create,$s=ae.createWithPreprocess,Zs=Pt.create;var a=Object.freeze({__proto__:null,defaultErrorMap:Ke,setErrorMap:qo,getErrorMap:Vt,makeIssue:zt,EMPTY_PATH:Yo,addIssueToContext:g,ParseStatus:H,INVALID:S,DIRTY:Je,OK:J,isAborted:vr,isDirty:wr,isValid:dt,isAsync:pt,get util(){return R},get objectUtil(){return gr},ZodParsedType:v,getParsedType:Re,ZodType:T,datetimeRegex:Xr,ZodString:oe,ZodNumber:Ne,ZodBigInt:Oe,ZodBoolean:ht,ZodDate:Ue,ZodSymbol:Bt,ZodUndefined:yt,ZodNull:_t,ZodAny:Qe,ZodUnknown:$e,ZodNever:Se,ZodVoid:qt,ZodArray:se,ZodObject:j,ZodUnion:gt,ZodDiscriminatedUnion:Yt,ZodIntersection:vt,ZodTuple:me,ZodRecord:wt,ZodMap:Wt,ZodSet:Ze,ZodFunction:et,ZodLazy:bt,ZodLiteral:Et,ZodEnum:Me,ZodNativeEnum:kt,ZodPromise:tt,ZodEffects:ae,ZodTransformer:ae,ZodOptional:he,ZodNullable:De,ZodDefault:Ct,ZodCatch:St,ZodNaN:Ht,BRAND:ls,ZodBranded:kr,ZodPipeline:Pt,ZodReadonly:At,custom:tn,Schema:T,ZodSchema:T,late:us,get ZodFirstPartyTypeKind(){return C},coerce:{string:t=>oe.create({...t,coerce:!0}),number:t=>Ne.create({...t,coerce:!0}),boolean:t=>ht.create({...t,coerce:!0}),bigint:t=>Oe.create({...t,coerce:!0}),date:t=>Ue.create({...t,coerce:!0})},any:gs,array:Es,bigint:fs,boolean:on,date:ms,discriminatedUnion:Ps,effect:sn,enum:Ds,function:Ns,instanceof:ds,intersection:As,lazy:Os,literal:Ms,map:Is,nan:ps,nativeEnum:Ls,never:ws,null:_s,nullable:Us,number:nn,object:ks,oboolean:()=>on().optional(),onumber:()=>nn().optional(),optional:Fs,ostring:()=>rn().optional(),pipeline:Zs,preprocess:$s,promise:js,record:xs,set:Rs,strictObject:Cs,string:rn,symbol:hs,transformer:sn,tuple:Ts,undefined:ys,union:Ss,unknown:vs,void:bs,NEVER:S,ZodIssueCode:y,quotelessJson:Bo,ZodError:te});const Vs=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()}),zs=a.array(Vs),Gs=a.object({code:a.string(),message:a.string(),path:a.array(a.string())}),Bs=a.array(Gs),qs={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},Cr=t=>{const e=t.toLowerCase().trim();return qs[e]??t},Ys=t=>{try{return typeof JSON.parse(t)=="object"}catch{return!1}},Ws=t=>t.length===1?Cr(t[0].msg):`Please fix the following errors:
2
+ ${t.map(r=>`• ${Cr(r.msg)}`).join(`
3
+ `)}`,Hs=t=>`Encountered the following errors:
4
4
  ${t.map(r=>`- ${r.path.join("/")}: ${r.message}`).join(`
5
- `)}`,ne=t=>{if(t instanceof Error)if(Ws(t.message)){const e=JSON.parse(t.message);return Gs.safeParse(e).success?Hs(e):qs.safeParse(e).success?Ks(e):(console.warn(`Encountered unknown stringified JSON object:
6
- ${t.message}`),t.message)}else return Sr(t.message);if(typeof t=="object")try{return JSON.stringify(t)}catch(e){return e+""}else return t+""},Js=(t,e,r)=>(...n)=>{try{return e(...n)}catch(o){r(`[form] Error running callback (${t}):`,o);return}};var re=(t=>(t.pockytPaypal="pockyt-paypal",t.airwallexGooglePay="airwallex-google-pay",t.airwallexApplePay="airwallex-apple-pay",t.authorizenetGooglePay="authorizenet-google-pay",t.authorizenetApplePay="authorizenet-apple-pay",t.loopCrypto="loop-crypto",t))(re||{});const Qs=a.nativeEnum(re),Z=a.string().trim().min(1,{message:"Cannot be blank"}),M=a.string().trim().optional(),Q=t=>a.nullable(t.optional());var m=(t=>(t.FIRST_NAME="firstName",t.LAST_NAME="lastName",t.EMAIL="email",t.ZIP_CODE="zipCode",t.CITY="city",t.STATE="state",t.COUNTRY="country",t.ADDRESS="address",t.PHONE="phone",t.PROMOTION_CODE="promotionCode",t))(m||{});const cn=a.nativeEnum(m);var ln=(t=>(t.CARD_NUMBER="cardNumber",t.CARD_EXPIRY="cardExpiry",t.CARD_CVC="cardCvc",t))(ln||{});const un=a.nativeEnum(ln),dn=a.union([cn,un]);var ye=(t=>(t.CARD="card",t.CARD_NUMBER="card-number",t.CARD_EXPIRY="card-expiry",t.CARD_CVC="card-cvc",t.CDE_BRIDGE="cde-bridge",t))(ye||{});const Xs=a.nativeEnum(ye),Jt=a.object({provider:a.string(),processor_name:Q(a.string()),metadata:Q(a.record(a.string(),a.any()))}),ea=a.object({id:a.string()});a.object({cardNumber:M,expiry:M,cvc:M}),a.object({backgroundColor:M,color:M,fontFamily:M,fontSize:M,fontWeight:M,margin:M,padding:M,letterSpacing:M,lineHeight:M,hideIcon:M});const ie=a.enum(["LAYOUT","LOADED","BLUR","FOCUS","CHANGE","TOKENIZE_STARTED","CHECKOUT_STARTED","PAYMENT_FLOW_STARTED","TOKENIZE_SUCCESS","CHECKOUT_SUCCESS","LOAD_ERROR","VALIDATION_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR","SETUP_PAYMENT_METHOD_SUCCESS","TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),ta=ie.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),ra=a.object({type:ta}),na=ie.extract(["BLUR","FOCUS","CHANGE"]),oa=a.object({type:na,elementType:un,errors:a.array(a.string()).optional()}),sa=ie.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),aa=a.object({type:sa,message:Z,headers:a.record(a.string(),a.string()).optional()}),ia=ie.extract(["VALIDATION_ERROR"]),ca=a.object({type:ia,elementType:dn,errors:a.array(a.string())}),la=a.object({type:a.literal(ie.enum.LAYOUT),height:Z}),ua=a.object({type:a.literal(ie.enum.LOADED),sessionId:Z,totalAmountAtoms:a.number(),currency:M,checkoutPaymentMethods:a.array(Jt)}),da=a.object({type:a.literal(ie.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:a.record(a.string(),a.any()),paymentFlowMetadata:a.any().optional(),startPFMetadata:a.optional(a.record(a.string(),a.any()))}),pa=a.object({type:a.literal(ie.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:a.string()}),xt=a.object({firstName:Z,lastName:Z,email:Z,zipCode:Z,country:Z,promotionCode:M}),fa=a.object({firstName:M,lastName:M,email:Z,zipCode:Z,country:Z,promotionCode:M,address:M,city:M,state:M}),ma=ie.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),ha=a.object({type:ma,sessionId:Z,checkoutPaymentMethod:Jt,paymentFlowMetadata:a.any().optional(),doNotUseLegacyCCFlow:a.boolean().optional(),existingCCPMId:M}).extend(xt.shape),ya=a.object({type:a.literal(ie.enum.TOKENIZE_SUCCESS),isReadyForCheckout:a.boolean()}),_a=a.object({type:a.literal(ie.enum.CHECKOUT_SUCCESS),invoiceUrls:a.array(a.string()),subscriptionIds:a.array(a.string()),customerId:a.string()}),ga=a.discriminatedUnion("type",[ra,oa,aa,ca,la,ua,ha,ya,_a,da,pa]),va=a.object({payload:ga,nonce:Z,formId:Z,elementId:Z});a.object({amountAtom:a.number(),currency:Z}),a.enum(["apple_pay","google_pay"]),a.object({secure_token:a.string(),promotion_code:a.string().optional()}),a.object({secure_token:a.string(),existing_cc_pm_id:Q(a.string()),their_pm_id:Q(a.string()),checkout_attempt_id:Q(a.string()),processor_specific_metadata:Q(a.record(a.string(),a.any()))});const Pr=a.object({invoice_urls:a.array(a.string()),subscription_ids:a.array(a.string()),customer_id:a.string(),processors_used:Q(a.array(a.string()))}),wa=a.object({elementType:a.string(),errors:a.array(a.string())});a.object({session_id:a.string()});const ba=a.object({success:a.literal(!1),error_type:a.literal("validation_error"),errors:a.array(wa)}),Ea=a.discriminatedUnion("success",[a.object({success:a.literal(!0)}),ba]);a.object({session_id:a.string(),checkout_payment_method:Jt,non_cde_form_fields:xt,do_not_use_legacy_cc_flow:a.boolean().optional(),existing_cc_pm_id:Q(a.string()),extra_metadata:a.record(a.string(),a.any())}),a.object({session_id:a.string(),checkout_payment_method:Jt,non_cde_form_fields:xt,extra_metadata:a.record(a.string(),a.any()).optional()});var V=(t=>(t.SUCCESS="success",t.FAILURE="failure",t.CANCELLED="cancelled",t))(V||{});const ka=a.object({status:a.enum(["success","failure","cancelled"]),href:a.string().optional().nullable()});a.object({href:a.string().optional().nullable()});const Ca=a.object({type:a.string(),redirect_url:a.string(),initial_intent_id:a.string(),consent_id:a.string(),their_pm_id:a.string().optional()}),pn=a.object({type:a.string(),redirect_url:Q(a.string()),initial_intent_id:Q(a.string()),consent_id:Q(a.string()),their_pm_id:Q(a.string()),payment_session:Q(a.record(a.string(),a.any()))}),Sa=a.discriminatedUnion("present",[a.object({present:a.literal(!0),href:a.string()}),a.object({present:a.literal(!1)})]),Pa=a.object({payment_methods:a.array(ea),pay_first_success_response:Q(Pr),required_user_actions:Q(a.array(pn))}),fn=t=>{const e={};return Object.entries(t).forEach(([r,n])=>{try{const o=cn.parse(r);Array.isArray(n)?e[o]=n:Array.isArray(n._errors)&&(e[o]=n._errors)}catch{return}}),e},Aa=a.object({stripe_pk:a.string(),client_secret:a.string(),stripe_pm_id:a.string()}),Ta=a.object({type:a.string(),client_secret:a.string(),stripe_pk:a.string()}),xa={usd:"usd",brl:"brl"},Qt=async t=>{for(let r=0;r<10;r++)mn()||await Ar(500);if(!mn())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(t)},Ia=async(t,e)=>{const r=await Qt(t);return{elements:r.elements(e),stripe:r}},Ra=async(t,e,r,n,o)=>{const s=await Qt(t),i=xa[r.toLowerCase().trim()];return s.paymentRequest({country:"US",currency:i,total:{label:"Total",amount:e,pending:n},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},Ar=t=>new Promise(e=>{setTimeout(e,t)}),mn=()=>"Stripe"in window,Na=async t=>new Promise((e,r)=>{try{t.on("paymentmethod",async n=>{console.log("paymentmethod EVT:: ",n),e(n)}),t.on("token",async n=>{console.log("token EVT:: ",n)}),t.on("cancel",()=>{r(new Error("Payment cancelled, please click Submit again to pay"))})}catch(n){r(n)}}),Oa=async(t,e)=>{if(!t.stripe_pk||!t.client_secret)throw new Error(`Invalid next action metadata format: ${JSON.stringify(t)}`);const n=await(await Qt(t.stripe_pk)).confirmCardSetup(t.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},Ma=async t=>{var o,s,i,c;const r=await(await Qt(t.stripe_pk)).confirmCardSetup(t.client_secret,{payment_method:t.stripe_pm_id}),n=(o=r.setupIntent)==null?void 0:o.status;if(n==="succeeded")console.log("[3DS] CONFIRMING PM:",t.stripe_pm_id),console.log("[3DS] Setup intent created:",r.setupIntent);else throw n==="canceled"?new Error("Payment cancelled, please click Submit again to pay"):new Error(`${((s=r.error)==null?void 0:s.message)??((c=(i=r.setupIntent)==null?void 0:i.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},Da=t=>JSON.stringify(t);for(var G=[],Tr=0;Tr<256;++Tr)G.push((Tr+256).toString(16).slice(1));function La(t,e=0){return(G[t[e+0]]+G[t[e+1]]+G[t[e+2]]+G[t[e+3]]+"-"+G[t[e+4]]+G[t[e+5]]+"-"+G[t[e+6]]+G[t[e+7]]+"-"+G[t[e+8]]+G[t[e+9]]+"-"+G[t[e+10]]+G[t[e+11]]+G[t[e+12]]+G[t[e+13]]+G[t[e+14]]+G[t[e+15]]).toLowerCase()}var Xt,ja=new Uint8Array(16);function Fa(){if(!Xt&&(Xt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Xt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Xt(ja)}var Ua=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const hn={randomUUID:Ua};function er(t,e,r){if(hn.randomUUID&&!e&&!t)return hn.randomUUID();t=t||{};var n=t.random||(t.rng||Fa)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,La(n)}const _e=(t,e)=>Array.from(t.querySelectorAll("[data-opid]")??[]).reduce((o,s)=>{const i=s.getAttribute("data-opid");return i?{...o,[i]:s.value}:o},{}),$a=t=>{try{return va.parse(t)}catch(e){throw console.error("Error parsing event payload:",t,e),e}};var ge;(function(t){t.Call="call",t.Reply="reply",t.Syn="syn",t.SynAck="synAck",t.Ack="ack"})(ge||(ge={}));var ze;(function(t){t.Fulfilled="fulfilled",t.Rejected="rejected"})(ze||(ze={}));var It;(function(t){t.ConnectionDestroyed="ConnectionDestroyed",t.ConnectionTimeout="ConnectionTimeout",t.NoIframeSrc="NoIframeSrc"})(It||(It={}));var xr;(function(t){t.DataCloneError="DataCloneError"})(xr||(xr={}));var Le;(function(t){t.Message="message"})(Le||(Le={}));const Za=(t,e)=>{const r=[];let n=!1;return{destroy(o){n||(n=!0,e(`${t}: Destroying connection`),r.forEach(s=>{s(o)}))},onDestroy(o){n?o():r.push(o)}}},Va=t=>(...e)=>{t&&console.log("[Penpal]",...e)},za={"http:":"80","https:":"443"},Ga=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Ba=["file:","data:"],qa=t=>{if(t&&Ba.find(c=>t.startsWith(c)))return"null";const e=document.location,r=Ga.exec(t);let n,o,s;r?(n=r[1]?r[1]:e.protocol,o=r[2],s=r[4]):(n=e.protocol,o=e.hostname,s=e.port);const i=s&&s!==za[n]?`:${s}`:"";return`${n}//${o}${i}`},yn=({name:t,message:e,stack:r})=>({name:t,message:e,stack:r}),Ya=t=>{const e=new Error;return Object.keys(t).forEach(r=>e[r]=t[r]),e},Wa=(t,e,r)=>{const{localName:n,local:o,remote:s,originForSending:i,originForReceiving:c}=t;let l=!1;const u=d=>{if(d.source!==s||d.data.penpal!==ge.Call)return;if(c!=="*"&&d.origin!==c){r(`${n} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const p=d.data,{methodName:_,args:f,id:h}=p;r(`${n}: Received ${_}() call`);const w=I=>E=>{if(r(`${n}: Sending ${_}() reply`),l){r(`${n}: Unable to send ${_}() reply due to destroyed connection`);return}const N={penpal:ge.Reply,id:h,resolution:I,returnValue:E};I===ze.Rejected&&E instanceof Error&&(N.returnValue=yn(E),N.returnValueIsError=!0);try{s.postMessage(N,i)}catch(x){if(x.name===xr.DataCloneError){const O={penpal:ge.Reply,id:h,resolution:ze.Rejected,returnValue:yn(x),returnValueIsError:!0};s.postMessage(O,i)}throw x}};new Promise(I=>I(e[_].apply(e,f))).then(w(ze.Fulfilled),w(ze.Rejected))};return o.addEventListener(Le.Message,u),()=>{l=!0,o.removeEventListener(Le.Message,u)}};let Ha=0;const Ka=()=>++Ha,_n=".",gn=t=>t?t.split(_n):[],Ja=t=>t.join(_n),Qa=(t,e)=>{const r=gn(e||"");return r.push(t),Ja(r)},Xa=(t,e,r)=>{const n=gn(e);return n.reduce((o,s,i)=>(typeof o[s]>"u"&&(o[s]={}),i===n.length-1&&(o[s]=r),o[s]),t),t},vn=(t,e)=>{const r={};return Object.keys(t).forEach(n=>{const o=t[n],s=Qa(n,e);typeof o=="object"&&Object.assign(r,vn(o,s)),typeof o=="function"&&(r[s]=o)}),r},ei=t=>{const e={};for(const r in t)Xa(e,r,t[r]);return e},ti=(t,e,r,n,o)=>{const{localName:s,local:i,remote:c,originForSending:l,originForReceiving:u}=e;let d=!1;o(`${s}: Connecting call sender`);const p=f=>(...h)=>{o(`${s}: Sending ${f}() call`);let w;try{c.closed&&(w=!0)}catch{w=!0}if(w&&n(),d){const I=new Error(`Unable to send ${f}() call due to destroyed connection`);throw I.code=It.ConnectionDestroyed,I}return new Promise((I,E)=>{const N=Ka(),x=U=>{if(U.source!==c||U.data.penpal!==ge.Reply||U.data.id!==N)return;if(u!=="*"&&U.origin!==u){o(`${s} received message from origin ${U.origin} which did not match expected origin ${u}`);return}const W=U.data;o(`${s}: Received ${f}() reply`),i.removeEventListener(Le.Message,x);let ke=W.returnValue;W.returnValueIsError&&(ke=Ya(ke)),(W.resolution===ze.Fulfilled?I:E)(ke)};i.addEventListener(Le.Message,x);const O={penpal:ge.Call,id:N,methodName:f,args:h};c.postMessage(O,l)})},_=r.reduce((f,h)=>(f[h]=p(h),f),{});return Object.assign(t,ei(_)),()=>{d=!0}},ri=(t,e,r,n,o)=>{const{destroy:s,onDestroy:i}=n;let c,l;const u={};return d=>{if(e!=="*"&&d.origin!==e){o(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}o("Parent: Handshake - Received ACK");const p={localName:"Parent",local:window,remote:d.source,originForSending:r,originForReceiving:e};c&&c(),c=Wa(p,t,o),i(c),l&&l.forEach(f=>{delete u[f]}),l=d.data.methodNames;const _=ti(u,p,l,s,o);return i(_),u}},ni=(t,e,r,n)=>o=>{if(!o.source)return;if(r!=="*"&&o.origin!==r){t(`Parent: Handshake - Received SYN message from origin ${o.origin} which did not match expected origin ${r}`);return}t("Parent: Handshake - Received SYN, responding with SYN-ACK");const s={penpal:ge.SynAck,methodNames:Object.keys(e)};o.source.postMessage(s,n)},oi=6e4,si=(t,e)=>{const{destroy:r,onDestroy:n}=e,o=setInterval(()=>{t.isConnected||(clearInterval(o),r())},oi);n(()=>{clearInterval(o)})},ai=(t,e)=>{let r;return t!==void 0&&(r=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${t}ms`);n.code=It.ConnectionTimeout,e(n)},t)),()=>{clearTimeout(r)}},ii=t=>{if(!t.src&&!t.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=It.NoIframeSrc,e}},wn=t=>{let{iframe:e,methods:r={},childOrigin:n,timeout:o,debug:s=!1}=t;const i=Va(s),c=Za("Parent",i),{onDestroy:l,destroy:u}=c;n||(ii(e),n=qa(e.src));const d=n==="null"?"*":n,p=vn(r),_=ni(i,p,n,d),f=ri(p,n,d,c,i);return{promise:new Promise((w,I)=>{const E=ai(o,u),N=x=>{if(!(x.source!==e.contentWindow||!x.data)){if(x.data.penpal===ge.Syn){_(x);return}if(x.data.penpal===ge.Ack){const O=f(x);O&&(E(),w(O));return}}};window.addEventListener(Le.Message,N),i("Parent: Awaiting handshake"),si(e,c),l(x=>{window.removeEventListener(Le.Message,N),x&&I(x)})}),destroy(){u()}}},ci=async t=>{if(typeof t!="object"||!t)return!1;try{const e={type:"ping"},r=await t.send(e);if(r!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(r)}`);return!0}catch(e){return console.error("Invalid CDE connection check:",e),!1}},li=(t,e)=>!!t&&e,P=t=>a.nullable(t.optional());a.string().trim().min(1,{message:"Cannot be blank"});const ui=a.object({cde_response_type:a.literal("error"),message:a.string(),headers:a.record(a.string(),a.string()).optional()});a.enum(["usd","brl"]);const bn=a.object({name:a.string(),amount_atom_off:P(a.number()),percent_off:P(a.number()),currency:P(a.string()),duration:a.string(),duration_in_months:P(a.number())}),En=a.object({amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),currency:a.string(),description:P(a.string()),price_id:a.string(),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),quantity:a.number().int()}),di=a.record(a.string(),a.any()),pi=a.object({name:a.string(),settings:P(di)}),nt=a.object({provider:a.string(),processor_name:P(a.string()),metadata:P(a.record(a.string(),a.any()))}),fi=a.object({quantity:a.number()}),mi=a.object({id:P(a.string()),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),subscription_items:a.array(fi),trial_start:P(a.string()),trial_end:P(a.string())}),kn=a.object({amount_atom:a.number()}),hi=a.object({amount_atom:a.number(),amount_atom_considering_discount_applied:a.number(),currency:a.string(),discount_amount_atoms:a.array(kn),subscription_item_id:a.string()}),yi=a.object({coupon:bn}),_i=a.object({currency:a.string(),discounts:a.array(yi),hosted_invoice_url:P(a.string()),lines:a.array(hi),remaining_amount_atom:a.number(),tax_amount_atom:a.number(),total_amount_atom:a.number(),total_discount_amount_atoms:a.array(kn)}),Cn=a.object({created:a.array(mi),invoices:a.array(_i),processors_used:P(a.array(a.string()))}),Sn=a.object({preview:Cn,preview_post_trial:P(Cn),coupons:a.array(bn)}),Pn=a.object({status:a.literal("open"),locale:P(a.string()),token:a.string(),email:P(a.string()),line_items:a.array(En),amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),brand:pi,subs_preview:P(Sn),methods_available:a.array(nt)}),An=a.discriminatedUnion("mode",[a.object({mode:a.literal("setup"),currency:a.nullable(a.undefined())}).extend(Pn.shape),a.object({mode:a.enum(["payment","subscription"]),currency:a.string()}).extend(Pn.shape)]),gi=a.object({status:a.literal("complete")}),vi=a.object({status:a.literal("expired")});a.union([An,gi,vi]),a.object({logo:a.string(),icon:a.string(),primary_color:a.string(),secondary_color:a.string()}),a.object({secure_token:a.string(),pm_id:a.string()}),a.object({secure_token:a.string(),payment_input:a.any(),customer_first_name:a.string().optional(),customer_last_name:a.string().optional(),customer_email:a.string(),customer_zip_code:a.string(),customer_country:a.string(),line_items:a.array(En),total_amount_atom:a.number().int(),cancel_at_end:a.boolean(),checkout_payment_method:nt,promotion_code:a.string().optional(),do_not_use_legacy_cc_flow:a.boolean().optional(),use_confirmed_pm_id:P(a.string())});const Tn=a.object({payment_method_id:a.string()});a.object({id:a.string(),return_url:a.string()});const wi=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()});a.array(wi);const bi=a.object({new_customer_email:a.string().optional(),new_customer_address:a.record(a.string(),a.any()).optional(),new_customer_first_name:a.string().optional(),new_customer_last_name:a.string().optional()}),Ei=a.object({price_id:a.string(),quantity:a.number().int()}),ki=a.object({line_items:a.array(Ei),promotion_code:a.string().optional(),displayed_total_amount_atom:a.number().int()}),Ci=a.object({processor_specific_metadata:P(a.record(a.string(),a.any()))});a.object({payment_provider:a.string(),checkout_payment_method:nt,existing_cc_pm_id:a.string().optional(),their_existing_pm_id:a.string().optional(),use_pay_first_flow:a.boolean().optional(),pay_first_flow_cart_info:ki.optional()}).extend(bi.shape).extend(Ci.shape);const xn=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),checkout_attempt_id:P(a.string())});a.object({fields:fa,checkoutPaymentMethod:nt}),a.object({session_id:a.string(),non_cde_form_fields:xt,checkout_payment_method:nt,extra_metadata:a.record(a.string(),a.any())});const Si=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),cc_pm_id:a.string()});a.record(a.any()),a.object({first_name:P(a.string()),last_name:P(a.string()),line1:P(a.string()),line2:P(a.string()),line3:P(a.string()),city:P(a.string()),state:P(a.string()),country:P(a.string()),zip_code:P(a.string()),email:P(a.string()),billing_email:P(a.string()),phone_number:P(a.string()),update_processor_customer:P(a.boolean())}),a.object({id:a.string(),email:P(a.string()),first_name:P(a.string()),last_name:P(a.string()),phone_number:P(a.string()),billing_email:P(a.string()),address:P(a.record(a.string(),a.any()))}),a.object({message:a.string()});const Pi=a.object({error_code:a.string()});a.object({checkout_payment_method:nt,processor_specific_metadata:a.record(a.any()).optional()});const Ai=a.object({next_action_metadata:P(a.record(a.any()))});a.object({events:a.array(a.object({event_name:a.string(),device_token:a.string(),properties:a.record(a.any()).optional(),context_properties:a.record(a.any()).optional()}))}),a.any().optional(),a.object({device_token:a.string()});const Ti=a.object({}),xi=t=>t.reduce((e,r)=>e+r,0);function Ii(t,e){var r=Object.setPrototypeOf;r?r(t,e):t.__proto__=e}function Ri(t,e){e===void 0&&(e=t.constructor);var r=Error.captureStackTrace;r&&r(t,e)}var Ni=function(){var t=function(r,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,s){o.__proto__=s}||function(o,s){for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(o[i]=s[i])},t(r,n)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Oi=function(t){Ni(e,t);function e(r,n){var o=this.constructor,s=t.call(this,r,n)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1,configurable:!0}),Ii(s,o.prototype),Ri(s),s}return e}(Error);const Ir=10,In=(t=0)=>e=>`\x1B[${e+t}m`,Rn=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,Nn=(t=0)=>(e,r,n)=>`\x1B[${38+t};2;${e};${r};${n}m`,D={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(D.modifier);const Mi=Object.keys(D.color),Di=Object.keys(D.bgColor);[...Mi,...Di];function Li(){const t=new Map;for(const[e,r]of Object.entries(D)){for(const[n,o]of Object.entries(r))D[n]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},r[n]=D[n],t.set(o[0],o[1]);Object.defineProperty(D,e,{value:r,enumerable:!1})}return Object.defineProperty(D,"codes",{value:t,enumerable:!1}),D.color.close="\x1B[39m",D.bgColor.close="\x1B[49m",D.color.ansi=In(),D.color.ansi256=Rn(),D.color.ansi16m=Nn(),D.bgColor.ansi=In(Ir),D.bgColor.ansi256=Rn(Ir),D.bgColor.ansi16m=Nn(Ir),Object.defineProperties(D,{rgbToAnsi256:{value(e,r,n){return e===r&&r===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){const r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!r)return[0,0,0];let[n]=r;n.length===3&&(n=[...n].map(s=>s+s).join(""));const o=Number.parseInt(n,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:e=>D.rgbToAnsi256(...D.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let r,n,o;if(e>=232)r=((e-232)*10+8)/255,n=r,o=r;else{e-=16;const c=e%36;r=Math.floor(e/36)/5,n=Math.floor(c/6)/5,o=c%6/5}const s=Math.max(r,n,o)*2;if(s===0)return 30;let i=30+(Math.round(o)<<2|Math.round(n)<<1|Math.round(r));return s===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,r,n)=>D.ansi256ToAnsi(D.rgbToAnsi256(e,r,n)),enumerable:!1},hexToAnsi:{value:e=>D.ansi256ToAnsi(D.hexToAnsi256(e)),enumerable:!1}}),D}const ve=Li(),tr=(()=>{if(navigator.userAgentData){const t=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(t&&t.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),On=tr!==0&&{level:tr,hasBasic:!0,has256:tr>=2,has16m:tr>=3},ji={stdout:On,stderr:On};function Fi(t,e,r){let n=t.indexOf(e);if(n===-1)return t;const o=e.length;let s=0,i="";do i+=t.slice(s,n)+e+r,s=n+o,n=t.indexOf(e,s);while(n!==-1);return i+=t.slice(s),i}function Ui(t,e,r,n){let o=0,s="";do{const i=t[n-1]==="\r";s+=t.slice(o,i?n-1:n)+e+(i?`\r
5
+ `)}`,ne=t=>{if(t instanceof Error)if(Ys(t.message)){const e=JSON.parse(t.message);return zs.safeParse(e).success?Ws(e):Bs.safeParse(e).success?Hs(e):(console.warn(`Encountered unknown stringified JSON object:
6
+ ${t.message}`),t.message)}else return Cr(t.message);if(typeof t=="object")try{return JSON.stringify(t)}catch(e){return e+""}else return t+""},Ks=(t,e,r)=>(...n)=>{try{return e(...n)}catch(o){r(`[form] Error running callback (${t}):`,o);return}};var re=(t=>(t.pockytPaypal="pockyt-paypal",t.airwallexGooglePay="airwallex-google-pay",t.airwallexApplePay="airwallex-apple-pay",t.authorizenetGooglePay="authorizenet-google-pay",t.authorizenetApplePay="authorizenet-apple-pay",t.loopCrypto="loop-crypto",t))(re||{});const Js=a.nativeEnum(re),Z=a.string().trim().min(1,{message:"Cannot be blank"}),M=a.string().trim().optional(),Q=t=>a.nullable(t.optional());var m=(t=>(t.FIRST_NAME="firstName",t.LAST_NAME="lastName",t.EMAIL="email",t.ZIP_CODE="zipCode",t.CITY="city",t.STATE="state",t.COUNTRY="country",t.ADDRESS="address",t.PHONE="phone",t.PROMOTION_CODE="promotionCode",t))(m||{});const an=a.nativeEnum(m);var cn=(t=>(t.CARD_NUMBER="cardNumber",t.CARD_EXPIRY="cardExpiry",t.CARD_CVC="cardCvc",t))(cn||{});const ln=a.nativeEnum(cn),un=a.union([an,ln]);var ye=(t=>(t.CARD="card",t.CARD_NUMBER="card-number",t.CARD_EXPIRY="card-expiry",t.CARD_CVC="card-cvc",t.CDE_BRIDGE="cde-bridge",t))(ye||{});const Qs=a.nativeEnum(ye),Kt=a.object({provider:a.string(),processor_name:Q(a.string()),metadata:Q(a.record(a.string(),a.any()))}),Xs=a.object({id:a.string()});a.object({cardNumber:M,expiry:M,cvc:M}),a.object({backgroundColor:M,color:M,fontFamily:M,fontSize:M,fontWeight:M,margin:M,padding:M,letterSpacing:M,lineHeight:M,hideIcon:M});const ie=a.enum(["LAYOUT","LOADED","BLUR","FOCUS","CHANGE","TOKENIZE_STARTED","CHECKOUT_STARTED","PAYMENT_FLOW_STARTED","TOKENIZE_SUCCESS","CHECKOUT_SUCCESS","LOAD_ERROR","VALIDATION_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR","SETUP_PAYMENT_METHOD_SUCCESS","TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),ea=ie.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),ta=a.object({type:ea}),ra=ie.extract(["BLUR","FOCUS","CHANGE"]),na=a.object({type:ra,elementType:ln,errors:a.array(a.string()).optional()}),oa=ie.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),sa=a.object({type:oa,message:Z,headers:a.record(a.string(),a.string()).optional()}),aa=ie.extract(["VALIDATION_ERROR"]),ia=a.object({type:aa,elementType:un,errors:a.array(a.string())}),ca=a.object({type:a.literal(ie.enum.LAYOUT),height:Z}),la=a.object({type:a.literal(ie.enum.LOADED),sessionId:Z,totalAmountAtoms:a.number(),currency:M,checkoutPaymentMethods:a.array(Kt)}),ua=a.object({type:a.literal(ie.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:a.record(a.string(),a.any()),paymentFlowMetadata:a.any().optional(),startPFMetadata:a.optional(a.record(a.string(),a.any()))}),da=a.object({type:a.literal(ie.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:a.string()}),Tt=a.object({firstName:Z,lastName:Z,email:Z,zipCode:Z,country:Z,promotionCode:M}),pa=a.object({firstName:M,lastName:M,email:Z,zipCode:Z,country:Z,promotionCode:M,address:M,city:M,state:M}),fa=ie.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),ma=a.object({type:fa,sessionId:Z,checkoutPaymentMethod:Kt,paymentFlowMetadata:a.any().optional(),doNotUseLegacyCCFlow:a.boolean().optional(),existingCCPMId:M}).extend(Tt.shape),ha=a.object({type:a.literal(ie.enum.TOKENIZE_SUCCESS),isReadyForCheckout:a.boolean()}),ya=a.object({type:a.literal(ie.enum.CHECKOUT_SUCCESS),invoiceUrls:a.array(a.string()),subscriptionIds:a.array(a.string()),customerId:a.string()}),_a=a.discriminatedUnion("type",[ta,na,sa,ia,ca,la,ma,ha,ya,ua,da]),ga=a.object({payload:_a,nonce:Z,formId:Z,elementId:Z});a.object({amountAtom:a.number(),currency:Z}),a.enum(["apple_pay","google_pay"]),a.object({secure_token:a.string(),promotion_code:a.string().optional()}),a.object({secure_token:a.string(),existing_cc_pm_id:Q(a.string()),their_pm_id:Q(a.string()),checkout_attempt_id:Q(a.string()),processor_specific_metadata:Q(a.record(a.string(),a.any()))});const Sr=a.object({invoice_urls:a.array(a.string()),subscription_ids:a.array(a.string()),customer_id:a.string(),processors_used:Q(a.array(a.string()))}),va=a.object({elementType:a.string(),errors:a.array(a.string())});a.object({session_id:a.string()});const wa=a.object({success:a.literal(!1),error_type:a.literal("validation_error"),errors:a.array(va)}),ba=a.discriminatedUnion("success",[a.object({success:a.literal(!0)}),wa]);a.object({session_id:a.string(),checkout_payment_method:Kt,non_cde_form_fields:Tt,do_not_use_legacy_cc_flow:a.boolean().optional(),existing_cc_pm_id:Q(a.string()),extra_metadata:a.record(a.string(),a.any())}),a.object({session_id:a.string(),checkout_payment_method:Kt,non_cde_form_fields:Tt,extra_metadata:a.record(a.string(),a.any()).optional()});var V=(t=>(t.SUCCESS="success",t.FAILURE="failure",t.CANCELLED="cancelled",t))(V||{});const Ea=a.object({status:a.enum(["success","failure","cancelled"]),href:a.string().optional().nullable()});a.object({href:a.string().optional().nullable()});const ka=a.object({type:a.string(),redirect_url:a.string(),initial_intent_id:a.string(),consent_id:a.string(),their_pm_id:a.string().optional()}),dn=a.object({type:a.string(),redirect_url:Q(a.string()),initial_intent_id:Q(a.string()),consent_id:Q(a.string()),their_pm_id:Q(a.string()),payment_session:Q(a.record(a.string(),a.any()))}),Ca=a.discriminatedUnion("present",[a.object({present:a.literal(!0),href:a.string()}),a.object({present:a.literal(!1)})]),Sa=a.object({payment_methods:a.array(Xs),pay_first_success_response:Q(Sr),required_user_actions:Q(a.array(dn))}),pn=t=>{const e={};return Object.entries(t).forEach(([r,n])=>{try{const o=an.parse(r);Array.isArray(n)?e[o]=n:Array.isArray(n._errors)&&(e[o]=n._errors)}catch{return}}),e},Pa=a.object({stripe_pk:a.string(),client_secret:a.string(),stripe_pm_id:a.string()}),Aa=a.object({type:a.string(),client_secret:a.string(),stripe_pk:a.string()}),Ta={usd:"usd",brl:"brl"},Jt=async t=>{for(let r=0;r<10;r++)fn()||await Pr(500);if(!fn())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(t)},xa=async(t,e)=>{const r=await Jt(t);return{elements:r.elements(e),stripe:r}},Ia=async(t,e,r,n,o)=>{const s=await Jt(t),i=Ta[r.toLowerCase().trim()];return s.paymentRequest({country:"US",currency:i,total:{label:"Total",amount:e,pending:n},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},Pr=t=>new Promise(e=>{setTimeout(e,t)}),fn=()=>"Stripe"in window,Ra=async t=>new Promise((e,r)=>{try{t.on("paymentmethod",async n=>{console.log("paymentmethod EVT:: ",n),e(n)}),t.on("token",async n=>{console.log("token EVT:: ",n)}),t.on("cancel",()=>{r(new Error("Payment cancelled, please click Submit again to pay"))})}catch(n){r(n)}}),Na=async(t,e)=>{if(!t.stripe_pk||!t.client_secret)throw new Error(`Invalid next action metadata format: ${JSON.stringify(t)}`);const n=await(await Jt(t.stripe_pk)).confirmCardSetup(t.client_secret,{payment_method:e.paymentMethod.id});if(n.error)throw e.complete("fail"),new Error(`Payment failed: ${n.error.message??"unknown"}`);return e.complete("success"),n},Oa=async t=>{var o,s,i,c;const r=await(await Jt(t.stripe_pk)).confirmCardSetup(t.client_secret,{payment_method:t.stripe_pm_id}),n=(o=r.setupIntent)==null?void 0:o.status;if(n==="succeeded")console.log("[3DS] CONFIRMING PM:",t.stripe_pm_id),console.log("[3DS] Setup intent created:",r.setupIntent);else throw n==="canceled"?new Error("Payment cancelled, please click Submit again to pay"):new Error(`${((s=r.error)==null?void 0:s.message)??((c=(i=r.setupIntent)==null?void 0:i.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},Ma=t=>JSON.stringify(t);for(var G=[],Ar=0;Ar<256;++Ar)G.push((Ar+256).toString(16).slice(1));function Da(t,e=0){return(G[t[e+0]]+G[t[e+1]]+G[t[e+2]]+G[t[e+3]]+"-"+G[t[e+4]]+G[t[e+5]]+"-"+G[t[e+6]]+G[t[e+7]]+"-"+G[t[e+8]]+G[t[e+9]]+"-"+G[t[e+10]]+G[t[e+11]]+G[t[e+12]]+G[t[e+13]]+G[t[e+14]]+G[t[e+15]]).toLowerCase()}var Qt,La=new Uint8Array(16);function ja(){if(!Qt&&(Qt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Qt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Qt(La)}var Fa=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const mn={randomUUID:Fa};function Xt(t,e,r){if(mn.randomUUID&&!e&&!t)return mn.randomUUID();t=t||{};var n=t.random||(t.rng||ja)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Da(n)}const _e=(t,e)=>Array.from(t.querySelectorAll("[data-opid]")??[]).reduce((o,s)=>{const i=s.getAttribute("data-opid");return i?{...o,[i]:s.value}:o},{}),Ua=t=>{try{return ga.parse(t)}catch(e){throw console.error("Error parsing event payload:",t,e),e}};var ge;(function(t){t.Call="call",t.Reply="reply",t.Syn="syn",t.SynAck="synAck",t.Ack="ack"})(ge||(ge={}));var Ve;(function(t){t.Fulfilled="fulfilled",t.Rejected="rejected"})(Ve||(Ve={}));var xt;(function(t){t.ConnectionDestroyed="ConnectionDestroyed",t.ConnectionTimeout="ConnectionTimeout",t.NoIframeSrc="NoIframeSrc"})(xt||(xt={}));var Tr;(function(t){t.DataCloneError="DataCloneError"})(Tr||(Tr={}));var Le;(function(t){t.Message="message"})(Le||(Le={}));const $a=(t,e)=>{const r=[];let n=!1;return{destroy(o){n||(n=!0,e(`${t}: Destroying connection`),r.forEach(s=>{s(o)}))},onDestroy(o){n?o():r.push(o)}}},Za=t=>(...e)=>{t&&console.log("[Penpal]",...e)},Va={"http:":"80","https:":"443"},za=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Ga=["file:","data:"],Ba=t=>{if(t&&Ga.find(c=>t.startsWith(c)))return"null";const e=document.location,r=za.exec(t);let n,o,s;r?(n=r[1]?r[1]:e.protocol,o=r[2],s=r[4]):(n=e.protocol,o=e.hostname,s=e.port);const i=s&&s!==Va[n]?`:${s}`:"";return`${n}//${o}${i}`},hn=({name:t,message:e,stack:r})=>({name:t,message:e,stack:r}),qa=t=>{const e=new Error;return Object.keys(t).forEach(r=>e[r]=t[r]),e},Ya=(t,e,r)=>{const{localName:n,local:o,remote:s,originForSending:i,originForReceiving:c}=t;let l=!1;const u=d=>{if(d.source!==s||d.data.penpal!==ge.Call)return;if(c!=="*"&&d.origin!==c){r(`${n} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const p=d.data,{methodName:_,args:f,id:h}=p;r(`${n}: Received ${_}() call`);const w=I=>E=>{if(r(`${n}: Sending ${_}() reply`),l){r(`${n}: Unable to send ${_}() reply due to destroyed connection`);return}const N={penpal:ge.Reply,id:h,resolution:I,returnValue:E};I===Ve.Rejected&&E instanceof Error&&(N.returnValue=hn(E),N.returnValueIsError=!0);try{s.postMessage(N,i)}catch(x){if(x.name===Tr.DataCloneError){const O={penpal:ge.Reply,id:h,resolution:Ve.Rejected,returnValue:hn(x),returnValueIsError:!0};s.postMessage(O,i)}throw x}};new Promise(I=>I(e[_].apply(e,f))).then(w(Ve.Fulfilled),w(Ve.Rejected))};return o.addEventListener(Le.Message,u),()=>{l=!0,o.removeEventListener(Le.Message,u)}};let Wa=0;const Ha=()=>++Wa,yn=".",_n=t=>t?t.split(yn):[],Ka=t=>t.join(yn),Ja=(t,e)=>{const r=_n(e||"");return r.push(t),Ka(r)},Qa=(t,e,r)=>{const n=_n(e);return n.reduce((o,s,i)=>(typeof o[s]>"u"&&(o[s]={}),i===n.length-1&&(o[s]=r),o[s]),t),t},gn=(t,e)=>{const r={};return Object.keys(t).forEach(n=>{const o=t[n],s=Ja(n,e);typeof o=="object"&&Object.assign(r,gn(o,s)),typeof o=="function"&&(r[s]=o)}),r},Xa=t=>{const e={};for(const r in t)Qa(e,r,t[r]);return e},ei=(t,e,r,n,o)=>{const{localName:s,local:i,remote:c,originForSending:l,originForReceiving:u}=e;let d=!1;o(`${s}: Connecting call sender`);const p=f=>(...h)=>{o(`${s}: Sending ${f}() call`);let w;try{c.closed&&(w=!0)}catch{w=!0}if(w&&n(),d){const I=new Error(`Unable to send ${f}() call due to destroyed connection`);throw I.code=xt.ConnectionDestroyed,I}return new Promise((I,E)=>{const N=Ha(),x=U=>{if(U.source!==c||U.data.penpal!==ge.Reply||U.data.id!==N)return;if(u!=="*"&&U.origin!==u){o(`${s} received message from origin ${U.origin} which did not match expected origin ${u}`);return}const W=U.data;o(`${s}: Received ${f}() reply`),i.removeEventListener(Le.Message,x);let ke=W.returnValue;W.returnValueIsError&&(ke=qa(ke)),(W.resolution===Ve.Fulfilled?I:E)(ke)};i.addEventListener(Le.Message,x);const O={penpal:ge.Call,id:N,methodName:f,args:h};c.postMessage(O,l)})},_=r.reduce((f,h)=>(f[h]=p(h),f),{});return Object.assign(t,Xa(_)),()=>{d=!0}},ti=(t,e,r,n,o)=>{const{destroy:s,onDestroy:i}=n;let c,l;const u={};return d=>{if(e!=="*"&&d.origin!==e){o(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}o("Parent: Handshake - Received ACK");const p={localName:"Parent",local:window,remote:d.source,originForSending:r,originForReceiving:e};c&&c(),c=Ya(p,t,o),i(c),l&&l.forEach(f=>{delete u[f]}),l=d.data.methodNames;const _=ei(u,p,l,s,o);return i(_),u}},ri=(t,e,r,n)=>o=>{if(!o.source)return;if(r!=="*"&&o.origin!==r){t(`Parent: Handshake - Received SYN message from origin ${o.origin} which did not match expected origin ${r}`);return}t("Parent: Handshake - Received SYN, responding with SYN-ACK");const s={penpal:ge.SynAck,methodNames:Object.keys(e)};o.source.postMessage(s,n)},ni=6e4,oi=(t,e)=>{const{destroy:r,onDestroy:n}=e,o=setInterval(()=>{t.isConnected||(clearInterval(o),r())},ni);n(()=>{clearInterval(o)})},si=(t,e)=>{let r;return t!==void 0&&(r=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${t}ms`);n.code=xt.ConnectionTimeout,e(n)},t)),()=>{clearTimeout(r)}},ai=t=>{if(!t.src&&!t.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=xt.NoIframeSrc,e}},vn=t=>{let{iframe:e,methods:r={},childOrigin:n,timeout:o,debug:s=!1}=t;const i=Za(s),c=$a("Parent",i),{onDestroy:l,destroy:u}=c;n||(ai(e),n=Ba(e.src));const d=n==="null"?"*":n,p=gn(r),_=ri(i,p,n,d),f=ti(p,n,d,c,i);return{promise:new Promise((w,I)=>{const E=si(o,u),N=x=>{if(!(x.source!==e.contentWindow||!x.data)){if(x.data.penpal===ge.Syn){_(x);return}if(x.data.penpal===ge.Ack){const O=f(x);O&&(E(),w(O));return}}};window.addEventListener(Le.Message,N),i("Parent: Awaiting handshake"),oi(e,c),l(x=>{window.removeEventListener(Le.Message,N),x&&I(x)})}),destroy(){u()}}},ii=async t=>{if(typeof t!="object"||!t)return!1;try{const e={type:"ping"},r=await t.send(e);if(r!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(r)}`);return!0}catch(e){return console.error("Invalid CDE connection check:",e),!1}},ci=(t,e)=>!!t&&e,P=t=>a.nullable(t.optional());a.string().trim().min(1,{message:"Cannot be blank"});const li=a.object({cde_response_type:a.literal("error"),message:a.string(),headers:a.record(a.string(),a.string()).optional()});a.enum(["usd","brl"]);const wn=a.object({name:a.string(),amount_atom_off:P(a.number()),percent_off:P(a.number()),currency:P(a.string()),duration:a.string(),duration_in_months:P(a.number())}),bn=a.object({amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),currency:a.string(),description:P(a.string()),price_id:a.string(),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),quantity:a.number().int()}),ui=a.record(a.string(),a.any()),di=a.object({name:a.string(),settings:P(ui)}),rt=a.object({provider:a.string(),processor_name:P(a.string()),metadata:P(a.record(a.string(),a.any()))}),pi=a.object({quantity:a.number()}),fi=a.object({id:P(a.string()),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),subscription_items:a.array(pi),trial_start:P(a.string()),trial_end:P(a.string())}),En=a.object({amount_atom:a.number()}),mi=a.object({amount_atom:a.number(),amount_atom_considering_discount_applied:a.number(),currency:a.string(),discount_amount_atoms:a.array(En),subscription_item_id:a.string()}),hi=a.object({coupon:wn}),yi=a.object({currency:a.string(),discounts:a.array(hi),hosted_invoice_url:P(a.string()),lines:a.array(mi),remaining_amount_atom:a.number(),tax_amount_atom:a.number(),total_amount_atom:a.number(),total_discount_amount_atoms:a.array(En)}),kn=a.object({created:a.array(fi),invoices:a.array(yi),processors_used:P(a.array(a.string()))}),Cn=a.object({preview:kn,preview_post_trial:P(kn),coupons:a.array(wn)}),Sn=a.object({status:a.literal("open"),locale:P(a.string()),token:a.string(),email:P(a.string()),line_items:a.array(bn),amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),brand:di,subs_preview:P(Cn),methods_available:a.array(rt)}),Pn=a.discriminatedUnion("mode",[a.object({mode:a.literal("setup"),currency:a.nullable(a.undefined())}).extend(Sn.shape),a.object({mode:a.enum(["payment","subscription"]),currency:a.string()}).extend(Sn.shape)]),_i=a.object({status:a.literal("complete")}),gi=a.object({status:a.literal("expired")});a.union([Pn,_i,gi]),a.object({logo:a.string(),icon:a.string(),primary_color:a.string(),secondary_color:a.string()}),a.object({secure_token:a.string(),pm_id:a.string()}),a.object({secure_token:a.string(),payment_input:a.any(),customer_first_name:a.string().optional(),customer_last_name:a.string().optional(),customer_email:a.string(),customer_zip_code:a.string(),customer_country:a.string(),line_items:a.array(bn),total_amount_atom:a.number().int(),cancel_at_end:a.boolean(),checkout_payment_method:rt,promotion_code:a.string().optional(),do_not_use_legacy_cc_flow:a.boolean().optional(),use_confirmed_pm_id:P(a.string())});const An=a.object({payment_method_id:a.string()});a.object({id:a.string(),return_url:a.string()});const vi=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()});a.array(vi);const wi=a.object({new_customer_email:a.string().optional(),new_customer_address:a.record(a.string(),a.any()).optional(),new_customer_first_name:a.string().optional(),new_customer_last_name:a.string().optional()}),bi=a.object({price_id:a.string(),quantity:a.number().int()}),Ei=a.object({line_items:a.array(bi),promotion_code:a.string().optional(),displayed_total_amount_atom:a.number().int()}),ki=a.object({processor_specific_metadata:P(a.record(a.string(),a.any()))});a.object({payment_provider:a.string(),checkout_payment_method:rt,existing_cc_pm_id:a.string().optional(),their_existing_pm_id:a.string().optional(),use_pay_first_flow:a.boolean().optional(),pay_first_flow_cart_info:Ei.optional()}).extend(wi.shape).extend(ki.shape);const Tn=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),checkout_attempt_id:P(a.string())});a.object({fields:pa,checkoutPaymentMethod:rt}),a.object({session_id:a.string(),non_cde_form_fields:Tt,checkout_payment_method:rt,extra_metadata:a.record(a.string(),a.any())});const Ci=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),cc_pm_id:a.string()});a.record(a.any()),a.object({first_name:P(a.string()),last_name:P(a.string()),line1:P(a.string()),line2:P(a.string()),line3:P(a.string()),city:P(a.string()),state:P(a.string()),country:P(a.string()),zip_code:P(a.string()),email:P(a.string()),billing_email:P(a.string()),phone_number:P(a.string()),update_processor_customer:P(a.boolean())}),a.object({id:a.string(),email:P(a.string()),first_name:P(a.string()),last_name:P(a.string()),phone_number:P(a.string()),billing_email:P(a.string()),address:P(a.record(a.string(),a.any()))}),a.object({message:a.string()});const Si=a.object({error_code:a.string()});a.object({checkout_payment_method:rt,processor_specific_metadata:a.record(a.any()).optional()});const Pi=a.object({next_action_metadata:P(a.record(a.any()))});a.object({events:a.array(a.object({event_name:a.string(),device_token:a.string(),properties:a.record(a.any()).optional(),context_properties:a.record(a.any()).optional()}))}),a.any().optional(),a.object({device_token:a.string()});const Ai=a.object({}),Ti=t=>t.reduce((e,r)=>e+r,0);function xi(t,e){var r=Object.setPrototypeOf;r?r(t,e):t.__proto__=e}function Ii(t,e){e===void 0&&(e=t.constructor);var r=Error.captureStackTrace;r&&r(t,e)}var Ri=function(){var t=function(r,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,s){o.__proto__=s}||function(o,s){for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(o[i]=s[i])},t(r,n)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Ni=function(t){Ri(e,t);function e(r,n){var o=this.constructor,s=t.call(this,r,n)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1,configurable:!0}),xi(s,o.prototype),Ii(s),s}return e}(Error);const xr=10,xn=(t=0)=>e=>`\x1B[${e+t}m`,In=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,Rn=(t=0)=>(e,r,n)=>`\x1B[${38+t};2;${e};${r};${n}m`,D={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(D.modifier);const Oi=Object.keys(D.color),Mi=Object.keys(D.bgColor);[...Oi,...Mi];function Di(){const t=new Map;for(const[e,r]of Object.entries(D)){for(const[n,o]of Object.entries(r))D[n]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},r[n]=D[n],t.set(o[0],o[1]);Object.defineProperty(D,e,{value:r,enumerable:!1})}return Object.defineProperty(D,"codes",{value:t,enumerable:!1}),D.color.close="\x1B[39m",D.bgColor.close="\x1B[49m",D.color.ansi=xn(),D.color.ansi256=In(),D.color.ansi16m=Rn(),D.bgColor.ansi=xn(xr),D.bgColor.ansi256=In(xr),D.bgColor.ansi16m=Rn(xr),Object.defineProperties(D,{rgbToAnsi256:{value(e,r,n){return e===r&&r===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){const r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!r)return[0,0,0];let[n]=r;n.length===3&&(n=[...n].map(s=>s+s).join(""));const o=Number.parseInt(n,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:e=>D.rgbToAnsi256(...D.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let r,n,o;if(e>=232)r=((e-232)*10+8)/255,n=r,o=r;else{e-=16;const c=e%36;r=Math.floor(e/36)/5,n=Math.floor(c/6)/5,o=c%6/5}const s=Math.max(r,n,o)*2;if(s===0)return 30;let i=30+(Math.round(o)<<2|Math.round(n)<<1|Math.round(r));return s===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,r,n)=>D.ansi256ToAnsi(D.rgbToAnsi256(e,r,n)),enumerable:!1},hexToAnsi:{value:e=>D.ansi256ToAnsi(D.hexToAnsi256(e)),enumerable:!1}}),D}const ve=Di(),er=(()=>{if(navigator.userAgentData){const t=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(t&&t.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),Nn=er!==0&&{level:er,hasBasic:!0,has256:er>=2,has16m:er>=3},Li={stdout:Nn,stderr:Nn};function ji(t,e,r){let n=t.indexOf(e);if(n===-1)return t;const o=e.length;let s=0,i="";do i+=t.slice(s,n)+e+r,s=n+o,n=t.indexOf(e,s);while(n!==-1);return i+=t.slice(s),i}function Fi(t,e,r,n){let o=0,s="";do{const i=t[n-1]==="\r";s+=t.slice(o,i?n-1:n)+e+(i?`\r
7
7
  `:`
8
8
  `)+r,o=n+1,n=t.indexOf(`
9
- `,o)}while(n!==-1);return s+=t.slice(o),s}const{stdout:Mn,stderr:Dn}=ji,Rr=Symbol("GENERATOR"),ot=Symbol("STYLER"),Rt=Symbol("IS_EMPTY"),Ln=["ansi","ansi","ansi256","ansi16m"],st=Object.create(null),$i=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const r=Mn?Mn.level:0;t.level=e.level===void 0?r:e.level},Zi=t=>{const e=(...r)=>r.join(" ");return $i(e,t),Object.setPrototypeOf(e,Nt.prototype),e};function Nt(t){return Zi(t)}Object.setPrototypeOf(Nt.prototype,Function.prototype);for(const[t,e]of Object.entries(ve))st[t]={get(){const r=rr(this,Or(e.open,e.close,this[ot]),this[Rt]);return Object.defineProperty(this,t,{value:r}),r}};st.visible={get(){const t=rr(this,this[ot],!0);return Object.defineProperty(this,"visible",{value:t}),t}};const Nr=(t,e,r,...n)=>t==="rgb"?e==="ansi16m"?ve[r].ansi16m(...n):e==="ansi256"?ve[r].ansi256(ve.rgbToAnsi256(...n)):ve[r].ansi(ve.rgbToAnsi(...n)):t==="hex"?Nr("rgb",e,r,...ve.hexToRgb(...n)):ve[r][t](...n),Vi=["rgb","hex","ansi256"];for(const t of Vi){st[t]={get(){const{level:r}=this;return function(...n){const o=Or(Nr(t,Ln[r],"color",...n),ve.color.close,this[ot]);return rr(this,o,this[Rt])}}};const e="bg"+t[0].toUpperCase()+t.slice(1);st[e]={get(){const{level:r}=this;return function(...n){const o=Or(Nr(t,Ln[r],"bgColor",...n),ve.bgColor.close,this[ot]);return rr(this,o,this[Rt])}}}}const zi=Object.defineProperties(()=>{},{...st,level:{enumerable:!0,get(){return this[Rr].level},set(t){this[Rr].level=t}}}),Or=(t,e,r)=>{let n,o;return r===void 0?(n=t,o=e):(n=r.openAll+t,o=e+r.closeAll),{open:t,close:e,openAll:n,closeAll:o,parent:r}},rr=(t,e,r)=>{const n=(...o)=>Gi(n,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(n,zi),n[Rr]=t,n[ot]=e,n[Rt]=r,n},Gi=(t,e)=>{if(t.level<=0||!e)return t[Rt]?"":e;let r=t[ot];if(r===void 0)return e;const{openAll:n,closeAll:o}=r;if(e.includes("\x1B"))for(;r!==void 0;)e=Fi(e,r.close,r.open),r=r.parent;const s=e.indexOf(`
10
- `);return s!==-1&&(e=Ui(e,o,n,s)),n+e+o};Object.defineProperties(Nt.prototype,st);const nr=Nt();Nt({level:Dn?Dn.level:0});const Ae=t=>async e=>{var r,n;try{(n=(r=e.formCallbacks.get).onCheckoutStarted)==null||n.call(r),k("checkout_started",{cpm:e.checkoutPaymentMethod});const o=await t(e);if(k("checkout_success",{cpm:e.checkoutPaymentMethod,...o}),o.mode==="setup")e.formCallbacks.get.onSetupPaymentMethodSuccess(o.result.payment_method_id);else if(o.mode==="checkout")e.formCallbacks.get.onCheckoutSuccess(o.result.invoice_urls,o.result.subscription_ids,o.result.customer_id,o.result.processors_used??[]);else throw new Error(`Unhandled mode: ${o}`)}catch(o){const s=ne(o),i=await io(e.context.anyCdeConnection,s);e.formCallbacks.get.onCheckoutError(s,i),k("checkout_error",{cpm:e.checkoutPaymentMethod,errorMessage:s,errorCode:i})}},Ge=t=>async e=>{try{return await t(e)}catch(r){const{err__:n}=F("init-error-catcher"),o=ne(r),s=await io(e.context.anyCdeConnection,o);return n(s,o,r),k("init_flow_error",{errorMessage:o,errorCode:s}),{isAvailable:!1,reason:o,errorCode:s,isLoading:!1}}},F=t=>{const e=(...n)=>{window.console.log(`${nr.green.bold("ojs/")}${nr.bold.gray(`${t}`)} `,...n)},r=(...n)=>{window.console.warn(`${nr.red.bold("ojs/")}${nr.bold.gray(`${t}`)} `,...n)};return{log:e,err:r,log__:e,err__:r}};var Mr=function(t,e){return Mr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},Mr(t,e)};function je(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Mr(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Bi(t,e,r,n){function o(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function c(d){try{u(n.next(d))}catch(p){i(p)}}function l(d){try{u(n.throw(d))}catch(p){i(p)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((n=n.apply(t,e||[])).next())})}function jn(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=c(0),i.throw=c(1),i.return=c(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function c(u){return function(d){return l([u,d])}}function l(u){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(r=0)),r;)try{if(n=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,o=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(d){u=[6,d],o=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function at(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function or(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(c){i={error:c}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s}function sr(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}function it(t){return this instanceof it?(this.v=t,this):new it(t)}function qi(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(f){return function(h){return Promise.resolve(h).then(f,p)}}function c(f,h){n[f]&&(o[f]=function(w){return new Promise(function(I,E){s.push([f,w,I,E])>1||l(f,w)})},h&&(o[f]=h(o[f])))}function l(f,h){try{u(n[f](h))}catch(w){_(s[0][3],w)}}function u(f){f.value instanceof it?Promise.resolve(f.value.v).then(d,p):_(s[0][2],f)}function d(f){l("next",f)}function p(f){l("throw",f)}function _(f,h){f(h),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Yi(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof at=="function"?at(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(i){return new Promise(function(c,l){i=t[s](i),o(c,l,i.done,i.value)})}}function o(s,i,c,l){Promise.resolve(l).then(function(u){s({value:u,done:c})},i)}}typeof SuppressedError=="function"&&SuppressedError;function B(t){return typeof t=="function"}function ar(t){var e=function(n){Error.call(n),n.stack=new Error().stack},r=t(e);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var Dr=ar(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
9
+ `,o)}while(n!==-1);return s+=t.slice(o),s}const{stdout:On,stderr:Mn}=Li,Ir=Symbol("GENERATOR"),nt=Symbol("STYLER"),It=Symbol("IS_EMPTY"),Dn=["ansi","ansi","ansi256","ansi16m"],ot=Object.create(null),Ui=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const r=On?On.level:0;t.level=e.level===void 0?r:e.level},$i=t=>{const e=(...r)=>r.join(" ");return Ui(e,t),Object.setPrototypeOf(e,Rt.prototype),e};function Rt(t){return $i(t)}Object.setPrototypeOf(Rt.prototype,Function.prototype);for(const[t,e]of Object.entries(ve))ot[t]={get(){const r=tr(this,Nr(e.open,e.close,this[nt]),this[It]);return Object.defineProperty(this,t,{value:r}),r}};ot.visible={get(){const t=tr(this,this[nt],!0);return Object.defineProperty(this,"visible",{value:t}),t}};const Rr=(t,e,r,...n)=>t==="rgb"?e==="ansi16m"?ve[r].ansi16m(...n):e==="ansi256"?ve[r].ansi256(ve.rgbToAnsi256(...n)):ve[r].ansi(ve.rgbToAnsi(...n)):t==="hex"?Rr("rgb",e,r,...ve.hexToRgb(...n)):ve[r][t](...n),Zi=["rgb","hex","ansi256"];for(const t of Zi){ot[t]={get(){const{level:r}=this;return function(...n){const o=Nr(Rr(t,Dn[r],"color",...n),ve.color.close,this[nt]);return tr(this,o,this[It])}}};const e="bg"+t[0].toUpperCase()+t.slice(1);ot[e]={get(){const{level:r}=this;return function(...n){const o=Nr(Rr(t,Dn[r],"bgColor",...n),ve.bgColor.close,this[nt]);return tr(this,o,this[It])}}}}const Vi=Object.defineProperties(()=>{},{...ot,level:{enumerable:!0,get(){return this[Ir].level},set(t){this[Ir].level=t}}}),Nr=(t,e,r)=>{let n,o;return r===void 0?(n=t,o=e):(n=r.openAll+t,o=e+r.closeAll),{open:t,close:e,openAll:n,closeAll:o,parent:r}},tr=(t,e,r)=>{const n=(...o)=>zi(n,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(n,Vi),n[Ir]=t,n[nt]=e,n[It]=r,n},zi=(t,e)=>{if(t.level<=0||!e)return t[It]?"":e;let r=t[nt];if(r===void 0)return e;const{openAll:n,closeAll:o}=r;if(e.includes("\x1B"))for(;r!==void 0;)e=ji(e,r.close,r.open),r=r.parent;const s=e.indexOf(`
10
+ `);return s!==-1&&(e=Fi(e,o,n,s)),n+e+o};Object.defineProperties(Rt.prototype,ot);const rr=Rt();Rt({level:Mn?Mn.level:0});const Ae=t=>async e=>{var r,n;try{(n=(r=e.formCallbacks.get).onCheckoutStarted)==null||n.call(r),k("checkout_started",{cpm:e.checkoutPaymentMethod});const o=await t(e);if(k("checkout_success",{cpm:e.checkoutPaymentMethod,...o}),o.mode==="setup")e.formCallbacks.get.onSetupPaymentMethodSuccess(o.result.payment_method_id);else if(o.mode==="checkout")e.formCallbacks.get.onCheckoutSuccess(o.result.invoice_urls,o.result.subscription_ids,o.result.customer_id,o.result.processors_used??[]);else throw new Error(`Unhandled mode: ${o}`)}catch(o){const s=ne(o),i=await ao(e.context.anyCdeConnection,s);e.formCallbacks.get.onCheckoutError(s,i),k("checkout_error",{cpm:e.checkoutPaymentMethod,errorMessage:s,errorCode:i})}},ze=t=>async e=>{try{return await t(e)}catch(r){const{err__:n}=F("init-error-catcher"),o=ne(r),s=await ao(e.context.anyCdeConnection,o);return n(s,o,r),k("init_flow_error",{errorMessage:o,errorCode:s}),{isAvailable:!1,reason:o,errorCode:s,isLoading:!1}}},F=t=>{const e=(...n)=>{window.console.log(`${rr.green.bold("ojs/")}${rr.bold.gray(`${t}`)} `,...n)},r=(...n)=>{window.console.warn(`${rr.red.bold("ojs/")}${rr.bold.gray(`${t}`)} `,...n)};return{log:e,err:r,log__:e,err__:r}};var Or=function(t,e){return Or=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},Or(t,e)};function je(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Or(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Gi(t,e,r,n){function o(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function c(d){try{u(n.next(d))}catch(p){i(p)}}function l(d){try{u(n.throw(d))}catch(p){i(p)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((n=n.apply(t,e||[])).next())})}function Ln(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=c(0),i.throw=c(1),i.return=c(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function c(u){return function(d){return l([u,d])}}function l(u){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(r=0)),r;)try{if(n=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,o=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(d){u=[6,d],o=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function st(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function nr(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(c){i={error:c}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s}function or(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}function at(t){return this instanceof at?(this.v=t,this):new at(t)}function Bi(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(f){return function(h){return Promise.resolve(h).then(f,p)}}function c(f,h){n[f]&&(o[f]=function(w){return new Promise(function(I,E){s.push([f,w,I,E])>1||l(f,w)})},h&&(o[f]=h(o[f])))}function l(f,h){try{u(n[f](h))}catch(w){_(s[0][3],w)}}function u(f){f.value instanceof at?Promise.resolve(f.value.v).then(d,p):_(s[0][2],f)}function d(f){l("next",f)}function p(f){l("throw",f)}function _(f,h){f(h),s.shift(),s.length&&l(s[0][0],s[0][1])}}function qi(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof st=="function"?st(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(i){return new Promise(function(c,l){i=t[s](i),o(c,l,i.done,i.value)})}}function o(s,i,c,l){Promise.resolve(l).then(function(u){s({value:u,done:c})},i)}}typeof SuppressedError=="function"&&SuppressedError;function B(t){return typeof t=="function"}function sr(t){var e=function(n){Error.call(n),n.stack=new Error().stack},r=t(e);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var Mr=sr(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
11
11
  `+r.map(function(n,o){return o+1+") "+n.toString()}).join(`
12
- `):"",this.name="UnsubscriptionError",this.errors=r}});function ir(t,e){if(t){var r=t.indexOf(e);0<=r&&t.splice(r,1)}}var Ot=function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,r,n,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var c=at(i),l=c.next();!l.done;l=c.next()){var u=l.value;u.remove(this)}}catch(w){e={error:w}}finally{try{l&&!l.done&&(r=c.return)&&r.call(c)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(B(d))try{d()}catch(w){s=w instanceof Dr?w.errors:[w]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var _=at(p),f=_.next();!f.done;f=_.next()){var h=f.value;try{$n(h)}catch(w){s=s??[],w instanceof Dr?s=sr(sr([],or(s)),or(w.errors)):s.push(w)}}}catch(w){n={error:w}}finally{try{f&&!f.done&&(o=_.return)&&o.call(_)}finally{if(n)throw n.error}}}if(s)throw new Dr(s)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)$n(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(e)}},t.prototype._hasParent=function(e){var r=this._parentage;return r===e||Array.isArray(r)&&r.includes(e)},t.prototype._addParent=function(e){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(e),r):r?[r,e]:e},t.prototype._removeParent=function(e){var r=this._parentage;r===e?this._parentage=null:Array.isArray(r)&&ir(r,e)},t.prototype.remove=function(e){var r=this._finalizers;r&&ir(r,e),e instanceof t&&e._removeParent(this)},t.EMPTY=function(){var e=new t;return e.closed=!0,e}(),t}(),Fn=Ot.EMPTY;function Un(t){return t instanceof Ot||t&&"closed"in t&&B(t.remove)&&B(t.add)&&B(t.unsubscribe)}function $n(t){B(t)?t():t.unsubscribe()}var Zn={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Vn={setTimeout:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,sr([t,e],or(r)))},clearTimeout:function(t){var e=Vn.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function zn(t){Vn.setTimeout(function(){throw t})}function Gn(){}function cr(t){t()}var Lr=function(t){je(e,t);function e(r){var n=t.call(this)||this;return n.isStopped=!1,r?(n.destination=r,Un(r)&&r.add(n)):n.destination=Ji,n}return e.create=function(r,n,o){return new Fr(r,n,o)},e.prototype.next=function(r){this.isStopped||this._next(r)},e.prototype.error=function(r){this.isStopped||(this.isStopped=!0,this._error(r))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(r){this.destination.next(r)},e.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Ot),Wi=Function.prototype.bind;function jr(t,e){return Wi.call(t,e)}var Hi=function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var r=this.partialObserver;if(r.next)try{r.next(e)}catch(n){lr(n)}},t.prototype.error=function(e){var r=this.partialObserver;if(r.error)try{r.error(e)}catch(n){lr(n)}else lr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(r){lr(r)}},t}(),Fr=function(t){je(e,t);function e(r,n,o){var s=t.call(this)||this,i;if(B(r)||!r)i={next:r??void 0,error:n??void 0,complete:o??void 0};else{var c;s&&Zn.useDeprecatedNextContext?(c=Object.create(r),c.unsubscribe=function(){return s.unsubscribe()},i={next:r.next&&jr(r.next,c),error:r.error&&jr(r.error,c),complete:r.complete&&jr(r.complete,c)}):i=r}return s.destination=new Hi(i),s}return e}(Lr);function lr(t){zn(t)}function Ki(t){throw t}var Ji={closed:!0,next:Gn,error:Ki,complete:Gn},Ur=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Qi(t){return t}function Xi(t){return t.length===0?Qi:t.length===1?t[0]:function(r){return t.reduce(function(n,o){return o(n)},r)}}var Te=function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var r=new t;return r.source=this,r.operator=e,r},t.prototype.subscribe=function(e,r,n){var o=this,s=tc(e)?e:new Fr(e,r,n);return cr(function(){var i=o,c=i.operator,l=i.source;s.add(c?c.call(s,l):l?o._subscribe(s):o._trySubscribe(s))}),s},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(r){e.error(r)}},t.prototype.forEach=function(e,r){var n=this;return r=Bn(r),new r(function(o,s){var i=new Fr({next:function(c){try{e(c)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});n.subscribe(i)})},t.prototype._subscribe=function(e){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(e)},t.prototype[Ur]=function(){return this},t.prototype.pipe=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Xi(e)(this)},t.prototype.toPromise=function(e){var r=this;return e=Bn(e),new e(function(n,o){var s;r.subscribe(function(i){return s=i},function(i){return o(i)},function(){return n(s)})})},t.create=function(e){return new t(e)},t}();function Bn(t){var e;return(e=t??Zn.Promise)!==null&&e!==void 0?e:Promise}function ec(t){return t&&B(t.next)&&B(t.error)&&B(t.complete)}function tc(t){return t&&t instanceof Lr||ec(t)&&Un(t)}function rc(t){return B(t==null?void 0:t.lift)}function nc(t){return function(e){if(rc(e))return e.lift(function(r){try{return t(r,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function oc(t,e,r,n,o){return new sc(t,e,r,n,o)}var sc=function(t){je(e,t);function e(r,n,o,s,i,c){var l=t.call(this,r)||this;return l.onFinalize=i,l.shouldUnsubscribe=c,l._next=n?function(u){try{n(u)}catch(d){r.error(d)}}:t.prototype._next,l._error=s?function(u){try{s(u)}catch(d){r.error(d)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=o?function(){try{o()}catch(u){r.error(u)}finally{this.unsubscribe()}}:t.prototype._complete,l}return e.prototype.unsubscribe=function(){var r;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;t.prototype.unsubscribe.call(this),!n&&((r=this.onFinalize)===null||r===void 0||r.call(this))}},e}(Lr),ac=ar(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),qn=function(t){je(e,t);function e(){var r=t.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return e.prototype.lift=function(r){var n=new Yn(this,this);return n.operator=r,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new ac},e.prototype.next=function(r){var n=this;cr(function(){var o,s;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var i=at(n.currentObservers),c=i.next();!c.done;c=i.next()){var l=c.value;l.next(r)}}catch(u){o={error:u}}finally{try{c&&!c.done&&(s=i.return)&&s.call(i)}finally{if(o)throw o.error}}}})},e.prototype.error=function(r){var n=this;cr(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=r;for(var o=n.observers;o.length;)o.shift().error(r)}})},e.prototype.complete=function(){var r=this;cr(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var n=r.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 r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(r){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,r)},e.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},e.prototype._innerSubscribe=function(r){var n=this,o=this,s=o.hasError,i=o.isStopped,c=o.observers;return s||i?Fn:(this.currentObservers=null,c.push(r),new Ot(function(){n.currentObservers=null,ir(c,r)}))},e.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,s=n.thrownError,i=n.isStopped;o?r.error(s):i&&r.complete()},e.prototype.asObservable=function(){var r=new Te;return r.source=this,r},e.create=function(r,n){return new Yn(r,n)},e}(Te),Yn=function(t){je(e,t);function e(r,n){var o=t.call(this)||this;return o.destination=r,o.source=n,o}return e.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},e.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},e.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},e.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:Fn},e}(qn),ic={now:function(){return Date.now()},delegate:void 0},cc=function(t){je(e,t);function e(r,n){return t.call(this)||this}return e.prototype.schedule=function(r,n){return this},e}(Ot),Wn={setInterval:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setInterval.apply(void 0,sr([t,e],or(r)))},clearInterval:function(t){return clearInterval(t)},delegate:void 0},lc=function(t){je(e,t);function e(r,n){var o=t.call(this,r,n)||this;return o.scheduler=r,o.work=n,o.pending=!1,o}return e.prototype.schedule=function(r,n){var o;if(n===void 0&&(n=0),this.closed)return this;this.state=r;var s=this.id,i=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(i,s,n)),this.pending=!0,this.delay=n,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(i,this.id,n),this},e.prototype.requestAsyncId=function(r,n,o){return o===void 0&&(o=0),Wn.setInterval(r.flush.bind(r,this),o)},e.prototype.recycleAsyncId=function(r,n,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return n;n!=null&&Wn.clearInterval(n)},e.prototype.execute=function(r,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(r,n);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(r,n){var o=!1,s;try{this.work(r)}catch(i){o=!0,s=i||new Error("Scheduled action threw falsy error")}if(o)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var r=this,n=r.id,o=r.scheduler,s=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,ir(s,this),n!=null&&(this.id=this.recycleAsyncId(o,n,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e}(cc),Hn=function(){function t(e,r){r===void 0&&(r=t.now),this.schedulerActionCtor=e,this.now=r}return t.prototype.schedule=function(e,r,n){return r===void 0&&(r=0),new this.schedulerActionCtor(this,e).schedule(n,r)},t.now=ic.now,t}(),uc=function(t){je(e,t);function e(r,n){n===void 0&&(n=Hn.now);var o=t.call(this,r,n)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(r){var n=this.actions;if(this._active){n.push(r);return}var o;this._active=!0;do if(o=r.execute(r.state,r.delay))break;while(r=n.shift());if(this._active=!1,o){for(;r=n.shift();)r.unsubscribe();throw o}},e}(Hn),dc=new uc(lc),pc=function(t){return t&&typeof t.length=="number"&&typeof t!="function"};function fc(t){return B(t==null?void 0:t.then)}function mc(t){return B(t[Ur])}function hc(t){return Symbol.asyncIterator&&B(t==null?void 0:t[Symbol.asyncIterator])}function yc(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function _c(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var gc=_c();function vc(t){return B(t==null?void 0:t[gc])}function wc(t){return qi(this,arguments,function(){var r,n,o,s;return jn(this,function(i){switch(i.label){case 0:r=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,it(r.read())];case 3:return n=i.sent(),o=n.value,s=n.done,s?[4,it(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,it(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function bc(t){return B(t==null?void 0:t.getReader)}function Ec(t){if(t instanceof Te)return t;if(t!=null){if(mc(t))return kc(t);if(pc(t))return Cc(t);if(fc(t))return Sc(t);if(hc(t))return Kn(t);if(vc(t))return Pc(t);if(bc(t))return Ac(t)}throw yc(t)}function kc(t){return new Te(function(e){var r=t[Ur]();if(B(r.subscribe))return r.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Cc(t){return new Te(function(e){for(var r=0;r<t.length&&!e.closed;r++)e.next(t[r]);e.complete()})}function Sc(t){return new Te(function(e){t.then(function(r){e.closed||(e.next(r),e.complete())},function(r){return e.error(r)}).then(null,zn)})}function Pc(t){return new Te(function(e){var r,n;try{for(var o=at(t),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(c){r={error:c}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}e.complete()})}function Kn(t){return new Te(function(e){Tc(t,e).catch(function(r){return e.error(r)})})}function Ac(t){return Kn(wc(t))}function Tc(t,e){var r,n,o,s;return Bi(this,void 0,void 0,function(){var i,c;return jn(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),r=Yi(t),l.label=1;case 1:return[4,r.next()];case 2:if(n=l.sent(),!!n.done)return[3,4];if(i=n.value,e.next(i),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=l.sent(),o={error:c},[3,11];case 6:return l.trys.push([6,,9,10]),n&&!n.done&&(s=r.return)?[4,s.call(r)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function xc(t,e,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var s=e.schedule(function(){r(),o?t.add(this.schedule(null,n)):this.unsubscribe()},n);if(t.add(s),!o)return s}function Ic(t,e){var r=B(t)?t:function(){return t},n=function(o){return o.error(r())};return new Te(n)}var Rc=ar(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function Nc(t,e){return new Promise(function(r,n){var o=!1,s;t.subscribe({next:function(i){s=i,o=!0},error:n,complete:function(){o?r(s):n(new Rc)}})})}function Oc(t){return t instanceof Date&&!isNaN(t)}var Mc=ar(function(t){return function(r){r===void 0&&(r=null),t(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=r}});function Dc(t,e){var r=Oc(t)?{first:t}:typeof t=="number"?{each:t}:t,n=r.first,o=r.each,s=r.with,i=s===void 0?Lc:s,c=r.scheduler,l=c===void 0?dc:c,u=r.meta,d=u===void 0?null:u;if(n==null&&o==null)throw new TypeError("No timeout provided.");return nc(function(p,_){var f,h,w=null,I=0,E=function(N){h=xc(_,l,function(){try{f.unsubscribe(),Ec(i({meta:d,lastValue:w,seen:I})).subscribe(_)}catch(x){_.error(x)}},N)};f=p.subscribe(oc(_,function(N){h==null||h.unsubscribe(),I++,_.next(w=N),o>0&&E(o)},void 0,void 0,function(){h!=null&&h.closed||h==null||h.unsubscribe(),w=null})),!I&&E(n!=null?typeof n=="number"?n:+n-l.now():o)})}function Lc(t){throw new Mc(t)}class Mt{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,r)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:r},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 r=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),r.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"&&ur(this._current);const r={first:e.timeoutSec*1e3,with:()=>Ic(()=>new Error(e.timeoutErrMsg))};return Nc(this._subject.pipe(Dc(r)))},this._current={status:"initial",isSuccess:!1},this._subject=new qn}get current(){return this._current}}const Jn=a.enum(["dev","stg","prod"]),jc={prod:"https://connto.getopenpay.com",stg:"https://connto.openpaystaging.com",dev:"http://localhost:8000"},Fc=t=>jc[t],$r={},Qn=async t=>{if($r[t])return $r[t];try{const e=await fetch(new URL("/health/environment",t)).then(n=>n.json()),r=Jn.parse(e.environment);return $r[t]=r,r}catch{return Jn.Values.prod}};function ur(t){throw new Error(`Unhandled case: ${t}`)}const Xn=(t,e)=>Object.fromEntries(Object.entries(t).filter(([r])=>!e.includes(r))),$=()=>{if(!(typeof window>"u"))return window},Zr=new Mt,eo="op_metrics_queue",Uc=3,$c=3,Zc=1e3,{log__:dr}=F("op-metrics");class Vc{constructor(){var e,r;this.queue=[],this.processingQueue=!1,this.batchTimeout=null,this.lastEventTimestamp=0,this.offlineListener=()=>{dr("Network offline, metrics will be queued"),this.cancelBatchProcessing()},this.onlineListener=()=>{dr("Network online, processing metrics queue"),this.processQueue()},this.loadQueueFromStorage(),(e=$())==null||e.addEventListener("offline",this.offlineListener),(r=$())==null||r.addEventListener("online",this.onlineListener)}addEvent(e,r,n){const o={eventName:e,properties:r||{},contextProperties:n||{},nonce:er(),timestamp:performance.now(),datetime:new Date().toISOString(),attemptCount:0,timeDiffFromPreviousEvent:this.lastEventTimestamp?performance.now()-this.lastEventTimestamp:0};this.lastEventTimestamp=o.timestamp,this.queue.push(o),this.saveQueueToStorage(),this.scheduleBatchProcessing()}loadQueueFromStorage(){var e,r;try{const n=(r=(e=$())==null?void 0:e.localStorage)==null?void 0:r.getItem(eo);n&&(this.queue=JSON.parse(n))}catch{this.queue=[],this.saveQueueToStorage()}}saveQueueToStorage(){var e;(e=$())==null||e.localStorage.setItem(eo,JSON.stringify(this.queue))}scheduleBatchProcessing(){const e=$();e&&navigator.onLine&&!this.processingQueue&&this.queue.length>0&&!this.batchTimeout&&(this.batchTimeout=e.setTimeout(()=>{this.batchTimeout=null,this.processQueue()},Zc))}cancelBatchProcessing(){var e;this.batchTimeout&&((e=$())==null||e.clearTimeout(this.batchTimeout),this.batchTimeout=null),this.processingQueue=!1}processQueue(){!navigator.onLine||this.processingQueue||this.queue.length===0||(this.processingQueue=!0,this.sendBatch().finally(()=>{this.processingQueue=!1,this.queue.length>0&&this.scheduleBatchProcessing()}))}async sendBatch(){if(this.queue.length===0)return;const e=Zr.getValueIfLoadedElse(void 0);if(!e){dr("Metrics context not available, will retry later");return}const r=this.queue.slice(0,$c);try{const n={events:r.map(c=>({event_name:c.eventName,device_token:e.deviceToken,context_properties:{...e,...c.contextProperties},properties:{nonce:c.nonce,datetime:c.datetime,timestamp:c.timestamp,time_diff_from_previous_event:c.timeDiffFromPreviousEvent,checkout_secure_token:e.checkoutSecureToken,...c.properties}}))},o=Fc(e.environment),s=new URL("/metrics/public/capture",o);(await fetch(s.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok?(this.queue=this.queue.slice(r.length),this.saveQueueToStorage()):this.handleFailedBatch(r)}catch(n){dr("Error sending metrics batch:",n),this.handleFailedBatch(r)}}handleFailedBatch(e){e.forEach(n=>{n.attemptCount++});const r=e.filter(n=>n.attemptCount<Uc);this.queue=this.queue.slice(e.length),this.queue=[...r,...this.queue],this.saveQueueToStorage()}cleanup(){var e,r;(e=$())==null||e.removeEventListener("offline",this.offlineListener),(r=$())==null||r.removeEventListener("online",this.onlineListener),this.cancelBatchProcessing()}}const to=new Vc,k=(t,e,r)=>{to.addEvent(t,e,r)},ro=t=>{const e=ne(t.reason);k("unhandled_rejection_error",{error_message:e,error_name:t.reason})},no=t=>{var r,n;const e=ne(t.error);k("uncaught_error",{error_message:e,error_name:(r=t.error)==null?void 0:r.name,error_stack:(n=t.error)==null?void 0:n.stack,file_name:t.filename,line_number:t.lineno,column_number:t.colno})},zc=()=>{var t,e;(t=$())==null||t.addEventListener("error",no),(e=$())==null||e.addEventListener("unhandledrejection",ro)},Gc=()=>{var t,e;(t=$())==null||t.removeEventListener("error",no),(e=$())==null||e.removeEventListener("unhandledrejection",ro)};(Bo=$())==null||Bo.addEventListener("beforeunload",()=>{to.processQueue()});class oo extends Oi{constructor(e){const r=`${e.message}`;super(r),this.response=e}get originalErrorMessage(){return this.response.message}}const K=async(t,e,r,n)=>{n&&k(n,{...e});const o=await t.send(e);if(qc(o))throw new oo(o);if(!Bc(o,r)){const s=r.safeParse(o);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",r,"Actual:",o),s.error)}return n&&k(n,{...o}),o},Bc=(t,e)=>e.safeParse(t).success,qc=t=>ui.safeParse(t).success,Yc=async(t,e)=>await K(t,{type:"get_checkout_preview",payload:e},Sn),q=async t=>await K(t,{type:"get_prefill",payload:{}},An),ct=async(t,e)=>await K(t,{type:"v2_start_payment_flow",payload:e},xn,"start_payment_flow"),Wc=async(t,e)=>await K(t,{type:"start_payment_flow_for_cc",payload:e},Si,"start_payment_flow_for_cc"),Hc=async(t,e)=>{k("start_payment_flow_for_pr",{...e});const r=await K(t,{type:"start_payment_flow_for_pr",payload:e},xn);return k("start_payment_flow_for_pr_result",{...r}),r},ce=async(t,e)=>await K(t,{type:"confirm_payment_flow",payload:e},Pa,"confirm_payment_flow"),Kc=async(t,e)=>await K(t,{type:"finalize_setup_payment_method",payload:e},Tn,"finalize_setup_payment_method"),Jc=async(t,e)=>await K(t,{type:"check_if_popup_window_verified",payload:e},Sa,"check_if_popup_window_verified"),Qc=async(t,e,r)=>{const n=await Yc(t,{secure_token:e,promotion_code:r}),o=new Set(n.preview.invoices.map(c=>c.currency));if(o.size!==1)throw new Error(`Expected exactly one currency, got ${o.size}`);const s=o.values().next().value??"usd",i=xi(n.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:s,amountAtom:i}},lt=async(t,e,r,n)=>{if(r)return{amountAtom:0,currency:"usd"};{n=n||void 0;const o=await Qc(t,e,n);return{amountAtom:o.amountAtom,currency:o.currency}}},Xc=async(t,e)=>{if(t.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(t.values()).map(n=>K(n,{type:"tokenize_card",payload:e},Ea)))},so=async(t,e)=>await K(t,{type:"checkout_card_elements",payload:e},Pr,"checkout_card_elements"),el=async(t,e)=>await K(t,{type:"setup_payment_method",payload:e},Tn,"setup_checkout"),Vr=async(t,e)=>await K(t,{type:"checkout",payload:e},Pr,"perform_checkout"),ao=1e3,tl=async(t,e)=>{console.log(e);const n=await wn({iframe:t,debug:!0,timeout:ao,childOrigin:"*"}).promise,o=await K(n,{type:"ping-3ds-status"},ka);return console.log("🟢 CDE connection successful! Stopping polling... Result:",o),o},zr=async(t,e)=>await K(t,{type:"prepare_payment_flow",payload:e},Ai,"prepare_payment_flow"),io=async(t,e)=>{try{return(await K(t,{type:"get_standardized_error_code",payload:{message:e}},Pi)).error_code}catch(r){return console.error("[cde-client] Error during getStandardizedErrorCode:",ne(r)),"PAYMENT_FAILED_GENERIC"}},rl=async(t,e)=>await K(t,{type:"set_user_device_token",payload:{device_token:e}},Ti),{log__:Xu,err__:nl}=F("common"),Dt=t=>{if(t.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${t.payment_methods.length}`);return{payment_method_id:t.payment_methods[0].id}},le=(t,e)=>{const r=t.find(n=>e.safeParse(n).success);if(!r)throw nl("No CPMs found for model. All models:",t),new Error("No CPMs found for model");return e.parse(r)},ol=t=>({new_customer_email:t.email,new_customer_address:{zip_code:t.zipCode,country:t.country},new_customer_first_name:t.firstName,new_customer_last_name:t.lastName}),pr=async t=>{const{log__:e}=F(t.logPrefix),r=await q(t.anyCdeConnection),n=Dt(t.confirmResult);if(r.mode==="setup")return e("Setting up payment method..."),{mode:"setup",result:await Kc(t.anyCdeConnection,{secure_token:r.token,pm_id:n.payment_method_id})};{e("Doing checkout...");const o={secure_token:r.token,payment_input:{provider_type:t.checkoutPaymentMethod.provider},customer_email:t.requiredFormFields[m.EMAIL],customer_zip_code:t.requiredFormFields[m.ZIP_CODE],customer_country:t.requiredFormFields[m.COUNTRY],promotion_code:t.requiredFormFields[m.PROMOTION_CODE],line_items:r.line_items,total_amount_atom:r.amount_total_atom,cancel_at_end:!1,checkout_payment_method:t.checkoutPaymentMethod,use_confirmed_pm_id:n.payment_method_id};return{mode:"checkout",result:await Vr(t.anyCdeConnection,o)}}},sl="@keyframes fadeIn{0%{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}.overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483648!important;display:flex;justify-content:center;align-items:center;background-color:#00000080}.container{max-width:500px;max-height:600px;width:100%;height:100%;background-color:#fff;position:relative;animation:fadeIn .3s ease-out}.frame,#adyen-container,#adyen-container>*{max-width:500px;max-height:600px;width:100%;height:100%;border:none}.cancel-button{position:absolute;background:transparent;border:none;font-size:1rem;color:#fff;cursor:pointer;top:-1.5rem;padding:0;right:0}",co=t=>{const e=document.createElement("template");e.innerHTML=`
12
+ `):"",this.name="UnsubscriptionError",this.errors=r}});function ar(t,e){if(t){var r=t.indexOf(e);0<=r&&t.splice(r,1)}}var Nt=function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,r,n,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var c=st(i),l=c.next();!l.done;l=c.next()){var u=l.value;u.remove(this)}}catch(w){e={error:w}}finally{try{l&&!l.done&&(r=c.return)&&r.call(c)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(B(d))try{d()}catch(w){s=w instanceof Mr?w.errors:[w]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var _=st(p),f=_.next();!f.done;f=_.next()){var h=f.value;try{Un(h)}catch(w){s=s??[],w instanceof Mr?s=or(or([],nr(s)),nr(w.errors)):s.push(w)}}}catch(w){n={error:w}}finally{try{f&&!f.done&&(o=_.return)&&o.call(_)}finally{if(n)throw n.error}}}if(s)throw new Mr(s)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)Un(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(e)}},t.prototype._hasParent=function(e){var r=this._parentage;return r===e||Array.isArray(r)&&r.includes(e)},t.prototype._addParent=function(e){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(e),r):r?[r,e]:e},t.prototype._removeParent=function(e){var r=this._parentage;r===e?this._parentage=null:Array.isArray(r)&&ar(r,e)},t.prototype.remove=function(e){var r=this._finalizers;r&&ar(r,e),e instanceof t&&e._removeParent(this)},t.EMPTY=function(){var e=new t;return e.closed=!0,e}(),t}(),jn=Nt.EMPTY;function Fn(t){return t instanceof Nt||t&&"closed"in t&&B(t.remove)&&B(t.add)&&B(t.unsubscribe)}function Un(t){B(t)?t():t.unsubscribe()}var $n={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Zn={setTimeout:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,or([t,e],nr(r)))},clearTimeout:function(t){var e=Zn.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function Vn(t){Zn.setTimeout(function(){throw t})}function zn(){}function ir(t){t()}var Dr=function(t){je(e,t);function e(r){var n=t.call(this)||this;return n.isStopped=!1,r?(n.destination=r,Fn(r)&&r.add(n)):n.destination=Ki,n}return e.create=function(r,n,o){return new jr(r,n,o)},e.prototype.next=function(r){this.isStopped||this._next(r)},e.prototype.error=function(r){this.isStopped||(this.isStopped=!0,this._error(r))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(r){this.destination.next(r)},e.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Nt),Yi=Function.prototype.bind;function Lr(t,e){return Yi.call(t,e)}var Wi=function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var r=this.partialObserver;if(r.next)try{r.next(e)}catch(n){cr(n)}},t.prototype.error=function(e){var r=this.partialObserver;if(r.error)try{r.error(e)}catch(n){cr(n)}else cr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(r){cr(r)}},t}(),jr=function(t){je(e,t);function e(r,n,o){var s=t.call(this)||this,i;if(B(r)||!r)i={next:r??void 0,error:n??void 0,complete:o??void 0};else{var c;s&&$n.useDeprecatedNextContext?(c=Object.create(r),c.unsubscribe=function(){return s.unsubscribe()},i={next:r.next&&Lr(r.next,c),error:r.error&&Lr(r.error,c),complete:r.complete&&Lr(r.complete,c)}):i=r}return s.destination=new Wi(i),s}return e}(Dr);function cr(t){Vn(t)}function Hi(t){throw t}var Ki={closed:!0,next:zn,error:Hi,complete:zn},Fr=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Ji(t){return t}function Qi(t){return t.length===0?Ji:t.length===1?t[0]:function(r){return t.reduce(function(n,o){return o(n)},r)}}var Te=function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var r=new t;return r.source=this,r.operator=e,r},t.prototype.subscribe=function(e,r,n){var o=this,s=ec(e)?e:new jr(e,r,n);return ir(function(){var i=o,c=i.operator,l=i.source;s.add(c?c.call(s,l):l?o._subscribe(s):o._trySubscribe(s))}),s},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(r){e.error(r)}},t.prototype.forEach=function(e,r){var n=this;return r=Gn(r),new r(function(o,s){var i=new jr({next:function(c){try{e(c)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});n.subscribe(i)})},t.prototype._subscribe=function(e){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(e)},t.prototype[Fr]=function(){return this},t.prototype.pipe=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Qi(e)(this)},t.prototype.toPromise=function(e){var r=this;return e=Gn(e),new e(function(n,o){var s;r.subscribe(function(i){return s=i},function(i){return o(i)},function(){return n(s)})})},t.create=function(e){return new t(e)},t}();function Gn(t){var e;return(e=t??$n.Promise)!==null&&e!==void 0?e:Promise}function Xi(t){return t&&B(t.next)&&B(t.error)&&B(t.complete)}function ec(t){return t&&t instanceof Dr||Xi(t)&&Fn(t)}function tc(t){return B(t==null?void 0:t.lift)}function rc(t){return function(e){if(tc(e))return e.lift(function(r){try{return t(r,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function nc(t,e,r,n,o){return new oc(t,e,r,n,o)}var oc=function(t){je(e,t);function e(r,n,o,s,i,c){var l=t.call(this,r)||this;return l.onFinalize=i,l.shouldUnsubscribe=c,l._next=n?function(u){try{n(u)}catch(d){r.error(d)}}:t.prototype._next,l._error=s?function(u){try{s(u)}catch(d){r.error(d)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=o?function(){try{o()}catch(u){r.error(u)}finally{this.unsubscribe()}}:t.prototype._complete,l}return e.prototype.unsubscribe=function(){var r;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;t.prototype.unsubscribe.call(this),!n&&((r=this.onFinalize)===null||r===void 0||r.call(this))}},e}(Dr),sc=sr(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Bn=function(t){je(e,t);function e(){var r=t.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return e.prototype.lift=function(r){var n=new qn(this,this);return n.operator=r,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new sc},e.prototype.next=function(r){var n=this;ir(function(){var o,s;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var i=st(n.currentObservers),c=i.next();!c.done;c=i.next()){var l=c.value;l.next(r)}}catch(u){o={error:u}}finally{try{c&&!c.done&&(s=i.return)&&s.call(i)}finally{if(o)throw o.error}}}})},e.prototype.error=function(r){var n=this;ir(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=r;for(var o=n.observers;o.length;)o.shift().error(r)}})},e.prototype.complete=function(){var r=this;ir(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var n=r.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 r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(r){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,r)},e.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},e.prototype._innerSubscribe=function(r){var n=this,o=this,s=o.hasError,i=o.isStopped,c=o.observers;return s||i?jn:(this.currentObservers=null,c.push(r),new Nt(function(){n.currentObservers=null,ar(c,r)}))},e.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,s=n.thrownError,i=n.isStopped;o?r.error(s):i&&r.complete()},e.prototype.asObservable=function(){var r=new Te;return r.source=this,r},e.create=function(r,n){return new qn(r,n)},e}(Te),qn=function(t){je(e,t);function e(r,n){var o=t.call(this)||this;return o.destination=r,o.source=n,o}return e.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},e.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},e.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},e.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:jn},e}(Bn),ac={now:function(){return Date.now()},delegate:void 0},ic=function(t){je(e,t);function e(r,n){return t.call(this)||this}return e.prototype.schedule=function(r,n){return this},e}(Nt),Yn={setInterval:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setInterval.apply(void 0,or([t,e],nr(r)))},clearInterval:function(t){return clearInterval(t)},delegate:void 0},cc=function(t){je(e,t);function e(r,n){var o=t.call(this,r,n)||this;return o.scheduler=r,o.work=n,o.pending=!1,o}return e.prototype.schedule=function(r,n){var o;if(n===void 0&&(n=0),this.closed)return this;this.state=r;var s=this.id,i=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(i,s,n)),this.pending=!0,this.delay=n,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(i,this.id,n),this},e.prototype.requestAsyncId=function(r,n,o){return o===void 0&&(o=0),Yn.setInterval(r.flush.bind(r,this),o)},e.prototype.recycleAsyncId=function(r,n,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return n;n!=null&&Yn.clearInterval(n)},e.prototype.execute=function(r,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(r,n);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(r,n){var o=!1,s;try{this.work(r)}catch(i){o=!0,s=i||new Error("Scheduled action threw falsy error")}if(o)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var r=this,n=r.id,o=r.scheduler,s=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,ar(s,this),n!=null&&(this.id=this.recycleAsyncId(o,n,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e}(ic),Wn=function(){function t(e,r){r===void 0&&(r=t.now),this.schedulerActionCtor=e,this.now=r}return t.prototype.schedule=function(e,r,n){return r===void 0&&(r=0),new this.schedulerActionCtor(this,e).schedule(n,r)},t.now=ac.now,t}(),lc=function(t){je(e,t);function e(r,n){n===void 0&&(n=Wn.now);var o=t.call(this,r,n)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(r){var n=this.actions;if(this._active){n.push(r);return}var o;this._active=!0;do if(o=r.execute(r.state,r.delay))break;while(r=n.shift());if(this._active=!1,o){for(;r=n.shift();)r.unsubscribe();throw o}},e}(Wn),uc=new lc(cc),dc=function(t){return t&&typeof t.length=="number"&&typeof t!="function"};function pc(t){return B(t==null?void 0:t.then)}function fc(t){return B(t[Fr])}function mc(t){return Symbol.asyncIterator&&B(t==null?void 0:t[Symbol.asyncIterator])}function hc(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function yc(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var _c=yc();function gc(t){return B(t==null?void 0:t[_c])}function vc(t){return Bi(this,arguments,function(){var r,n,o,s;return Ln(this,function(i){switch(i.label){case 0:r=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,at(r.read())];case 3:return n=i.sent(),o=n.value,s=n.done,s?[4,at(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,at(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function wc(t){return B(t==null?void 0:t.getReader)}function bc(t){if(t instanceof Te)return t;if(t!=null){if(fc(t))return Ec(t);if(dc(t))return kc(t);if(pc(t))return Cc(t);if(mc(t))return Hn(t);if(gc(t))return Sc(t);if(wc(t))return Pc(t)}throw hc(t)}function Ec(t){return new Te(function(e){var r=t[Fr]();if(B(r.subscribe))return r.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function kc(t){return new Te(function(e){for(var r=0;r<t.length&&!e.closed;r++)e.next(t[r]);e.complete()})}function Cc(t){return new Te(function(e){t.then(function(r){e.closed||(e.next(r),e.complete())},function(r){return e.error(r)}).then(null,Vn)})}function Sc(t){return new Te(function(e){var r,n;try{for(var o=st(t),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(c){r={error:c}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}e.complete()})}function Hn(t){return new Te(function(e){Ac(t,e).catch(function(r){return e.error(r)})})}function Pc(t){return Hn(vc(t))}function Ac(t,e){var r,n,o,s;return Gi(this,void 0,void 0,function(){var i,c;return Ln(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),r=qi(t),l.label=1;case 1:return[4,r.next()];case 2:if(n=l.sent(),!!n.done)return[3,4];if(i=n.value,e.next(i),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=l.sent(),o={error:c},[3,11];case 6:return l.trys.push([6,,9,10]),n&&!n.done&&(s=r.return)?[4,s.call(r)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Tc(t,e,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var s=e.schedule(function(){r(),o?t.add(this.schedule(null,n)):this.unsubscribe()},n);if(t.add(s),!o)return s}function xc(t,e){var r=B(t)?t:function(){return t},n=function(o){return o.error(r())};return new Te(n)}var Ic=sr(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function Rc(t,e){return new Promise(function(r,n){var o=!1,s;t.subscribe({next:function(i){s=i,o=!0},error:n,complete:function(){o?r(s):n(new Ic)}})})}function Nc(t){return t instanceof Date&&!isNaN(t)}var Oc=sr(function(t){return function(r){r===void 0&&(r=null),t(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=r}});function Mc(t,e){var r=Nc(t)?{first:t}:typeof t=="number"?{each:t}:t,n=r.first,o=r.each,s=r.with,i=s===void 0?Dc:s,c=r.scheduler,l=c===void 0?uc:c,u=r.meta,d=u===void 0?null:u;if(n==null&&o==null)throw new TypeError("No timeout provided.");return rc(function(p,_){var f,h,w=null,I=0,E=function(N){h=Tc(_,l,function(){try{f.unsubscribe(),bc(i({meta:d,lastValue:w,seen:I})).subscribe(_)}catch(x){_.error(x)}},N)};f=p.subscribe(nc(_,function(N){h==null||h.unsubscribe(),I++,_.next(w=N),o>0&&E(o)},void 0,void 0,function(){h!=null&&h.closed||h==null||h.unsubscribe(),w=null})),!I&&E(n!=null?typeof n=="number"?n:+n-l.now():o)})}function Dc(t){throw new Oc(t)}class Ot{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,r)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:r},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 r=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),r.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"&&lr(this._current);const r={first:e.timeoutSec*1e3,with:()=>xc(()=>new Error(e.timeoutErrMsg))};return Rc(this._subject.pipe(Mc(r)))},this._current={status:"initial",isSuccess:!1},this._subject=new Bn}get current(){return this._current}}const Kn=a.enum(["dev","stg","prod"]),Lc={prod:"https://connto.getopenpay.com",stg:"https://connto.openpaystaging.com",dev:"http://localhost:8000"},jc=t=>Lc[t],Ur={},Jn=async t=>{if(Ur[t])return Ur[t];try{const e=await fetch(new URL("/health/environment",t)).then(n=>n.json()),r=Kn.parse(e.environment);return Ur[t]=r,r}catch{return Kn.Values.prod}};function lr(t){throw new Error(`Unhandled case: ${t}`)}const Qn=(t,e)=>Object.fromEntries(Object.entries(t).filter(([r])=>!e.includes(r))),$=()=>{if(!(typeof window>"u"))return window},$r=new Ot,Xn="op_metrics_queue",Fc=3,Uc=3,$c=1e3,{log__:ur}=F("op-metrics");class Zc{constructor(){var e,r;this.queue=[],this.processingQueue=!1,this.batchTimeout=null,this.lastEventTimestamp=0,this.offlineListener=()=>{ur("Network offline, metrics will be queued"),this.cancelBatchProcessing()},this.onlineListener=()=>{ur("Network online, processing metrics queue"),this.processQueue()},this.loadQueueFromStorage(),(e=$())==null||e.addEventListener("offline",this.offlineListener),(r=$())==null||r.addEventListener("online",this.onlineListener)}addEvent(e,r,n){const o={eventName:e,properties:r||{},contextProperties:n||{},nonce:Xt(),timestamp:performance.now(),datetime:new Date().toISOString(),attemptCount:0,timeDiffFromPreviousEvent:this.lastEventTimestamp?performance.now()-this.lastEventTimestamp:0};this.lastEventTimestamp=o.timestamp,this.queue.push(o),this.saveQueueToStorage(),this.scheduleBatchProcessing()}loadQueueFromStorage(){var e,r;try{const n=(r=(e=$())==null?void 0:e.localStorage)==null?void 0:r.getItem(Xn);n&&(this.queue=JSON.parse(n))}catch{this.queue=[],this.saveQueueToStorage()}}saveQueueToStorage(){var e;(e=$())==null||e.localStorage.setItem(Xn,JSON.stringify(this.queue))}scheduleBatchProcessing(){const e=$();e&&navigator.onLine&&!this.processingQueue&&this.queue.length>0&&!this.batchTimeout&&(this.batchTimeout=e.setTimeout(()=>{this.batchTimeout=null,this.processQueue()},$c))}cancelBatchProcessing(){var e;this.batchTimeout&&((e=$())==null||e.clearTimeout(this.batchTimeout),this.batchTimeout=null),this.processingQueue=!1}processQueue(){!navigator.onLine||this.processingQueue||this.queue.length===0||(this.processingQueue=!0,this.sendBatch().finally(()=>{this.processingQueue=!1,this.queue.length>0&&this.scheduleBatchProcessing()}))}async sendBatch(){if(this.queue.length===0)return;const e=$r.getValueIfLoadedElse(void 0);if(!e){ur("Metrics context not available, will retry later");return}const r=this.queue.slice(0,Uc);try{const n={events:r.map(c=>({event_name:c.eventName,device_token:e.deviceToken,context_properties:{...e,...c.contextProperties},properties:{nonce:c.nonce,datetime:c.datetime,timestamp:c.timestamp,time_diff_from_previous_event:c.timeDiffFromPreviousEvent,checkout_secure_token:e.checkoutSecureToken,...c.properties}}))},o=jc(e.environment),s=new URL("/metrics/public/capture",o);(await fetch(s.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok?(this.queue=this.queue.slice(r.length),this.saveQueueToStorage()):this.handleFailedBatch(r)}catch(n){ur("Error sending metrics batch:",n),this.handleFailedBatch(r)}}handleFailedBatch(e){e.forEach(n=>{n.attemptCount++});const r=e.filter(n=>n.attemptCount<Fc);this.queue=this.queue.slice(e.length),this.queue=[...r,...this.queue],this.saveQueueToStorage()}cleanup(){var e,r;(e=$())==null||e.removeEventListener("offline",this.offlineListener),(r=$())==null||r.removeEventListener("online",this.onlineListener),this.cancelBatchProcessing()}}const eo=new Zc,k=(t,e,r)=>{eo.addEvent(t,e,r)},to=t=>{const e=ne(t.reason);k("unhandled_rejection_error",{error_message:e,error_name:t.reason})},ro=t=>{var r,n;const e=ne(t.error);k("uncaught_error",{error_message:e,error_name:(r=t.error)==null?void 0:r.name,error_stack:(n=t.error)==null?void 0:n.stack,file_name:t.filename,line_number:t.lineno,column_number:t.colno})},Vc=()=>{var t,e;(t=$())==null||t.addEventListener("error",ro),(e=$())==null||e.addEventListener("unhandledrejection",to)},zc=()=>{var t,e;(t=$())==null||t.removeEventListener("error",ro),(e=$())==null||e.removeEventListener("unhandledrejection",to)};(Go=$())==null||Go.addEventListener("beforeunload",()=>{eo.processQueue()});class no extends Ni{constructor(e){const r=`${e.message}`;super(r),this.response=e}get originalErrorMessage(){return this.response.message}}const K=async(t,e,r,n)=>{n&&k(n,{...e});const o=await t.send(e);if(Bc(o))throw new no(o);if(!Gc(o,r)){const s=r.safeParse(o);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",r,"Actual:",o),s.error)}return n&&k(n,{...o}),o},Gc=(t,e)=>e.safeParse(t).success,Bc=t=>li.safeParse(t).success,qc=async(t,e)=>await K(t,{type:"get_checkout_preview",payload:e},Cn),q=async t=>await K(t,{type:"get_prefill",payload:{}},Pn),it=async(t,e)=>await K(t,{type:"v2_start_payment_flow",payload:e},Tn,"start_payment_flow"),Yc=async(t,e)=>await K(t,{type:"start_payment_flow_for_cc",payload:e},Ci,"start_payment_flow_for_cc"),Wc=async(t,e)=>{k("start_payment_flow_for_pr",{...e});const r=await K(t,{type:"start_payment_flow_for_pr",payload:e},Tn);return k("start_payment_flow_for_pr_result",{...r}),r},ce=async(t,e)=>await K(t,{type:"confirm_payment_flow",payload:e},Sa,"confirm_payment_flow"),Hc=async(t,e)=>await K(t,{type:"finalize_setup_payment_method",payload:e},An,"finalize_setup_payment_method"),Kc=async(t,e)=>await K(t,{type:"check_if_popup_window_verified",payload:e},Ca,"check_if_popup_window_verified"),Jc=async(t,e,r)=>{const n=await qc(t,{secure_token:e,promotion_code:r}),o=new Set(n.preview.invoices.map(c=>c.currency));if(o.size!==1)throw new Error(`Expected exactly one currency, got ${o.size}`);const s=o.values().next().value??"usd",i=Ti(n.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:s,amountAtom:i}},ct=async(t,e,r,n)=>{if(r)return{amountAtom:0,currency:"usd"};{n=n||void 0;const o=await Jc(t,e,n);return{amountAtom:o.amountAtom,currency:o.currency}}},Qc=async(t,e)=>{if(t.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(t.values()).map(n=>K(n,{type:"tokenize_card",payload:e},ba)))},oo=async(t,e)=>await K(t,{type:"checkout_card_elements",payload:e},Sr,"checkout_card_elements"),Xc=async(t,e)=>await K(t,{type:"setup_payment_method",payload:e},An,"setup_checkout"),Zr=async(t,e)=>await K(t,{type:"checkout",payload:e},Sr,"perform_checkout"),so=1e3,el=async(t,e)=>{console.log(e);const n=await vn({iframe:t,debug:!0,timeout:so,childOrigin:"*"}).promise,o=await K(n,{type:"ping-3ds-status"},Ea);return console.log("🟢 CDE connection successful! Stopping polling... Result:",o),o},Vr=async(t,e)=>await K(t,{type:"prepare_payment_flow",payload:e},Pi,"prepare_payment_flow"),ao=async(t,e)=>{try{return(await K(t,{type:"get_standardized_error_code",payload:{message:e}},Si)).error_code}catch(r){return console.error("[cde-client] Error during getStandardizedErrorCode:",ne(r)),"PAYMENT_FAILED_GENERIC"}},tl=async(t,e)=>await K(t,{type:"set_user_device_token",payload:{device_token:e}},Ai),{log__:Wu,err__:rl}=F("common"),Mt=t=>{if(t.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${t.payment_methods.length}`);return{payment_method_id:t.payment_methods[0].id}},le=(t,e)=>{const r=t.find(n=>e.safeParse(n).success);if(!r)throw rl("No CPMs found for model. All models:",t),new Error("No CPMs found for model");return e.parse(r)},nl=t=>({new_customer_email:t.email,new_customer_address:{zip_code:t.zipCode,country:t.country},new_customer_first_name:t.firstName,new_customer_last_name:t.lastName}),dr=async t=>{const{log__:e}=F(t.logPrefix),r=await q(t.anyCdeConnection),n=Mt(t.confirmResult);if(r.mode==="setup")return e("Setting up payment method..."),{mode:"setup",result:await Hc(t.anyCdeConnection,{secure_token:r.token,pm_id:n.payment_method_id})};{e("Doing checkout...");const o={secure_token:r.token,payment_input:{provider_type:t.checkoutPaymentMethod.provider},customer_email:t.requiredFormFields[m.EMAIL],customer_zip_code:t.requiredFormFields[m.ZIP_CODE],customer_country:t.requiredFormFields[m.COUNTRY],promotion_code:t.requiredFormFields[m.PROMOTION_CODE],line_items:r.line_items,total_amount_atom:r.amount_total_atom,cancel_at_end:!1,checkout_payment_method:t.checkoutPaymentMethod,use_confirmed_pm_id:n.payment_method_id};return{mode:"checkout",result:await Zr(t.anyCdeConnection,o)}}},ol="@keyframes fadeIn{0%{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}.overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483648!important;display:flex;justify-content:center;align-items:center;background-color:#00000080}.container{max-width:500px;max-height:600px;width:100%;height:100%;background-color:#fff;position:relative;animation:fadeIn .3s ease-out}.frame,#adyen-container,#adyen-container>*{max-width:500px;max-height:600px;width:100%;height:100%;border:none}.cancel-button{position:absolute;background:transparent;border:none;font-size:1rem;color:#fff;cursor:pointer;top:-1.5rem;padding:0;right:0}",io=t=>{const e=document.createElement("template");e.innerHTML=`
13
13
  <style>
14
- ${sl}
14
+ ${ol}
15
15
  </style>
16
16
  <div class="overlay">
17
17
  <div class="container">
@@ -19,7 +19,7 @@ ${t.message}`),t.message)}else return Sr(t.message);if(typeof t=="object")try{re
19
19
  <iframe src="${t}" class="frame" id="three-ds-iframe" title="3D Secure verification" allow="payment"></iframe>
20
20
  </div>
21
21
  </div>
22
- `;const r=document.createElement("div"),n=r.attachShadow({mode:"open"});n.appendChild(e.content.cloneNode(!0));const o=n.querySelector("#three-ds-iframe"),s=n.querySelector(".cancel-button");return document.body.appendChild(r),{host:r,iframe:o,cancelButton:s}};function al(t,e,r){const n=async()=>{try{const s=await tl(t,r);s&&(clearInterval(o),e(s))}catch{}};n();const o=setInterval(n,ao);return o}function il({elements:t,pollingInterval:e,resolve:r}){const n=()=>{clearInterval(e),t.host.remove(),r({status:V.CANCELLED})};return t.cancelButton.addEventListener("click",n),()=>{t.cancelButton.removeEventListener("click",n)}}async function fr(t){const{url:e,baseUrl:r}=t,n=co(e);return new Promise(o=>{const s=l=>{setTimeout(()=>{n.host.remove()},1e3),o(l),c==null||c()},i=al(n.iframe,s,new URL(r).origin),c=il({elements:n,pollingInterval:i,resolve:o})})}const lo=async t=>{const e=await fr(t);if(e.status===V.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===V.FAILURE)throw new Error("3DS verification failed");return e.status!==V.SUCCESS&&ur(e.status),{href:e.href}},cl=(t,e)=>{const r=window.open(e,"_blank");if(!r)throw new Error(`${t} popup window blocked. Please allow popups for this site.`);return r},ll=async(t,e,r,n)=>{const{err__:o}=F("popup-verify");return new Promise((s,i)=>{const c=cl(t,n),l=setInterval(async()=>{try{const u=await Jc(e,r);if(u.present)clearInterval(l),c.close(),s({href:u.href});else if(c.closed)throw new Error(`${t} payment cancelled`)}catch(u){o(ne(u)),clearInterval(l),i(ne(u))}},1e3)})},{log__:uo,err__:po}=F("common-cc"),Fe=(t,e,r)=>{if(r){uo(`Received default field values: ${JSON.stringify(r)}`);for(const[o,s]of Object.entries(r))t[o]||(t[o]=s)}const n=xt.safeParse(t);if(!n.success){const o=n.error.format(),s=fn(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw po("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return n.data},ul=(t,e)=>{for(const r of t)if(r.success===!1)throw r.errors.forEach(n=>{const o=dn.safeParse(n.elementType);if(!o.success)po(`Unknown field name in onValidationError: ${n.elementType}. Error object:`,n);else{const s=o.data;e(s,n.errors)}}),uo(`Error tokenizing card: got validation errors: ${JSON.stringify(r.errors)}`),new Error("Got validation errors while tokenizing card")},ue=a.enum(["stripe","airwallex","authorize_net"]);ue.Enum.stripe;const fo=({scriptId:t,src:e,checkLoadedFn:r})=>{const n=new AbortController;return new Promise((o,s)=>{let i=document.createElement("script");i.src=e,i.id=t,i.async=!0;const c=document.getElementById(t);r()?o():c?i=c:document.body.appendChild(i),i.addEventListener("load",()=>{n.abort(),o()},{signal:n.signal}),i.addEventListener("error",()=>{n.abort(),s("Failed to load the script")},{signal:n.signal})})},mo=()=>fo({scriptId:"__op_internal_apple_pay_sdk",src:"https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",checkLoadedFn:()=>!!window.ApplePaySession||!!window.ApplePaySDK}),ho=(t,e)=>{const r=e.token.paymentMethod.billingContact,n=e.billingContact,o=e.shippingContact,s={...t};if(r||n||o){s[m.EMAIL]=s[m.EMAIL]||(r==null?void 0:r.emailAddress)||(n==null?void 0:n.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[m.COUNTRY]=s[m.COUNTRY]||(r==null?void 0:r.countryCode)||(n==null?void 0:n.countryCode)||(o==null?void 0:o.countryCode)||"US",s[m.ZIP_CODE]=s[m.ZIP_CODE]||(r==null?void 0:r.postalCode)||(n==null?void 0:n.postalCode)||(o==null?void 0:o.postalCode)||"00000";const i=s[m.FIRST_NAME]||(r==null?void 0:r.givenName)||(n==null?void 0:n.givenName)||(o==null?void 0:o.givenName)||"",c=s[m.LAST_NAME]||(r==null?void 0:r.familyName)||(n==null?void 0:n.familyName)||(o==null?void 0:o.familyName)||"";i||c?(s[m.FIRST_NAME]=i,s[m.LAST_NAME]=c):(s[m.FIRST_NAME]="_OP_UNKNOWN",s[m.LAST_NAME]="")}return s};a.object({data:a.object({messageHeaders:a.record(a.string(),a.any()),errors:a.array(a.any()),messageType:a.string(),messageBody:a.record(a.string(),a.any())}),origin:a.literal("https://applepay.cdn-apple.com")});const yo=({total:t,prefill:e})=>{var n;if(e.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:t.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${e.token}`,Ke).toString()};const r=(n=e.line_items)==null?void 0:n[0];if(r)return{paymentDescription:(r==null?void 0:r.description)??"",regularBilling:{amount:t.amount,label:(r==null?void 0:r.description)??"",recurringPaymentIntervalUnit:r==null?void 0:r.billing_interval,recurringPaymentIntervalCount:(r==null?void 0:r.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},_o=({overridePaymentRequest:t,initialPreview:e,prefill:r,defaultLabel:n="Total"})=>{var c,l;const o=(((c=t==null?void 0:t.amount)==null?void 0:c.currency)??(r==null?void 0:r.currency)??e.currency).toUpperCase(),i=((((l=t==null?void 0:t.amount)==null?void 0:l.amountAtom)??(e==null?void 0:e.amountAtom)??0)/100).toFixed(2);return{currencyCode:o,total:{label:(t==null?void 0:t.label)??n??"Total",type:t!=null&&t.pending?"pending":"final",amount:i}}},{log__:mr}=F("awx-apple-pay");async function dl(t,e){try{const n=(await zr(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),k("apple_pay_complete_merchant_validation",{...o})}catch(r){throw e.session.abort(),r}}async function pl(t,e){if(!t.redirect_url)throw new Error("No redirect URL found");mr("3DS Required, starting verification...",t);const{status:r}=await fr({url:t.redirect_url,baseUrl:e.baseUrl});if(mr(`╰ 3DS verification completed [Status: ${r}]`),r===V.CANCELLED)throw new Error("3DS verification cancelled");if(r===V.FAILURE)throw new Error("3DS verification failed");const n=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:t.their_pm_id,airwallex_consent_id:t.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return mr("[2nd] Confirm payment flow response",n),n}async function fl(t,e){var r,n,o,s,i;try{const c=t.payment,l=ho(e.nonCdeFormInputs,c),u=Fe(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues);k("billing_details_received",{...u});const _=(await ct(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[m.EMAIL],new_customer_first_name:u[m.FIRST_NAME],new_customer_last_name:u[m.LAST_NAME],new_customer_address:{zip_code:u[m.ZIP_CODE],country:u[m.COUNTRY]}})).required_user_actions[0].consent_id;if(!_)throw new Error("No consent ID received from payment flow");let f=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:_,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});mr("[1st] Confirm payment flow response",f);let h=(n=(r=f.payment_methods)==null?void 0:r[0])==null?void 0:n.id;const w=(o=f.required_user_actions)==null?void 0:o.find(E=>E.type==="airwallex_payment_consent");if(w!=null&&w.redirect_url&&w.consent_id&&w.their_pm_id&&(f=await pl(w,e),h=(i=(s=f.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!h)throw new Error("No PM ID found");const I={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(I),pr({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:f,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:ml,err__:Gr}=F("airwallex-cc"),hl=a.object({"op-airwallex-3ds-url":a.string(),"op-airwallex-initial-intent-id":a.string(),"op-airwallex-consent-id":a.string()}),yl=t=>{const e=hl.safeParse(t);if(!e.success){const r="Unable to process your credit card. Please contact support for assistance.",n=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw Gr(n),new Error(r)}return e.data},_l=t=>(t==null?void 0:t["op-airwallex-3ds-url"])!==void 0,gl=t=>{try{const e=new URL(t??"").searchParams.get("payment_intent_id");if(!e)throw new Error("No intent ID found in Airwallex 3DS verification result");return ml(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const r="Error verifying Airwallex 3DS verification result.";throw Gr(r,`Resulting URL: ${t}.
23
- Error: ${ne(e)}`),new Error(r)}},vl=async(t,e)=>{const r=yl(e),n=await lo({url:r["op-airwallex-3ds-url"],baseUrl:t}),o=gl(n.href??""),s=r["op-airwallex-initial-intent-id"];if(s!==o){const c="Unable to process your credit card. Please contact support for assistance.",l=`Intent ID from callback (${o}) does not match the initial intent ID (${s}).`;throw Gr(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:r["op-airwallex-consent-id"]}}},go=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),vo=a.object({provider:a.literal("google_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:Lt,err__:wo}=F("awx-apple-pay"),wl=Ge(async({context:t,formCallbacks:e})=>{const r={processor:ue.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,go);if(!n)return r;if(Lt("Loading Apple Pay script"),await mo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return Lt("Apple Pay is not available on this device/browser"),r;if(Lt("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return Lt("No active cards available for Apple Pay"),r;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async p=>{try{await z.airwallexApplePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){wo("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ue.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),bl=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,customParams:n,formCallbacks:o})=>{var I;const s=le(t.checkoutPaymentMethods,go),{overridePaymentRequest:i,initialPreview:c}=n,l=t.anyCdeConnection,u=await q(l),d=u.mode==="setup",{currencyCode:p,total:_}=_o({overridePaymentRequest:i,initialPreview:c,defaultLabel:(I=s==null?void 0:s.metadata)==null?void 0:I.processor_account_name}),f={countryCode:"US",currencyCode:p,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:_,recurringPaymentRequest:yo({total:_,prefill:u}),...(i==null?void 0:i.applePayPaymentRequest)??{}},h=new ApplePaySession(3,f),w={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:r,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o,defaultFieldValues:n==null?void 0:n.defaultFieldValues};return k("apple_pay_flow_started",{processor_name:e.processor_name,prefill:Xn(u,["brand"]),overridePaymentRequest:i}),new Promise((E,N)=>{const x=()=>{Lt("Payment cancelled by user"),N(new Error("Payment cancelled by user"))};h.oncancel=x,h.onvalidatemerchant=async O=>{try{await dl(O,w)}catch(U){N(U)}},h.onpaymentmethodselected=()=>{const O={newTotal:{..._}};h.completePaymentMethodSelection(O)},h.onpaymentauthorized=async O=>{k("apple_pay_payment_authorized");try{const U=await fl(O,w);E(U)}catch(U){N(U)}},h.begin()}).catch(E=>{throw wo("Apple Pay payment error",E),k("apple_pay_payment_error",{error:E}),E})}),hr=({gateway:t,gatewayMerchantId:e,merchantName:r,merchantId:n,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var p,_;const c=((p=s==null?void 0:s.amount)==null?void 0:p.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((_=s==null?void 0:s.amount)==null?void 0:_.currency)??(i==null?void 0:i.currency)??o.currency).toUpperCase(),d={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:t,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:n??"",merchantName:r},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?{...d,...s.googlePayPaymentRequest}:d},bo=()=>fo({scriptId:"__op_internal_google_pay_sdk",src:"https://pay.google.com/gp/p/js/pay.js",checkLoadedFn:()=>{var t,e;return!!((e=(t=window.google)==null?void 0:t.payments)!=null&&e.api)}});let Br=null;const Eo=async t=>await Qn(t)==="prod"?"PRODUCTION":"TEST",yr=async(t,e)=>{const r=await Eo(t);return Br===null&&(Br=new window.google.payments.api.PaymentsClient({environment:r,merchantInfo:e.merchantInfo})),Br},El=t=>{const e=t.required_user_actions.find(r=>r.type==="airwallex_payment_consent");return e?pn.parse(e):null},ko=(t,e)=>{var o,s,i,c;const r={...t},n=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(n){const[l,...u]=((c=(i=n.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;r[m.EMAIL]=r[m.EMAIL]||e.email||"op_unfilled@getopenpay.com",r[m.COUNTRY]=r[m.COUNTRY]||n.countryCode||"US",r[m.ADDRESS]=r[m.ADDRESS]||n.address1||"",r[m.CITY]=r[m.CITY]||n.locality||"",r[m.ZIP_CODE]=r[m.ZIP_CODE]||n.postalCode||"00000",r[m.STATE]=r[m.STATE]||n.administrativeArea||"";const p=r[m.FIRST_NAME]||l||"",_=r[m.LAST_NAME]||d||"";p||_?(r[m.FIRST_NAME]=p,r[m.LAST_NAME]=_):(r[m.FIRST_NAME]="_OP_UNKNOWN",r[m.LAST_NAME]="")}return r},{log__:de,err__:ut}=F("awx-google-pay"),kl=Ge(async({context:t,formCallbacks:e})=>{var p,_;const r={processor:ue.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,vo);if(!n)return r;de("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return ut("No gateway merchant ID found in processor account"),r;if(de("Loading Google Pay script"),await bo(),!((_=(p=window.google)==null?void 0:p.payments)!=null&&_.api))return ut("Google Pay SDK not loaded properly"),r;if(await Eo(t.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return ut("Google Pay merchant ID is required for production environment"),r;de("Google Pay SDK loaded",window.google.payments);try{const f=hr({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),h=await yr(t.baseUrl,f),{result:w}=await h.isReadyToPay(f);if(!w)return de("Google Pay is not available for this user"),r}catch(f){return ut("Error checking Google Pay availability",f),r}const i=t.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async f=>{try{z.airwallexGooglePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...f,initialPreview:u}})}catch(h){ut("Google Pay payment error",h),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:ue.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Cl=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{var f,h,w,I,E,N,x;de("Starting Google Pay flow...");const s=le(t.checkoutPaymentMethods,vo),{initialPreview:i,overridePaymentRequest:c}=o,l=s.metadata;if(!l.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const u=hr({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=t.anyCdeConnection,p=await q(d);k("google_pay_flow_started",{processor_name:s.processor_name,prefill:Xn(p,["brand"]),overridePaymentRequest:c});const _=await yr(t.baseUrl,u);try{const O=await _.loadPaymentData(u);de("Google Pay Payment data",O);const U=ko(r,O),W=Fe(U,n.get.onValidationError,o==null?void 0:o.defaultFieldValues);k("billing_details_received",{...W});const ke=(h=(f=O.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!ke)throw new Error("No payment token received from Google Pay");const Yu=await ct(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:W[m.EMAIL],new_customer_first_name:W[m.FIRST_NAME],new_customer_last_name:W[m.LAST_NAME],new_customer_address:{zip_code:W[m.ZIP_CODE],country:W[m.COUNTRY]}}),gr=El(Yu);de("Start flow next actions",gr);let We=await ce(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:gr==null?void 0:gr.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:ke}}}});de("[1st] Confirm payment flow response",We);let Wr=(I=(w=We.payment_methods)==null?void 0:w[0])==null?void 0:I.id;const He=(E=We.required_user_actions)==null?void 0:E.find(Vt=>Vt.type==="airwallex_payment_consent");if(He&&He.redirect_url){de("3DS Required, starting verification...",He);const{status:Vt}=await fr({url:He.redirect_url,baseUrl:t.baseUrl});if(de(`╰ 3DS verification completed [Status: ${Vt}]`),Vt===V.CANCELLED)throw new Error("3DS verification cancelled");if(Vt===V.FAILURE)throw new Error("3DS verification failed")}if(He&&!Wr&&(We=await ce(d,{secure_token:p.token,their_pm_id:He.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:He.consent_id}}),de("[2nd] Confirm payment flow response",We),Wr=(x=(N=We.payment_methods)==null?void 0:N[0])==null?void 0:x.id),!Wr)throw new Error("No PM ID found");return pr({logPrefix:"awx-googlepay",anyCdeConnection:d,checkoutPaymentMethod:e,requiredFormFields:W,confirmResult:We,usePayFirstFlow:!1})}catch(O){throw ut("Google Pay payment error",O),k("google_pay_payment_error",{error:O}),new Error((O==null?void 0:O.message)??"Unknown error")}});async function Sl(t,e){try{const n=(await zr(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),k("apple_pay_complete_merchant_validation",{...o})}catch(r){throw e.session.abort(),r}}async function Pl(t,e){var r,n;try{const o=t.payment,s=ho(e.nonCdeFormInputs,o),i=Fe(s,e.formCallbacks.get.onValidationError);k("billing_details_received",{...i}),await ct(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[m.EMAIL],new_customer_first_name:i[m.FIRST_NAME],new_customer_last_name:i[m.LAST_NAME],new_customer_address:{zip_code:i[m.ZIP_CODE],country:i[m.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((n=(r=l.payment_methods)==null?void 0:r[0])==null?void 0:n.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),pr({logPrefix:"authnet-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:i,confirmResult:l,usePayFirstFlow:!1})}catch(o){const s={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(s),o}}const Co=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),So=a.object({provider:a.literal("google_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:_r,err__:Po}=F("authnet-applepay"),Al=Ge(async({context:t,formCallbacks:e})=>{const r={processor:ue.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,Co);if(!n)return r;if(_r("Loading Apple Pay script"),await mo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return _r("Apple Pay is not available on this device/browser"),r;if(!await ApplePaySession.canMakePayments())return _r("No active cards available for Apple Pay"),r;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async p=>{try{await z.authorizeNetApplePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Po("Apple Pay payment error",_),k("apple_pay_payment_error",{error:_}),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ue.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),Tl=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,customParams:n,formCallbacks:o})=>{var I;const{initialPreview:s,overridePaymentRequest:i}=n,c=le(t.checkoutPaymentMethods,Co),{currencyCode:l,total:u}=_o({overridePaymentRequest:i,initialPreview:s,defaultLabel:(I=c==null?void 0:c.metadata)==null?void 0:I.processor_account_name}),d=t.anyCdeConnection,p=await q(d),_=p.mode==="setup",f={countryCode:"US",currencyCode:l,total:u,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],recurringPaymentRequest:yo({total:u,prefill:p}),...(i==null?void 0:i.applePayPaymentRequest)??{}};k("apple_pay_flow_started",{processor_name:e.processor_name,prefill:p,overridePaymentRequest:i});const h=new ApplePaySession(3,f),w={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:r,processorAccount:e.metadata,prefill:p,isSetupMode:_,baseUrl:t.baseUrl,formCallbacks:o};return new Promise((E,N)=>{h.oncancel=()=>{_r("Payment cancelled by user"),N(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async x=>{try{await Sl(x,w)}catch(O){N(O)}},h.onpaymentmethodselected=()=>{const x={newTotal:f.total};h.completePaymentMethodSelection(x)},h.onpaymentauthorized=async x=>{k("apple_pay_payment_authorized");try{const O=await Pl(x,w);E(O)}catch(O){N(O)}},h.begin()}).catch(E=>{throw Po("Apple Pay payment error",E),k("apple_pay_payment_error",{error:E}),E})}),{log__:Be,err__:jt}=F("authnet-googlepay"),xl=Ge(async({context:t,formCallbacks:e})=>{var d,p;Be("Initializing Authnet GooglePay flow");const r={processor:ue.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,So);if(!n)return r;Be("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return jt("No gateway merchant ID found in processor account"),r;if(Be("Loading Google Pay script"),await bo(),!((p=(d=window.google)==null?void 0:d.payments)!=null&&p.api))return jt("Google Pay SDK not loaded properly"),r;Be("Google Pay SDK loaded",window.google.payments);try{const _=hr({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),f=await yr(t.baseUrl,_),{result:h}=await f.isReadyToPay(_);if(!h)return Be("Google Pay is not available for this user"),r}catch(_){return jt("Error checking Google Pay availability",_),r}const s=t.anyCdeConnection,i=await q(s),c=i.mode==="setup",l=await lt(s,i.token,c,void 0),u=async _=>{try{z.authorizeNetGooglePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{..._,initialPreview:l}})}catch(f){jt("Google Pay payment error",f),k("google_pay_payment_error",{error:f}),e.get.onCheckoutError((f==null?void 0:f.message)??"Unknown error")}};return{processor:ue.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),Il=Ae(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:r,formCallbacks:n,customParams:o})=>{var f,h,w,I;const{initialPreview:s,overridePaymentRequest:i}=o,l=le(t.checkoutPaymentMethods,So).metadata,u=hr({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=t.anyCdeConnection,p=await q(d);k("google_pay_flow_started",{processor_name:r.processor_name,prefill:p,overridePaymentRequest:i});const _=await yr(t.baseUrl,u);try{const E=await _.loadPaymentData(u);Be("Google Pay Payment data",E);const N=ko(e,E),x=Fe(N,n.get.onValidationError);k("billing_details_received",{...x});const O=(h=(f=E.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!O)throw new Error("No payment token received from Google Pay");const U=await ct(d,{payment_provider:r.provider,checkout_payment_method:r,new_customer_email:x[m.EMAIL],new_customer_first_name:x[m.FIRST_NAME],new_customer_last_name:x[m.LAST_NAME],new_customer_address:{zip_code:x[m.ZIP_CODE],country:x[m.COUNTRY]}});Be("Start payment flow response",U);const W=await ce(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:r.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(O)}}});if(!((I=(w=W.payment_methods)==null?void 0:w[0])==null?void 0:I.id))throw new Error("No PM ID found");return pr({logPrefix:"authnet-googlepay",anyCdeConnection:d,checkoutPaymentMethod:r,requiredFormFields:x,confirmResult:W,usePayFirstFlow:!1})}catch(E){throw jt("Google Pay payment error",E),k("google_pay_payment_error",{error:E}),new Error((E==null?void 0:E.message)??"Unknown error")}}),{log__:Rl,err__:Ao}=F("pockyt-cc"),Nl=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),Ol=t=>{const e=Nl.safeParse(t);if(!e.success){const r="Unable to process your credit card. Please contact support for assistance.",n=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw Ao(n),new Error(r)}return e.data},To=t=>{try{const e=new URL(t??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return Rl(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const r="Error verifying 3DS verification result.";throw Ao(r,`Resulting URL: ${t}.
24
- Error: ${ne(e)}`),new Error(r)}},Ml=(t,e)=>new URL(t).searchParams.get(e),Dl=t=>(t==null?void 0:t["op-pockyt-3ds-url"])!==void 0,Ll=async(t,e)=>{const r=Ol(e),n=await lo({url:r["op-pockyt-3ds-url"],baseUrl:t});return{existing_cc:{vault_id:To(n.href??""),transaction_no:r["op-pockyt-txn-no"],reference_no:r["op-pockyt-ref-no"]}}},jl=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),Fl=a.enum(["ar","bg-BG","ca-ES","cs-CZ","da-DK","de-DE","el-GR","en-US","es-ES","et-EE","fi-FI","fr-FR","hr-HR","hu-HU","is-IS","it-IT","ja-JP","ko-KR","lt-LT","lv-LV","nl-NL","no-NO","pl-PL","pt-BR","pt-PT","ro-RO","ru-RU","sk-SK","sl-SI","sv-SE","zh-CN","zh-TW"]),{log__:dt,err__:Ft}=F("adyen-cc"),Ul=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":jl,"op-adyen-action":a.string()}),xo="Unable to process your credit card. Please contact support for assistance.",$l=t=>{const e=Ul.safeParse(t);if(!e.success)throw Ft(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`),new Error(xo);return e.data},Zl=t=>JSON.parse(t),Io=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,Vl=async()=>{dt("Waiting for Adyen SDK to load...");for(let t=0;t<10;t++)Io()||await Ar(500);if(!Io())throw Ft("Adyen SDK not loaded properly"),new Error(xo);return dt("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},zl=t=>{const{headers:e,locale:r,countryCode:n,component:o,host:s,cancelButton:i}=t,c=Zl(e["op-adyen-action"]);return dt(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{dt("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",_),s.remove()},d=h=>{Ft("Authentication failed. Result:",h),l({status:V.FAILURE,cleanup:u})},p=h=>{Ft("Adyen error:",h),l({status:V.FAILURE,cleanup:u})},_=()=>{l({status:V.CANCELLED,cleanup:u})};i.addEventListener("click",_);const f=(h,w,I)=>{s.remove(),l({status:V.SUCCESS,additionalDetails:h,cleanup:u})};Vl().then(h=>h({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:r,countryCode:n,onAdditionalDetails:f,onPaymentFailed:d,onError:p})).then(h=>{h.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},Gl=t=>{const e=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,r=t??e,n=Fl.safeParse(r);return n.success?(dt(`Resolved locale: ${n.data}`),n.data):(Ft(`Resolved invalid locale: ${r}. Defaulting to en-US.`),"en-US")},Bl=t=>(t==null?void 0:t["op-adyen-action"])!==void 0,ql=async(t,e,r)=>{const n=$l(e),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=co("http://example.com");i.replaceWith(o);const l=await zl({headers:n,locale:Gl(r),countryCode:t,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===V.FAILURE)throw new Error("3DS verification failed");if(l.status===V.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===V.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return dt("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else ur(l.status)},{log__:L,err__:Ro}=F("common-cc"),{log__:No}=F("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const Yl=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{var u;L("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=t.anyCdeConnection,i=await q(s);k("common_cc_flow_started",{...e,prefill:i}),L(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=Fe(r,n.get.onValidationError);k("billing_details_received",{...c});const l={session_id:t.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin}};try{L(`├ Tokenizing card info in CDE [Session: ${t.elementsSessionId}]`);const d=await Xc(o.currentCdeConnections,{session_id:t.elementsSessionId});if(ul(d,n.get.onValidationError),i.mode==="setup"){L(`├ Setting up payment method in CDE [Token: ${i.token}]`);const p=await el(s,l);return L(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{L(`├ Initial checkout flow. Checking out card info in CDE [Session: ${t.elementsSessionId}]`);const p=await so(s,l);return L("╰ Checkout completed successfully."),{mode:"checkout",result:p}}}catch(d){if(d instanceof oo&&d.originalErrorMessage.includes("3DS_REQUIRED")){L("├ Card requires 3DS, starting non-legacy payment flow"),L("Received 3DS error response headers:",d.response.headers),k("3ds_required",{...e,...d.response.headers});const p=Dl(d.response.headers);if(p){L("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const E=await Ll(t.baseUrl,d.response.headers);l.extra_metadata.pockyt=E}if(_l(d.response.headers)){L("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const E=await vl(t.baseUrl,d.response.headers);l.extra_metadata.airwallex=E}if(Bl(d.response.headers)){L("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const E=await ql(r[m.COUNTRY],d.response.headers,i.locale);l.extra_metadata.adyen=E}const h=await Wc(s,l);L("├ Payment flow result:",h);const w=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";p?L("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):w?(L("├ Using stripe 3DS flow"),await Ql(h)):(L("├ Using common 3DS flow"),await Jl(h,t.baseUrl));const I=h.cc_pm_id;if(i.mode==="setup"){L(`├ Confirming payment flow [cc_pm_id: ${I}]`);const E=await ce(s,{secure_token:i.token,existing_cc_pm_id:I});L("├ Confirm payment flow result received Result:",E);const N=Dt(E);return L(`╰ Setup completed successfully [PM ID: ${N.payment_method_id}]`),{mode:"setup",result:N}}else{L(`├ Checking out after 3DS flow [Flow: ${w?"legacy":"new"}]`);const E=await so(s,{...l,existing_cc_pm_id:I,do_not_use_legacy_cc_flow:w});return L("╰ Checkout completed successfully."),{mode:"checkout",result:E}}}throw Ro("╰ Error checking out card info in CDE"),Ro(d),d}}),Wl=t=>{const e=t.required_user_actions.find(r=>r.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Aa.parse(e)},Hl=["airwallex_payment_consent","adyen"],Kl=t=>{const e=t.required_user_actions.find(r=>Hl.includes(r.type));if(!e)throw new Error("No common 3DS action found");return Ca.parse(e)},Jl=async(t,e)=>{const r=Kl(t);if(r.redirect_url==="3DS_COMPLETE"){L("├ 3DS flow completed successfully"),k("3ds_complete");return}L(`├ Using common 3DS flow [URL: ${r.redirect_url}]`),k("3ds_redirect",{...r});const{status:n}=await fr({url:r.redirect_url,baseUrl:e});if(L(`╰ 3DS verification completed [Status: ${n}]`),n===V.CANCELLED)throw k("3ds_cancelled"),new Error("3DS verification cancelled");if(n===V.FAILURE)throw k("3ds_failure"),new Error("3DS verification failed")},Ql=async t=>{const e=Wl(t);k("3ds_stripe_redirect",{...e}),No(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Ma(e),k("3ds_stripe_complete"),No("╰ Stripe 3DS flow completed successfully")},Xl=1,eu=a.object({processor_name:a.literal("loop"),provider:a.literal("crypto"),metadata:a.object({merchant_id:a.string(),entity_id:a.string(),api_token:a.string(),supported_currencies:a.array(a.string()),environment:a.string()})}),{log__:ee,err__:Oo}=F("loop-crypto"),tu=a.object({loopFirstName:Z,loopLastName:Z,loopEmail:Z,[m.PROMOTION_CODE]:M}),ru=a.object({loopFirstName:M,loopLastName:M,loopEmail:M,[m.PROMOTION_CODE]:M}),Mo=(t,e,r,n)=>{const o=r.safeParse(t);if(!o.success){const s=o.error.format(),i=fn(s);for(const[c,l]of Object.entries(i))e(c,l,c);throw Oo("Got validation errors in non-CDE form fields",i),new Error("Got validation errors in non-CDE form fields")}return o.data},nu=Ge(async({context:t})=>{ee("Checking if there are any CPMs for Loop Crypto...");const e=le(t.checkoutPaymentMethods,eu);ee(`checkoutPaymentMethod: ${JSON.stringify(e)}`),ee("Starting Loop Crypto flow...");const r=await q(t.anyCdeConnection),n=await zr(t.anyCdeConnection,{checkout_payment_method:e});if(r.mode!=="setup"&&!e.metadata.supported_currencies.includes(r.currency))throw Error(`Currency ${r.currency} not enabled for Loop. Enabled currencies: ${e.metadata.supported_currencies}`);if(!n||!n.next_action_metadata)throw Error("Failed to fetch necessary setup data for Loop");const o=n.next_action_metadata;let s;r.mode==="setup"?s=Xl:s=r.amount_total_atom*o.token_price;const i=s,c=o.authorization_amount,l=er(),u={paymentUsdAmount:i,suggestedAuthorizationUsdAmount:c,customerRefId:l},d={apiKey:e.metadata.api_token,entityId:e.metadata.entity_id,merchantId:e.metadata.merchant_id,environment:e.metadata.environment};return{isAvailable:!0,widgetProps:u,initLoopConnectProps:d}}),ou=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{ee("Running Loop flow..."),ee("context",t),ee("checkoutPaymentMethod",e),ee("nonCdeFormInputs",r),ee("flowCallbacks",n),ee("customParams",o);let s;o!=null&&o.success?s=Mo(r,n.get.onValidationError,tu):s=Mo(r,n.get.onValidationError,ru);const i=t.anyCdeConnection,c=await q(t.anyCdeConnection),l=c.mode!=="setup",u=await ct(t.anyCdeConnection,{checkout_payment_method:e,payment_provider:e.provider,new_customer_email:s.loopEmail,new_customer_first_name:s.loopFirstName,new_customer_last_name:s.loopLastName,use_pay_first_flow:l,pay_first_flow_cart_info:l?{line_items:c.line_items,displayed_total_amount_atom:c.amount_total_atom}:void 0});if(!o)throw Error("Checkout failed. Failed to properly submit form data.");const d=await ce(i,{secure_token:c.token,their_pm_id:o.success?o.payin.paymentMethod.paymentMethodId:void 0,checkout_attempt_id:c.mode!=="setup"?u.checkout_attempt_id:void 0,processor_specific_metadata:{loop_customer:o.success?o.customer:void 0,loop_payin:o.success?o.payin:void 0,loop_failure_details:o.success?void 0:o.failureDetails,loop_debug_info:o.success?void 0:o.debugInfo,loop_success:o.success}});if(ee(`Confirm result: ${d}`),c.mode==="setup"){ee("Doing payment setup..."),ee("├ Confirm payment flow result received Result:",d);const p=Dt(d);return ee(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{if(ee("Doing checkout..."),!d.pay_first_success_response)throw Oo("Checkout failed, no pay-first success response:",d),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:d.pay_first_success_response}}}),{log__:we,err__:Do}=F("pockyt-paypal"),su=a.object({processor_name:a.literal("pockyt"),provider:a.literal("paypal")});a.array(a.object({paypal_iframe_url:a.string(),verify_token:a.string()})).length(1);const au=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{var W,ke;we("Running Pockyt Paypal flow...");const s=t.anyCdeConnection,i=await q(s);we("Verifying CPM...");const c=su.parse(e);we("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=Fe(r,n.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=ol(u);we(`Starting payment flow... Mode: ${i.mode}`);const p=er(),_=i.mode!=="setup",f={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:_,pay_first_flow_cart_info:_?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((W=o==null?void 0:o.settings)!=null&&W.useRedirectFlow),frontend_token_for_redirect_flow:p},...d},h=new URL("/app/pre-action/start/",t.baseUrl).toString(),w=btoa(JSON.stringify(f)),I=new URLSearchParams({st:i.token,r:w}),E=`${h}?${I.toString()}`;if((ke=o==null?void 0:o.settings)!=null&&ke.useRedirectFlow)throw we("Starting redirect mode for PayPal..."),window.location.href=E,await Ar(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");we("Starting popup mode for PayPal..."),we("Opening paypal iframe...");const N=await ll("PayPal",s,p,E);we("Paypal flow result",N);const x=To(N.href),O=Ml(N.href,"catt");if(!O)throw Do("Checkout attempt ID not found in redirect URL:",N.href),new Error("Checkout attempt ID not found in redirect URL");we(`Confirming payment flow using vault ID ${x}`);const U=await ce(s,{secure_token:i.token,their_pm_id:x,checkout_attempt_id:_?O:void 0});if(we("Confirm payment flow result",U),i.mode==="setup")return{mode:"setup",result:{payment_method_id:U.payment_methods[0].id}};if(!U.pay_first_success_response)throw Do("Checkout failed, no pay-first success response:",U),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:U.pay_first_success_response}}),Lo="ojs-stripe-link-btn",{log__:Y,err__:iu}=F("stripe-link"),cu=a.object({provider:a.literal("stripe_link"),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),lu=a.array(a.object({our_existing_pm_id:a.string()})).length(1),uu=Ge(async({context:t,formCallbacks:e})=>{const r=t.customInitParams.stripeLink;Y("Checking if there are any CPMs for Stripe Link...");const n=le(t.checkoutPaymentMethods,cu);Y("Starting stripe link flow...");const o=t.anyCdeConnection,s=await q(o),i=s.mode==="setup";Y("Creating stripe elements...");const c=await lt(o,s.token,i,void 0),{elements:l,stripe:u}=await Ia(n.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});Y("Creating express checkout...");const d=l.create("expressCheckout",{buttonHeight:r==null?void 0:r.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),p=()=>{d.mount(`#${Lo}`)},_=()=>{d.unmount()};return r!=null&&r.doNotMountOnInit?Y("NOT mounting stripe link button (doNotMountOnInit is true)"):(Y("Mounting stripe link button..."),p()),d.on("click",async f=>{if(Y("Stripe Link button clicked"),r!=null&&r.overrideLinkSubmit&&!await r.overrideLinkSubmit()){Y("Stripe Link submit aborted by overrideLinkSubmit");return}f.resolve()}),d.on("confirm",async f=>{Y("Stripe Link window confirmed",f);const h=await u.createPaymentMethod({elements:l,params:{billing_details:f.billingDetails}});h.error?(iu("error",h.error),e.get.onCheckoutError(h.error.message??"Stripe Link unknown error")):(Y("paymentMethod",h.paymentMethod),z.stripeLink.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{stripePM:h.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:p,dismountButton:_,waitForButtonToMount:async()=>await fu(Lo)}}}),du=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{Y("Running Stripe Link flow...");const s=t.anyCdeConnection;Y("Merging PM fields with form fields...");const i=pu(r,o.stripePM),c=Fe(i,n.get.onValidationError);k("billing_details_received",{...c}),Y("Starting payment flow...");const l=await ct(s,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:o.stripePM.id,new_customer_email:c[m.EMAIL],new_customer_first_name:c[m.FIRST_NAME],new_customer_last_name:c[m.LAST_NAME],new_customer_address:{zip_code:c[m.ZIP_CODE],country:c[m.COUNTRY]}});Y("Start payment flow response",l);const d=lu.parse(l.required_user_actions)[0].our_existing_pm_id,p=await q(s);if(p.mode==="setup"){Y("Doing payment setup...");const _=await ce(s,{secure_token:p.token,existing_cc_pm_id:d});return{mode:"setup",result:Dt(_)}}else{Y("Doing checkout...");const _={secure_token:p.token,payment_input:{provider_type:e.provider},customer_email:c[m.EMAIL],customer_zip_code:c[m.ZIP_CODE],customer_country:c[m.COUNTRY],promotion_code:c[m.PROMOTION_CODE],line_items:p.line_items,total_amount_atom:p.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Vr(s,_)}}}),pu=(t,e)=>{var l,u,d,p,_;const r={...t},[n,...o]=((u=(l=e.billing_details.name)==null?void 0:l.trim())==null?void 0:u.split(/\s+/))??[],s=o.join(" ")||void 0;r[m.EMAIL]=r[m.EMAIL]||((d=e.link)==null?void 0:d.email)||e.billing_details.email||"op_unfilled@getopenpay.com",r[m.ZIP_CODE]=r[m.ZIP_CODE]||((p=e.billing_details.address)==null?void 0:p.postal_code)||"00000",r[m.COUNTRY]=r[m.COUNTRY]||((_=e.billing_details.address)==null?void 0:_.country)||"US";const i=r[m.FIRST_NAME]||n||"",c=r[m.LAST_NAME]||s||"";return i||c?(r[m.FIRST_NAME]=i,r[m.LAST_NAME]=c):(r[m.FIRST_NAME]="_OP_UNKNOWN",r[m.LAST_NAME]=""),Y("Final form inputs:",r),r},fu=t=>new Promise(e=>{const r=()=>{const n=document.getElementById(t);n?e(n):requestAnimationFrame(r)};r()}),{log__:X,err__:mu}=F("stripe-pr"),hu=a.object({provider:a.union([a.literal("apple_pay"),a.literal("google_pay")]),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),yu=Ge(async({context:t,formCallbacks:e})=>{X("Checking if there are any CPMs for Stripe PR...");const r=le(t.checkoutPaymentMethods,hu);X("Initializing Stripe PR flow...");const n=t.anyCdeConnection,o=await q(n),s=o.mode==="setup";X("Getting initial preview amount");const i=await lt(n,o.token,s,void 0),c=await Ra(r.metadata.stripe_pk,i.amountAtom,i.currency,s);X("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return mu("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};X("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,p)=>z.stripePR.run({context:t,checkoutPaymentMethod:Ut(t.checkoutPaymentMethods,d),nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:p==null?void 0:p.overridePaymentRequest},initResult:{processor:ue.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:ue.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),_u=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o,initResult:s})=>{if(X("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=t.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const h=o.overridePaymentRequest;X("Overriding PR amount with",h),vu(c,h.amount,h.pending,h.applePayPaymentRequest,h.label)}X("Showing PR dialog..."),c.show();const l=await Na(c);X("Stripe PM added event:",l),X("Merging PM fields with form fields...");const u=gu(r,l),d=Fe(u,n.get.onValidationError);k("billing_details_received",{...d}),X("PR dialog finished. Starting payment flow...",d);const p=await Hc(i,{fields:d,checkoutPaymentMethod:e}),_=wu(p);X("Confirming PR with Stripe..."),await Oa(_,l);const f=await q(i);if(f.mode==="setup"){X("Confirming payment flow for setup...");const h=await ce(i,{secure_token:f.token});return{mode:"setup",result:Dt(h)}}else{X("Performing checkout...");const h={secure_token:f.token,payment_input:{provider_type:e.provider},customer_first_name:d[m.FIRST_NAME],customer_last_name:d[m.LAST_NAME],customer_email:d[m.EMAIL],customer_zip_code:d[m.ZIP_CODE],customer_country:d[m.COUNTRY],promotion_code:d[m.PROMOTION_CODE],line_items:f.line_items,total_amount_atom:f.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Vr(i,h)}}}),gu=(t,e)=>{var d,p,_,f;const r={...t},[n,...o]=((p=(d=e.payerName)==null?void 0:d.trim())==null?void 0:p.split(/\s+/))??[],s=o.join(" ")||void 0,i=(f=(_=e.paymentMethod)==null?void 0:_.billing_details)==null?void 0:f.address,c=e.shippingAddress;r[m.EMAIL]=r[m.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",r[m.ZIP_CODE]=r[m.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",r[m.COUNTRY]=r[m.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US";const l=r[m.FIRST_NAME]||n||"",u=r[m.LAST_NAME]||s||"";return l||u?(r[m.FIRST_NAME]=l,r[m.LAST_NAME]=u):(r[m.FIRST_NAME]="_OP_UNKNOWN",r[m.LAST_NAME]=""),X("Final form inputs:",r),r},vu=(t,e,r,n,o)=>{t.update({total:{amount:e.amountAtom,label:o??"Total",pending:r},currency:e.currency,applePay:n})},wu=t=>{if(t.required_user_actions.length!==1)throw new Error(`Error occurred.
25
- Details: got ${t.required_user_actions.length} required user actions`);return Ta.parse(t.required_user_actions[0])},Ut=(t,e,r)=>{const n=t.filter(o=>{const s=r===void 0?!0:o.processor_name===r,i=o.provider===e;return s&&i});if(n.length===0)throw console.warn("CPMs list",t),new Error(`No CPMs found with provider '${e}' and processor '${r}'`);return n.length!==1&&(console.warn("CPMs list",t),console.warn(`More than one CPM found with provider '${e}' and processor '${r}'`),k("more_than_one_cpm_found",{provider:e,processor:r,cpms:t})),n[0]},z={commonCC:{init:async()=>{},run:Yl},stripePR:{init:yu,run:_u},stripeLink:{init:uu,run:du},pockytPaypal:{run:au},airwallexGooglePay:{init:kl,run:Cl},airwallexApplePay:{init:wl,run:bl},loopCrypto:{init:nu,run:ou},authorizeNetApplePay:{init:Al,run:Tl},authorizeNetGooglePay:{init:xl,run:Il}},{log__:bu,err__:Eu}=F("init-flows"),qe=(t,e)=>{const r=new Mt;return{publisher:r,initialize:async n=>{try{if(r.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(n);bu(`✔ ${t} flow initialized successfully. Result:`,o),r.set(o)}catch(o){Eu(`𝙭 ${t} flow initialization failed. Error:`,ne(o),"Details:",o),r.throw(o,ne(o))}}}},ku=async(t,e,r)=>{await Promise.all(Object.values(t).map(n=>n.initialize({context:e,formCallbacks:r})))},Cu=()=>({stripePR:qe("Stripe PR",z.stripePR.init),stripeLink:qe("Stripe Link",z.stripeLink.init),airwallexGooglePay:qe("Airwallex GooglePay",z.airwallexGooglePay.init),airwallexApplePay:qe("Airwallex ApplePay",z.airwallexApplePay.init),loop:qe("Loop",z.loopCrypto.init),authorizeNetGooglePay:qe("Authnet GooglePay",z.authorizeNetGooglePay.init),authorizeNetApplePay:qe("Authnet ApplePay",z.authorizeNetApplePay.init)}),{err__:Su}=F("form-callbacks"),pe=a.function().optional(),jo=a.object({onFocus:pe,onBlur:pe,onChange:pe,onLoad:pe,onLoadError:pe,onValidationError:pe,onCheckoutStarted:pe,onCheckoutSuccess:pe,onSetupPaymentMethodSuccess:pe,onCheckoutError:pe,onPaymentRequestLoad:pe}),Ee=class Ee{constructor(){this.setCallbacks=e=>{this._callbacks=Ee.createEmptyCallbacks(),Object.entries(e).forEach(([r,n])=>{const o=Js(r,n??Ee.NOOP,Su);this._callbacks[r]=o})},this._callbacks=Ee.createEmptyCallbacks()}get get(){return{...this._callbacks}}};Ee.NOOP=()=>{},Ee.createEmptyCallbacks=()=>{const e={};return Object.keys(jo.keyof().enum).forEach(r=>{e[r]=Ee.NOOP}),e},Ee.fromObject=e=>{const r=new Ee;return r.setCallbacks(jo.parse(e)),r};let qr=Ee;const Pu="error",Au="debug",Tu=console.error,xu=console.debug,Ue=$();Ue&&(Ue._ojs_console_callbacks=[]),console.error=function(...t){var e;Tu.call(console,...t),(e=Ue==null?void 0:Ue._ojs_console_callbacks)==null||e.forEach(r=>r(Pu,...t))},console.debug=function(...t){var e;xu.call(console,...t),(e=Ue==null?void 0:Ue._ojs_console_callbacks)==null||e.forEach(r=>r(Au,...t))};const Fo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",$t=32,Iu=16,Uo=10,$o=0xffffffffffff;var Ye;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID"})(Ye||(Ye={}));class Zt extends Error{constructor(e,r){super(`${r} (${e})`),this.name="ULIDError",this.code=e}}function Ru(t){let e=Math.floor(t()*$t);return e===$t&&(e=$t-1),Fo.charAt(e)}function Nu(t){const e=Ou(),r=e&&(e.crypto||e.msCrypto)||null;if(typeof(r==null?void 0:r.getRandomValues)=="function")return()=>{const n=new Uint8Array(1);return r.getRandomValues(n),n[0]/255};if(typeof(r==null?void 0:r.randomBytes)=="function")return()=>r.randomBytes(1).readUInt8()/255;throw new Zt(Ye.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Ou(){return Lu()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Mu(t,e){let r="";for(;t>0;t--)r=Ru(e)+r;return r}function Du(t,e=Uo){if(isNaN(t))throw new Zt(Ye.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>$o)throw new Zt(Ye.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${$o}: ${t}`);if(t<0)throw new Zt(Ye.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===!1)throw new Zt(Ye.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let r,n="";for(let o=e;o>0;o--)r=t%$t,n=Fo.charAt(r)+n,t=(t-r)/$t;return n}function Lu(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function ju(t,e){const r=Nu(),n=Date.now();return Du(n,Uo)+Mu(Iu,r)}const Zo="op_analytics_device_token",Fu=()=>{const t=document.cookie.split(";").find(r=>r.includes(Zo));if(t)return t.split("=")[1];const e=ju();return Uu(e),e},Uu=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Zo}=${t}; path=/; expires=${e.toUTCString()}`};function $u(){try{const t=$();if(t!=null&&t.next||t!=null&&t.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";const e=$();if(e!=null&&e.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(n=>n.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(n=>n._reactRootContainer))return"react";const r=$();return r!=null&&r.Vue||r!=null&&r.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function Zu(t){var e,r,n;try{switch(t){case"react":return null;case"nextjs":{const o=$();return((e=o==null?void 0:o.next)==null?void 0:e.version)||((r=o==null?void 0:o.__NEXT_DATA__)==null?void 0:r.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const o=(n=$())==null?void 0:n.document,s=o==null?void 0:o.querySelector("[ng-version]");return s?s.getAttribute("ng-version"):null}default:return null}}catch{return null}}function Vu(){const t=$u(),e=Zu(t);return{framework:t,version:e}}class zu{constructor(e,r,n,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if(Vo(s.origin)!==Vo(this.baseUrl)||typeof s.data=="object"&&s.data.penpal||typeof s.data=="object"&&s.data.source&&s.data.source==="react-devtools-bridge")return;let i=null;try{i=$a(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=r,this.formCallbacks=n,this.internalCallbacks=o}}const Vo=t=>new URL(t).origin;async function Gu(t,e){const n=await wn({iframe:t,debug:!1,childOrigin:e}).promise,o=await ci(n);if(!li(n,o))throw new Error("Got invalid CDE connection object");return n}class Bu{constructor(){this.connections=new Map}addConnection(e,r){this.connections.set(e,r)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const qu=(t,e,r)=>{const{stripePR:n}=t;n.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&zo("apple_pay",s,e,r,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&zo("google_pay",s,e,r,u)}}};r.get.onPaymentRequestLoad(l)}})},zo=(t,e,r,n,o)=>z.stripePR.run({context:r,checkoutPaymentMethod:Ut(r.checkoutPaymentMethods,t),nonCdeFormInputs:_e(r.formDiv),formCallbacks:n,customParams:{provider:t,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),Go="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:be,err__:xe}=F("op-form"),Ie=class Ie{constructor(e){var o;this.cdeLoadEvent=new Mt,this.anyCdeConn=new Mt,this.context=new Mt,this.initFlows=Cu(),this.startFormInit=async()=>{try{const s=this.createElement(ye.CDE_BRIDGE);s.node.id="__op_internal_cde_bridge",s.node.ariaHidden="true",Object.assign(s.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),s.mount("body"),be("CDE bridge element mounted"),be("Initializing OpenPay form:"),be("├ Waiting for CDE load event...");const i=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Go});be("├ CDE load event received"),be("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Go});be("├ CDE connection received"),await rl(c,this.deviceToken),be("├ Creating OJS context, setting up handlers...");const l=Ie.buildOjsFlowContext(this.config,i,c,this.getFormDiv());this.context.set(l),qu(this.initFlows,l,this.formCallbacks),be("├ Starting OJS init flows..."),await ku(this.initFlows,l,this.formCallbacks),this.formCallbacks.get.onLoad(i.totalAmountAtoms,i.currency),be("╰ Done initializing OJS flows."),k("form_loaded")}catch(s){const i=ne(s);xe("╰ Error initializing OP form:",i),k("form_init_error",{error:i}),this.formCallbacks.get.onLoadError(i)}},this.setFormHeight=s=>{this.formProperties.height=s,this.registeredElements&&Object.values(this.registeredElements).forEach(i=>{!i||i.type===ye.CDE_BRIDGE||(i.node.style.height=s)})},this.onCdeLoaded=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(s),k("cde_loaded"))},this.onCdeLoadError=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(s),s),k("cde_load_error",{error:s}))},this.createElement=(s,i={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const c=Xs.parse(s),l=document.createElement("iframe"),u=this.buildQueryString(i);l.name=`${c}-element`;const d=new URL(`/app/v1/${l.name}/`,this.config.baseUrl);return d.search=u.toString(),l.src=d.href,l.style.border="none",l.style.width="100%",this.registerIframe(c,l)},this.registerIframe=(s,i)=>{const c={type:s,node:i,mount:l=>{var u;(u=document.querySelector(l))==null||u.appendChild(i),k("element_mounted",{element_type:s})}};return this.connectToElement({type:c.type,node:c.node}),this.registeredElements||(this.registeredElements={[ye.CARD]:void 0,[ye.CARD_NUMBER]:void 0,[ye.CARD_EXPIRY]:void 0,[ye.CARD_CVC]:void 0,[ye.CDE_BRIDGE]:void 0}),this.registeredElements[s]=c,c},this.buildQueryString=s=>{const i=new URLSearchParams;return i.append("referer",this.referrer),i.append("formId",this.formId),s.styles&&i.append("styles",Da(s.styles)),i.append("secureToken",this.config.checkoutSecureToken),i},this.connectToElement=s=>{Gu(s.node).then(i=>{this.connectionManager.addConnection(s.type,i),!this.anyCdeConn.current.isSuccess&&s.type===ye.CDE_BRIDGE&&this.anyCdeConn.set(i)}).catch(i=>xe("[FORM] Error connecting to CDE iframe",i))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{k("submit_card");const s=this.context.getValueIfLoadedElse(null);if(!s){xe("Please wait for the form to finish loading before submitting.");return}z.commonCC.run({context:s,checkoutPaymentMethod:Ut(s.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:_e(s.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){xe("Please wait for the form to finish loading before getting available payment methods.");return}const i={airwallexGooglePay:re.airwallexGooglePay,airwallexApplePay:re.airwallexApplePay,authorizeNetGooglePay:re.authorizenetGooglePay,authorizeNetApplePay:re.authorizenetApplePay},c=Object.entries(this.initFlows).map(([l,u])=>({name:i[l]??l,...u.publisher.getValueIfLoadedElse(null)}));return k("get_available_payment_methods",{available_payment_methods:c}),c},this.generalSubmit=(s,i)=>{k("general_form_submit",{method:s,settings:i});const c=this.context.getValueIfLoadedElse(null);if(!c){xe("Please wait for the form to finish loading before submitting.");return}switch(s){case re.pockytPaypal:return z.pockytPaypal.run({context:c,checkoutPaymentMethod:Ut(c.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:_e(c.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:i},initResult:void 0});case re.airwallexGooglePay:{const l=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!l){xe("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.airwallexApplePay:{const l=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!l){xe("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.authorizenetGooglePay:{const l=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!l){xe("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.authorizenetApplePay:{const l=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!l){xe("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.loopCrypto:return z.loopCrypto.run({context:c,checkoutPaymentMethod:Ut(c.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:_e(c.formDiv),formCallbacks:this.formCallbacks,customParams:i,initResult:void 0});default:ur(s)}},this.submit=this.submitCard,this.destroy=()=>{var s;be("Destroying OpenPay form...");for(const i of Object.values(this.registeredElements??{}))i&&i.node.remove();(s=$())==null||s.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),Gc(),this.registeredElements=null,delete window.ojs,k("form_destroyed")},this.updateCallbacks=s=>{this.formCallbacks.setCallbacks(s)},Ie.assignAsSingleton(this),this.ojsVersion="0.2.31",this.ojsReleaseVersion="0.2.31",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=qr.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${er()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Bu,this.deviceToken=Fu(),zc();const{framework:r,version:n}=Vu();Qn(this.baseUrl).then(s=>{if(!Zr.current.isSuccess){const i={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:s,framework:r,frameworkVersion:n,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl};Zr.set(i)}}),k("form_init"),this.eventHandler=new zu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),(o=$())==null||o.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}};Ie.ojsFlows=z,Ie.assignAsSingleton=e=>{if(Ie.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},Ie.getInstance=()=>window.ojs??null,Ie.buildOjsFlowContext=(e,r,n,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??Ke).origin,formDiv:o,elementsSessionId:r.sessionId,checkoutPaymentMethods:r.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Yr=Ie;Ce.FieldName=m,Ce.OpenPayForm=Yr,Ce.SubmitMethod=Qs,Ce.SubmitMethods=re,Object.defineProperty(Ce,Symbol.toStringTag,{value:"Module"})});
22
+ `;const r=document.createElement("div"),n=r.attachShadow({mode:"open"});n.appendChild(e.content.cloneNode(!0));const o=n.querySelector("#three-ds-iframe"),s=n.querySelector(".cancel-button");return document.body.appendChild(r),{host:r,iframe:o,cancelButton:s}};function sl(t,e,r){const n=async()=>{try{const s=await el(t,r);s&&(clearInterval(o),e(s))}catch{}};n();const o=setInterval(n,so);return o}function al({elements:t,pollingInterval:e,resolve:r}){const n=()=>{clearInterval(e),t.host.remove(),r({status:V.CANCELLED})};return t.cancelButton.addEventListener("click",n),()=>{t.cancelButton.removeEventListener("click",n)}}async function pr(t){const{url:e,baseUrl:r}=t,n=io(e);return new Promise(o=>{const s=l=>{setTimeout(()=>{n.host.remove()},1e3),o(l),c==null||c()},i=sl(n.iframe,s,new URL(r).origin),c=al({elements:n,pollingInterval:i,resolve:o})})}const co=async t=>{const e=await pr(t);if(e.status===V.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===V.FAILURE)throw new Error("3DS verification failed");return e.status!==V.SUCCESS&&lr(e.status),{href:e.href}},il=(t,e)=>{const r=window.open(e,"_blank");if(!r)throw new Error(`${t} popup window blocked. Please allow popups for this site.`);return r},cl=async(t,e,r,n)=>{const{err__:o}=F("popup-verify");return new Promise((s,i)=>{const c=il(t,n),l=setInterval(async()=>{try{const u=await Kc(e,r);if(u.present)clearInterval(l),c.close(),s({href:u.href});else if(c.closed)throw new Error(`${t} payment cancelled`)}catch(u){o(ne(u)),clearInterval(l),i(ne(u))}},1e3)})},{log__:lo,err__:uo}=F("common-cc"),Fe=(t,e,r)=>{if(r){lo(`Received default field values: ${JSON.stringify(r)}`);for(const[o,s]of Object.entries(r))t[o]||(t[o]=s)}const n=Tt.safeParse(t);if(!n.success){const o=n.error.format(),s=pn(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw uo("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return n.data},ll=(t,e)=>{for(const r of t)if(r.success===!1)throw r.errors.forEach(n=>{const o=un.safeParse(n.elementType);if(!o.success)uo(`Unknown field name in onValidationError: ${n.elementType}. Error object:`,n);else{const s=o.data;e(s,n.errors)}}),lo(`Error tokenizing card: got validation errors: ${JSON.stringify(r.errors)}`),new Error("Got validation errors while tokenizing card")},ue=a.enum(["stripe","airwallex","authorize_net"]);ue.Enum.stripe;const po=({scriptId:t,src:e,checkLoadedFn:r})=>{const n=new AbortController;return new Promise((o,s)=>{let i=document.createElement("script");i.src=e,i.id=t,i.async=!0;const c=document.getElementById(t);r()?o():c?i=c:document.body.appendChild(i),i.addEventListener("load",()=>{n.abort(),o()},{signal:n.signal}),i.addEventListener("error",()=>{n.abort(),s("Failed to load the script")},{signal:n.signal})})},fo=()=>po({scriptId:"__op_internal_apple_pay_sdk",src:"https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",checkLoadedFn:()=>!!window.ApplePaySession||!!window.ApplePaySDK}),mo=(t,e)=>{const r=e.token.paymentMethod.billingContact,n=e.billingContact,o=e.shippingContact,s={...t};if(r||n||o){s[m.EMAIL]=s[m.EMAIL]||(r==null?void 0:r.emailAddress)||(n==null?void 0:n.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[m.COUNTRY]=s[m.COUNTRY]||(r==null?void 0:r.countryCode)||(n==null?void 0:n.countryCode)||(o==null?void 0:o.countryCode)||"US",s[m.ZIP_CODE]=s[m.ZIP_CODE]||(r==null?void 0:r.postalCode)||(n==null?void 0:n.postalCode)||(o==null?void 0:o.postalCode)||"00000";const i=s[m.FIRST_NAME]||(r==null?void 0:r.givenName)||(n==null?void 0:n.givenName)||(o==null?void 0:o.givenName)||"",c=s[m.LAST_NAME]||(r==null?void 0:r.familyName)||(n==null?void 0:n.familyName)||(o==null?void 0:o.familyName)||"";i||c?(s[m.FIRST_NAME]=i,s[m.LAST_NAME]=c):(s[m.FIRST_NAME]="_OP_UNKNOWN",s[m.LAST_NAME]="")}return s};a.object({data:a.object({messageHeaders:a.record(a.string(),a.any()),errors:a.array(a.any()),messageType:a.string(),messageBody:a.record(a.string(),a.any())}),origin:a.literal("https://applepay.cdn-apple.com")});const ho=({total:t,prefill:e})=>{var n;if(e.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:t.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${e.token}`,He).toString()};const r=(n=e.line_items)==null?void 0:n[0];if(r)return{paymentDescription:(r==null?void 0:r.description)??"",regularBilling:{amount:t.amount,label:(r==null?void 0:r.description)??"",recurringPaymentIntervalUnit:r==null?void 0:r.billing_interval,recurringPaymentIntervalCount:(r==null?void 0:r.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},yo=({overridePaymentRequest:t,initialPreview:e,prefill:r,defaultLabel:n="Total"})=>{var c,l;const o=(((c=t==null?void 0:t.amount)==null?void 0:c.currency)??(r==null?void 0:r.currency)??e.currency).toUpperCase(),i=((((l=t==null?void 0:t.amount)==null?void 0:l.amountAtom)??(e==null?void 0:e.amountAtom)??0)/100).toFixed(2);return{currencyCode:o,total:{label:(t==null?void 0:t.label)??n??"Total",type:t!=null&&t.pending?"pending":"final",amount:i}}},{log__:fr}=F("awx-apple-pay");async function ul(t,e){try{const n=(await Vr(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),k("apple_pay_complete_merchant_validation",{...o})}catch(r){throw e.session.abort(),r}}async function dl(t,e){if(!t.redirect_url)throw new Error("No redirect URL found");fr("3DS Required, starting verification...",t);const{status:r}=await pr({url:t.redirect_url,baseUrl:e.baseUrl});if(fr(`╰ 3DS verification completed [Status: ${r}]`),r===V.CANCELLED)throw new Error("3DS verification cancelled");if(r===V.FAILURE)throw new Error("3DS verification failed");const n=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:t.their_pm_id,airwallex_consent_id:t.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return fr("[2nd] Confirm payment flow response",n),n}async function pl(t,e){var r,n,o,s,i;try{const c=t.payment,l=mo(e.nonCdeFormInputs,c),u=Fe(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues);k("billing_details_received",{...u});const _=(await it(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[m.EMAIL],new_customer_first_name:u[m.FIRST_NAME],new_customer_last_name:u[m.LAST_NAME],new_customer_address:{zip_code:u[m.ZIP_CODE],country:u[m.COUNTRY]}})).required_user_actions[0].consent_id;if(!_)throw new Error("No consent ID received from payment flow");let f=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:_,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});fr("[1st] Confirm payment flow response",f);let h=(n=(r=f.payment_methods)==null?void 0:r[0])==null?void 0:n.id;const w=(o=f.required_user_actions)==null?void 0:o.find(E=>E.type==="airwallex_payment_consent");if(w!=null&&w.redirect_url&&w.consent_id&&w.their_pm_id&&(f=await dl(w,e),h=(i=(s=f.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!h)throw new Error("No PM ID found");const I={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(I),dr({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:f,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:fl,err__:zr}=F("airwallex-cc"),ml=a.object({"op-airwallex-3ds-url":a.string(),"op-airwallex-initial-intent-id":a.string(),"op-airwallex-consent-id":a.string()}),hl=t=>{const e=ml.safeParse(t);if(!e.success){const r="Unable to process your credit card. Please contact support for assistance.",n=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw zr(n),new Error(r)}return e.data},yl=t=>(t==null?void 0:t["op-airwallex-3ds-url"])!==void 0,_l=t=>{try{const e=new URL(t??"").searchParams.get("payment_intent_id");if(!e)throw new Error("No intent ID found in Airwallex 3DS verification result");return fl(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const r="Error verifying Airwallex 3DS verification result.";throw zr(r,`Resulting URL: ${t}.
23
+ Error: ${ne(e)}`),new Error(r)}},gl=async(t,e)=>{const r=hl(e),n=await co({url:r["op-airwallex-3ds-url"],baseUrl:t}),o=_l(n.href??""),s=r["op-airwallex-initial-intent-id"];if(s!==o){const c="Unable to process your credit card. Please contact support for assistance.",l=`Intent ID from callback (${o}) does not match the initial intent ID (${s}).`;throw zr(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:r["op-airwallex-consent-id"]}}},_o=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),go=a.object({provider:a.literal("google_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:Dt,err__:vo}=F("awx-apple-pay"),vl=ze(async({context:t,formCallbacks:e})=>{const r={processor:ue.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,_o);if(!n)return r;if(Dt("Loading Apple Pay script"),await fo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return Dt("Apple Pay is not available on this device/browser"),r;if(Dt("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return Dt("No active cards available for Apple Pay"),r;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await ct(i,c.token,l,void 0),d=async p=>{try{await z.airwallexApplePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){vo("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ue.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),wl=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,customParams:n,formCallbacks:o})=>{var I;const s=le(t.checkoutPaymentMethods,_o),{overridePaymentRequest:i,initialPreview:c}=n,l=t.anyCdeConnection,u=await q(l),d=u.mode==="setup",{currencyCode:p,total:_}=yo({overridePaymentRequest:i,initialPreview:c,defaultLabel:(I=s==null?void 0:s.metadata)==null?void 0:I.processor_account_name}),f={countryCode:"US",currencyCode:p,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:_,recurringPaymentRequest:ho({total:_,prefill:u}),...(i==null?void 0:i.applePayPaymentRequest)??{}},h=new ApplePaySession(3,f),w={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:r,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o,defaultFieldValues:n==null?void 0:n.defaultFieldValues};return k("apple_pay_flow_started",{processor_name:e.processor_name,prefill:Qn(u,["brand"]),overridePaymentRequest:i}),new Promise((E,N)=>{const x=()=>{Dt("Payment cancelled by user"),N(new Error("Payment cancelled by user"))};h.oncancel=x,h.onvalidatemerchant=async O=>{try{await ul(O,w)}catch(U){N(U)}},h.onpaymentmethodselected=()=>{const O={newTotal:{..._}};h.completePaymentMethodSelection(O)},h.onpaymentauthorized=async O=>{k("apple_pay_payment_authorized");try{const U=await pl(O,w);E(U)}catch(U){N(U)}},h.begin()}).catch(E=>{throw vo("Apple Pay payment error",E),k("apple_pay_payment_error",{error:E}),E})}),mr=({gateway:t,gatewayMerchantId:e,merchantName:r,merchantId:n,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var p,_;const c=((p=s==null?void 0:s.amount)==null?void 0:p.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((_=s==null?void 0:s.amount)==null?void 0:_.currency)??(i==null?void 0:i.currency)??o.currency).toUpperCase(),d={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:t,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:n??"",merchantName:r},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?{...d,...s.googlePayPaymentRequest}:d},wo=()=>po({scriptId:"__op_internal_google_pay_sdk",src:"https://pay.google.com/gp/p/js/pay.js",checkLoadedFn:()=>{var t,e;return!!((e=(t=window.google)==null?void 0:t.payments)!=null&&e.api)}});let Gr=null;const bo=async t=>await Jn(t)==="prod"?"PRODUCTION":"TEST",hr=async(t,e)=>{const r=await bo(t);return Gr===null&&(Gr=new window.google.payments.api.PaymentsClient({environment:r,merchantInfo:e.merchantInfo})),Gr},bl=t=>{const e=t.required_user_actions.find(r=>r.type==="airwallex_payment_consent");return e?dn.parse(e):null},Eo=(t,e)=>{var o,s,i,c;const r={...t},n=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(n){const[l,...u]=((c=(i=n.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;r[m.EMAIL]=r[m.EMAIL]||e.email||"op_unfilled@getopenpay.com",r[m.COUNTRY]=r[m.COUNTRY]||n.countryCode||"US",r[m.ADDRESS]=r[m.ADDRESS]||n.address1||"",r[m.CITY]=r[m.CITY]||n.locality||"",r[m.ZIP_CODE]=r[m.ZIP_CODE]||n.postalCode||"00000",r[m.STATE]=r[m.STATE]||n.administrativeArea||"";const p=r[m.FIRST_NAME]||l||"",_=r[m.LAST_NAME]||d||"";p||_?(r[m.FIRST_NAME]=p,r[m.LAST_NAME]=_):(r[m.FIRST_NAME]="_OP_UNKNOWN",r[m.LAST_NAME]="")}return r},{log__:de,err__:lt}=F("awx-google-pay"),El=ze(async({context:t,formCallbacks:e})=>{var p,_;const r={processor:ue.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,go);if(!n)return r;de("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return lt("No gateway merchant ID found in processor account"),r;if(de("Loading Google Pay script"),await wo(),!((_=(p=window.google)==null?void 0:p.payments)!=null&&_.api))return lt("Google Pay SDK not loaded properly"),r;if(await bo(t.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return lt("Google Pay merchant ID is required for production environment"),r;de("Google Pay SDK loaded",window.google.payments);try{const f=mr({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),h=await hr(t.baseUrl,f),{result:w}=await h.isReadyToPay(f);if(!w)return de("Google Pay is not available for this user"),r}catch(f){return lt("Error checking Google Pay availability",f),r}const i=t.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await ct(i,c.token,l,void 0),d=async f=>{try{z.airwallexGooglePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...f,initialPreview:u}})}catch(h){lt("Google Pay payment error",h),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:ue.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),kl=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{var f,h,w,I,E,N,x;de("Starting Google Pay flow...");const s=le(t.checkoutPaymentMethods,go),{initialPreview:i,overridePaymentRequest:c}=o,l=s.metadata;if(!l.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const u=mr({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=t.anyCdeConnection,p=await q(d);k("google_pay_flow_started",{processor_name:s.processor_name,prefill:Qn(p,["brand"]),overridePaymentRequest:c});const _=await hr(t.baseUrl,u);try{const O=await _.loadPaymentData(u);de("Google Pay Payment data",O);const U=Eo(r,O),W=Fe(U,n.get.onValidationError,o==null?void 0:o.defaultFieldValues);k("billing_details_received",{...W});const ke=(h=(f=O.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!ke)throw new Error("No payment token received from Google Pay");const Vu=await it(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:W[m.EMAIL],new_customer_first_name:W[m.FIRST_NAME],new_customer_last_name:W[m.LAST_NAME],new_customer_address:{zip_code:W[m.ZIP_CODE],country:W[m.COUNTRY]}}),_r=bl(Vu);de("Start flow next actions",_r);let Ye=await ce(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:_r==null?void 0:_r.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:ke}}}});de("[1st] Confirm payment flow response",Ye);let Yr=(I=(w=Ye.payment_methods)==null?void 0:w[0])==null?void 0:I.id;const We=(E=Ye.required_user_actions)==null?void 0:E.find(Zt=>Zt.type==="airwallex_payment_consent");if(We&&We.redirect_url){de("3DS Required, starting verification...",We);const{status:Zt}=await pr({url:We.redirect_url,baseUrl:t.baseUrl});if(de(`╰ 3DS verification completed [Status: ${Zt}]`),Zt===V.CANCELLED)throw new Error("3DS verification cancelled");if(Zt===V.FAILURE)throw new Error("3DS verification failed")}if(We&&!Yr&&(Ye=await ce(d,{secure_token:p.token,their_pm_id:We.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:We.consent_id}}),de("[2nd] Confirm payment flow response",Ye),Yr=(x=(N=Ye.payment_methods)==null?void 0:N[0])==null?void 0:x.id),!Yr)throw new Error("No PM ID found");return dr({logPrefix:"awx-googlepay",anyCdeConnection:d,checkoutPaymentMethod:e,requiredFormFields:W,confirmResult:Ye,usePayFirstFlow:!1})}catch(O){throw lt("Google Pay payment error",O),k("google_pay_payment_error",{error:O}),new Error((O==null?void 0:O.message)??"Unknown error")}});async function Cl(t,e){try{const n=(await Vr(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),k("apple_pay_complete_merchant_validation",{...o})}catch(r){throw e.session.abort(),r}}async function Sl(t,e){var r,n;try{const o=t.payment,s=mo(e.nonCdeFormInputs,o),i=Fe(s,e.formCallbacks.get.onValidationError);k("billing_details_received",{...i}),await it(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[m.EMAIL],new_customer_first_name:i[m.FIRST_NAME],new_customer_last_name:i[m.LAST_NAME],new_customer_address:{zip_code:i[m.ZIP_CODE],country:i[m.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((n=(r=l.payment_methods)==null?void 0:r[0])==null?void 0:n.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),dr({logPrefix:"authnet-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:i,confirmResult:l,usePayFirstFlow:!1})}catch(o){const s={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(s),o}}const ko=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),Co=a.object({provider:a.literal("google_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:yr,err__:So}=F("authnet-applepay"),Pl=ze(async({context:t,formCallbacks:e})=>{const r={processor:ue.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,ko);if(!n)return r;if(yr("Loading Apple Pay script"),await fo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return yr("Apple Pay is not available on this device/browser"),r;if(!await ApplePaySession.canMakePayments())return yr("No active cards available for Apple Pay"),r;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await ct(i,c.token,l,void 0),d=async p=>{try{await z.authorizeNetApplePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){So("Apple Pay payment error",_),k("apple_pay_payment_error",{error:_}),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ue.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),Al=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,customParams:n,formCallbacks:o})=>{var I;const{initialPreview:s,overridePaymentRequest:i}=n,c=le(t.checkoutPaymentMethods,ko),{currencyCode:l,total:u}=yo({overridePaymentRequest:i,initialPreview:s,defaultLabel:(I=c==null?void 0:c.metadata)==null?void 0:I.processor_account_name}),d=t.anyCdeConnection,p=await q(d),_=p.mode==="setup",f={countryCode:"US",currencyCode:l,total:u,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],recurringPaymentRequest:ho({total:u,prefill:p}),...(i==null?void 0:i.applePayPaymentRequest)??{}};k("apple_pay_flow_started",{processor_name:e.processor_name,prefill:p,overridePaymentRequest:i});const h=new ApplePaySession(3,f),w={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:r,processorAccount:e.metadata,prefill:p,isSetupMode:_,baseUrl:t.baseUrl,formCallbacks:o};return new Promise((E,N)=>{h.oncancel=()=>{yr("Payment cancelled by user"),N(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async x=>{try{await Cl(x,w)}catch(O){N(O)}},h.onpaymentmethodselected=()=>{const x={newTotal:f.total};h.completePaymentMethodSelection(x)},h.onpaymentauthorized=async x=>{k("apple_pay_payment_authorized");try{const O=await Sl(x,w);E(O)}catch(O){N(O)}},h.begin()}).catch(E=>{throw So("Apple Pay payment error",E),k("apple_pay_payment_error",{error:E}),E})}),{log__:Ge,err__:Lt}=F("authnet-googlepay"),Tl=ze(async({context:t,formCallbacks:e})=>{var d,p;Ge("Initializing Authnet GooglePay flow");const r={processor:ue.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,Co);if(!n)return r;Ge("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return Lt("No gateway merchant ID found in processor account"),r;if(Ge("Loading Google Pay script"),await wo(),!((p=(d=window.google)==null?void 0:d.payments)!=null&&p.api))return Lt("Google Pay SDK not loaded properly"),r;Ge("Google Pay SDK loaded",window.google.payments);try{const _=mr({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),f=await hr(t.baseUrl,_),{result:h}=await f.isReadyToPay(_);if(!h)return Ge("Google Pay is not available for this user"),r}catch(_){return Lt("Error checking Google Pay availability",_),r}const s=t.anyCdeConnection,i=await q(s),c=i.mode==="setup",l=await ct(s,i.token,c,void 0),u=async _=>{try{z.authorizeNetGooglePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{..._,initialPreview:l}})}catch(f){Lt("Google Pay payment error",f),k("google_pay_payment_error",{error:f}),e.get.onCheckoutError((f==null?void 0:f.message)??"Unknown error")}};return{processor:ue.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),xl=Ae(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:r,formCallbacks:n,customParams:o})=>{var f,h,w,I;const{initialPreview:s,overridePaymentRequest:i}=o,l=le(t.checkoutPaymentMethods,Co).metadata,u=mr({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=t.anyCdeConnection,p=await q(d);k("google_pay_flow_started",{processor_name:r.processor_name,prefill:p,overridePaymentRequest:i});const _=await hr(t.baseUrl,u);try{const E=await _.loadPaymentData(u);Ge("Google Pay Payment data",E);const N=Eo(e,E),x=Fe(N,n.get.onValidationError);k("billing_details_received",{...x});const O=(h=(f=E.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!O)throw new Error("No payment token received from Google Pay");const U=await it(d,{payment_provider:r.provider,checkout_payment_method:r,new_customer_email:x[m.EMAIL],new_customer_first_name:x[m.FIRST_NAME],new_customer_last_name:x[m.LAST_NAME],new_customer_address:{zip_code:x[m.ZIP_CODE],country:x[m.COUNTRY]}});Ge("Start payment flow response",U);const W=await ce(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:r.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(O)}}});if(!((I=(w=W.payment_methods)==null?void 0:w[0])==null?void 0:I.id))throw new Error("No PM ID found");return dr({logPrefix:"authnet-googlepay",anyCdeConnection:d,checkoutPaymentMethod:r,requiredFormFields:x,confirmResult:W,usePayFirstFlow:!1})}catch(E){throw Lt("Google Pay payment error",E),k("google_pay_payment_error",{error:E}),new Error((E==null?void 0:E.message)??"Unknown error")}}),{log__:Il,err__:Po}=F("pockyt-cc"),Rl=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),Nl=t=>{const e=Rl.safeParse(t);if(!e.success){const r="Unable to process your credit card. Please contact support for assistance.",n=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw Po(n),new Error(r)}return e.data},Ao=t=>{try{const e=new URL(t??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return Il(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const r="Error verifying 3DS verification result.";throw Po(r,`Resulting URL: ${t}.
24
+ Error: ${ne(e)}`),new Error(r)}},Ol=(t,e)=>new URL(t).searchParams.get(e),Ml=t=>(t==null?void 0:t["op-pockyt-3ds-url"])!==void 0,Dl=async(t,e)=>{const r=Nl(e),n=await co({url:r["op-pockyt-3ds-url"],baseUrl:t});return{existing_cc:{vault_id:Ao(n.href??""),transaction_no:r["op-pockyt-txn-no"],reference_no:r["op-pockyt-ref-no"]}}},Ll=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),jl=a.enum(["ar","bg-BG","ca-ES","cs-CZ","da-DK","de-DE","el-GR","en-US","es-ES","et-EE","fi-FI","fr-FR","hr-HR","hu-HU","is-IS","it-IT","ja-JP","ko-KR","lt-LT","lv-LV","nl-NL","no-NO","pl-PL","pt-BR","pt-PT","ro-RO","ru-RU","sk-SK","sl-SI","sv-SE","zh-CN","zh-TW"]),{log__:ut,err__:jt}=F("adyen-cc"),Fl=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":Ll,"op-adyen-action":a.string()}),To="Unable to process your credit card. Please contact support for assistance.",Ul=t=>{const e=Fl.safeParse(t);if(!e.success)throw jt(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`),new Error(To);return e.data},$l=t=>JSON.parse(t),xo=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,Zl=async()=>{ut("Waiting for Adyen SDK to load...");for(let t=0;t<10;t++)xo()||await Pr(500);if(!xo())throw jt("Adyen SDK not loaded properly"),new Error(To);return ut("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},Vl=t=>{const{headers:e,locale:r,countryCode:n,component:o,host:s,cancelButton:i}=t,c=$l(e["op-adyen-action"]);return ut(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{ut("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",_),s.remove()},d=h=>{jt("Authentication failed. Result:",h),l({status:V.FAILURE,cleanup:u})},p=h=>{jt("Adyen error:",h),l({status:V.FAILURE,cleanup:u})},_=()=>{l({status:V.CANCELLED,cleanup:u})};i.addEventListener("click",_);const f=(h,w,I)=>{s.remove(),l({status:V.SUCCESS,additionalDetails:h,cleanup:u})};Zl().then(h=>h({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:r,countryCode:n,onAdditionalDetails:f,onPaymentFailed:d,onError:p})).then(h=>{h.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},zl=t=>{const e=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,r=t??e,n=jl.safeParse(r);return n.success?(ut(`Resolved locale: ${n.data}`),n.data):(jt(`Resolved invalid locale: ${r}. Defaulting to en-US.`),"en-US")},Gl=t=>(t==null?void 0:t["op-adyen-action"])!==void 0,Bl=async(t,e,r)=>{const n=Ul(e),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=io("http://example.com");i.replaceWith(o);const l=await Vl({headers:n,locale:zl(r),countryCode:t,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===V.FAILURE)throw new Error("3DS verification failed");if(l.status===V.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===V.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return ut("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else lr(l.status)},{log__:L,err__:Io}=F("common-cc"),{log__:Ro}=F("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const ql=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{var u;L("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=t.anyCdeConnection,i=await q(s);k("common_cc_flow_started",{...e,prefill:i}),L(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=Fe(r,n.get.onValidationError);k("billing_details_received",{...c});const l={session_id:t.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin}};try{L(`├ Tokenizing card info in CDE [Session: ${t.elementsSessionId}]`);const d=await Qc(o.currentCdeConnections,{session_id:t.elementsSessionId});if(ll(d,n.get.onValidationError),i.mode==="setup"){L(`├ Setting up payment method in CDE [Token: ${i.token}]`);const p=await Xc(s,l);return L(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{L(`├ Initial checkout flow. Checking out card info in CDE [Session: ${t.elementsSessionId}]`);const p=await oo(s,l);return L("╰ Checkout completed successfully."),{mode:"checkout",result:p}}}catch(d){if(d instanceof no&&d.originalErrorMessage.includes("3DS_REQUIRED")){L("├ Card requires 3DS, starting non-legacy payment flow"),L("Received 3DS error response headers:",d.response.headers),k("3ds_required",{...e,...d.response.headers});const p=Ml(d.response.headers);if(p){L("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const E=await Dl(t.baseUrl,d.response.headers);l.extra_metadata.pockyt=E}if(yl(d.response.headers)){L("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const E=await gl(t.baseUrl,d.response.headers);l.extra_metadata.airwallex=E}if(Gl(d.response.headers)){L("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const E=await Bl(r[m.COUNTRY],d.response.headers,i.locale);l.extra_metadata.adyen=E}const h=await Yc(s,l);L("├ Payment flow result:",h);const w=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";p?L("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):w?(L("├ Using stripe 3DS flow"),await Jl(h)):(L("├ Using common 3DS flow"),await Kl(h,t.baseUrl));const I=h.cc_pm_id;if(i.mode==="setup"){L(`├ Confirming payment flow [cc_pm_id: ${I}]`);const E=await ce(s,{secure_token:i.token,existing_cc_pm_id:I});L("├ Confirm payment flow result received Result:",E);const N=Mt(E);return L(`╰ Setup completed successfully [PM ID: ${N.payment_method_id}]`),{mode:"setup",result:N}}else{L(`├ Checking out after 3DS flow [Flow: ${w?"legacy":"new"}]`);const E=await oo(s,{...l,existing_cc_pm_id:I,do_not_use_legacy_cc_flow:w});return L("╰ Checkout completed successfully."),{mode:"checkout",result:E}}}throw Io("╰ Error checking out card info in CDE"),Io(d),d}}),Yl=t=>{const e=t.required_user_actions.find(r=>r.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Pa.parse(e)},Wl=["airwallex_payment_consent","adyen"],Hl=t=>{const e=t.required_user_actions.find(r=>Wl.includes(r.type));if(!e)throw new Error("No common 3DS action found");return ka.parse(e)},Kl=async(t,e)=>{const r=Hl(t);if(r.redirect_url==="3DS_COMPLETE"){L("├ 3DS flow completed successfully"),k("3ds_complete");return}L(`├ Using common 3DS flow [URL: ${r.redirect_url}]`),k("3ds_redirect",{...r});const{status:n}=await pr({url:r.redirect_url,baseUrl:e});if(L(`╰ 3DS verification completed [Status: ${n}]`),n===V.CANCELLED)throw k("3ds_cancelled"),new Error("3DS verification cancelled");if(n===V.FAILURE)throw k("3ds_failure"),new Error("3DS verification failed")},Jl=async t=>{const e=Yl(t);k("3ds_stripe_redirect",{...e}),Ro(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Oa(e),k("3ds_stripe_complete"),Ro("╰ Stripe 3DS flow completed successfully")},Ql=1,Xl=a.object({processor_name:a.literal("loop"),provider:a.literal("crypto"),metadata:a.object({merchant_id:a.string(),entity_id:a.string(),api_token:a.string(),supported_currencies:a.array(a.string()),environment:a.string()})}),{log__:ee,err__:No}=F("loop-crypto"),eu=a.object({loopFirstName:Z,loopLastName:Z,loopEmail:Z,[m.PROMOTION_CODE]:M}),tu=a.object({loopFirstName:M,loopLastName:M,loopEmail:M,[m.PROMOTION_CODE]:M}),Oo=(t,e,r,n)=>{const o=r.safeParse(t);if(!o.success){const s=o.error.format(),i=pn(s);for(const[c,l]of Object.entries(i))e(c,l,c);throw No("Got validation errors in non-CDE form fields",i),new Error("Got validation errors in non-CDE form fields")}return o.data},ru=ze(async({context:t})=>{ee("Checking if there are any CPMs for Loop Crypto...");const e=le(t.checkoutPaymentMethods,Xl);ee(`checkoutPaymentMethod: ${JSON.stringify(e)}`),ee("Starting Loop Crypto flow...");const r=await q(t.anyCdeConnection),n=await Vr(t.anyCdeConnection,{checkout_payment_method:e});if(r.mode!=="setup"&&!e.metadata.supported_currencies.includes(r.currency))throw Error(`Currency ${r.currency} not enabled for Loop. Enabled currencies: ${e.metadata.supported_currencies}`);if(!n||!n.next_action_metadata)throw Error("Failed to fetch necessary setup data for Loop");const o=n.next_action_metadata;let s;r.mode==="setup"?s=Ql:s=r.amount_total_atom*o.token_price;const i=s,c=o.authorization_amount,l=Xt(),u={paymentUsdAmount:i,suggestedAuthorizationUsdAmount:c,customerRefId:l},d={apiKey:e.metadata.api_token,entityId:e.metadata.entity_id,merchantId:e.metadata.merchant_id,environment:e.metadata.environment};return{isAvailable:!0,widgetProps:u,initLoopConnectProps:d}}),nu=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{ee("Running Loop flow..."),ee("context",t),ee("checkoutPaymentMethod",e),ee("nonCdeFormInputs",r),ee("flowCallbacks",n),ee("customParams",o);let s;o!=null&&o.success?s=Oo(r,n.get.onValidationError,eu):s=Oo(r,n.get.onValidationError,tu);const i=t.anyCdeConnection,c=await q(t.anyCdeConnection),l=c.mode!=="setup",u=await it(t.anyCdeConnection,{checkout_payment_method:e,payment_provider:e.provider,new_customer_email:s.loopEmail,new_customer_first_name:s.loopFirstName,new_customer_last_name:s.loopLastName,use_pay_first_flow:l,pay_first_flow_cart_info:l?{line_items:c.line_items,displayed_total_amount_atom:c.amount_total_atom}:void 0});if(!o)throw Error("Checkout failed. Failed to properly submit form data.");const d=await ce(i,{secure_token:c.token,their_pm_id:o.success?o.payin.paymentMethod.paymentMethodId:void 0,checkout_attempt_id:c.mode!=="setup"?u.checkout_attempt_id:void 0,processor_specific_metadata:{loop_customer:o.success?o.customer:void 0,loop_payin:o.success?o.payin:void 0,loop_failure_details:o.success?void 0:o.failureDetails,loop_debug_info:o.success?void 0:o.debugInfo,loop_success:o.success}});if(ee(`Confirm result: ${d}`),c.mode==="setup"){ee("Doing payment setup..."),ee("├ Confirm payment flow result received Result:",d);const p=Mt(d);return ee(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{if(ee("Doing checkout..."),!d.pay_first_success_response)throw No("Checkout failed, no pay-first success response:",d),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:d.pay_first_success_response}}}),{log__:we,err__:Mo}=F("pockyt-paypal"),ou=a.object({processor_name:a.literal("pockyt"),provider:a.literal("paypal")});a.array(a.object({paypal_iframe_url:a.string(),verify_token:a.string()})).length(1);const su=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{var W,ke;we("Running Pockyt Paypal flow...");const s=t.anyCdeConnection,i=await q(s);we("Verifying CPM...");const c=ou.parse(e);we("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=Fe(r,n.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=nl(u);we(`Starting payment flow... Mode: ${i.mode}`);const p=Xt(),_=i.mode!=="setup",f={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:_,pay_first_flow_cart_info:_?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((W=o==null?void 0:o.settings)!=null&&W.useRedirectFlow),frontend_token_for_redirect_flow:p},...d},h=new URL("/app/pre-action/start/",t.baseUrl).toString(),w=btoa(JSON.stringify(f)),I=new URLSearchParams({st:i.token,r:w}),E=`${h}?${I.toString()}`;if((ke=o==null?void 0:o.settings)!=null&&ke.useRedirectFlow)throw we("Starting redirect mode for PayPal..."),window.location.href=E,await Pr(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");we("Starting popup mode for PayPal..."),we("Opening paypal iframe...");const N=await cl("PayPal",s,p,E);we("Paypal flow result",N);const x=Ao(N.href),O=Ol(N.href,"catt");if(!O)throw Mo("Checkout attempt ID not found in redirect URL:",N.href),new Error("Checkout attempt ID not found in redirect URL");we(`Confirming payment flow using vault ID ${x}`);const U=await ce(s,{secure_token:i.token,their_pm_id:x,checkout_attempt_id:_?O:void 0});if(we("Confirm payment flow result",U),i.mode==="setup")return{mode:"setup",result:{payment_method_id:U.payment_methods[0].id}};if(!U.pay_first_success_response)throw Mo("Checkout failed, no pay-first success response:",U),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:U.pay_first_success_response}}),Do="ojs-stripe-link-btn",{log__:Y,err__:au}=F("stripe-link"),iu=a.object({provider:a.literal("stripe_link"),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),cu=a.array(a.object({our_existing_pm_id:a.string()})).length(1),lu=ze(async({context:t,formCallbacks:e})=>{const r=t.customInitParams.stripeLink;Y("Checking if there are any CPMs for Stripe Link...");const n=le(t.checkoutPaymentMethods,iu);Y("Starting stripe link flow...");const o=t.anyCdeConnection,s=await q(o),i=s.mode==="setup";Y("Creating stripe elements...");const c=await ct(o,s.token,i,void 0),{elements:l,stripe:u}=await xa(n.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});Y("Creating express checkout...");const d=l.create("expressCheckout",{buttonHeight:r==null?void 0:r.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),p=()=>{d.mount(`#${Do}`)},_=()=>{d.unmount()};return r!=null&&r.doNotMountOnInit?Y("NOT mounting stripe link button (doNotMountOnInit is true)"):(Y("Mounting stripe link button..."),p()),d.on("click",async f=>{if(Y("Stripe Link button clicked"),r!=null&&r.overrideLinkSubmit&&!await r.overrideLinkSubmit()){Y("Stripe Link submit aborted by overrideLinkSubmit");return}f.resolve()}),d.on("confirm",async f=>{Y("Stripe Link window confirmed",f);const h=await u.createPaymentMethod({elements:l,params:{billing_details:f.billingDetails}});h.error?(au("error",h.error),e.get.onCheckoutError(h.error.message??"Stripe Link unknown error")):(Y("paymentMethod",h.paymentMethod),z.stripeLink.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{stripePM:h.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:p,dismountButton:_,waitForButtonToMount:async()=>await pu(Do)}}}),uu=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{Y("Running Stripe Link flow...");const s=t.anyCdeConnection;Y("Merging PM fields with form fields...");const i=du(r,o.stripePM),c=Fe(i,n.get.onValidationError);k("billing_details_received",{...c}),Y("Starting payment flow...");const l=await it(s,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:o.stripePM.id,new_customer_email:c[m.EMAIL],new_customer_first_name:c[m.FIRST_NAME],new_customer_last_name:c[m.LAST_NAME],new_customer_address:{zip_code:c[m.ZIP_CODE],country:c[m.COUNTRY]}});Y("Start payment flow response",l);const d=cu.parse(l.required_user_actions)[0].our_existing_pm_id,p=await q(s);if(p.mode==="setup"){Y("Doing payment setup...");const _=await ce(s,{secure_token:p.token,existing_cc_pm_id:d});return{mode:"setup",result:Mt(_)}}else{Y("Doing checkout...");const _={secure_token:p.token,payment_input:{provider_type:e.provider},customer_email:c[m.EMAIL],customer_zip_code:c[m.ZIP_CODE],customer_country:c[m.COUNTRY],promotion_code:c[m.PROMOTION_CODE],line_items:p.line_items,total_amount_atom:p.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Zr(s,_)}}}),du=(t,e)=>{var l,u,d,p,_;const r={...t},[n,...o]=((u=(l=e.billing_details.name)==null?void 0:l.trim())==null?void 0:u.split(/\s+/))??[],s=o.join(" ")||void 0;r[m.EMAIL]=r[m.EMAIL]||((d=e.link)==null?void 0:d.email)||e.billing_details.email||"op_unfilled@getopenpay.com",r[m.ZIP_CODE]=r[m.ZIP_CODE]||((p=e.billing_details.address)==null?void 0:p.postal_code)||"00000",r[m.COUNTRY]=r[m.COUNTRY]||((_=e.billing_details.address)==null?void 0:_.country)||"US";const i=r[m.FIRST_NAME]||n||"",c=r[m.LAST_NAME]||s||"";return i||c?(r[m.FIRST_NAME]=i,r[m.LAST_NAME]=c):(r[m.FIRST_NAME]="_OP_UNKNOWN",r[m.LAST_NAME]=""),Y("Final form inputs:",r),r},pu=t=>new Promise(e=>{const r=()=>{const n=document.getElementById(t);n?e(n):requestAnimationFrame(r)};r()}),{log__:X,err__:fu}=F("stripe-pr"),mu=a.object({provider:a.union([a.literal("apple_pay"),a.literal("google_pay")]),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),hu=ze(async({context:t,formCallbacks:e})=>{X("Checking if there are any CPMs for Stripe PR...");const r=le(t.checkoutPaymentMethods,mu);X("Initializing Stripe PR flow...");const n=t.anyCdeConnection,o=await q(n),s=o.mode==="setup";X("Getting initial preview amount");const i=await ct(n,o.token,s,void 0),c=await Ia(r.metadata.stripe_pk,i.amountAtom,i.currency,s);X("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return fu("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};X("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,p)=>z.stripePR.run({context:t,checkoutPaymentMethod:Ft(t.checkoutPaymentMethods,d),nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:p==null?void 0:p.overridePaymentRequest},initResult:{processor:ue.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:ue.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),yu=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o,initResult:s})=>{if(X("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=t.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const h=o.overridePaymentRequest;X("Overriding PR amount with",h),gu(c,h.amount,h.pending,h.applePayPaymentRequest,h.label)}X("Showing PR dialog..."),c.show();const l=await Ra(c);X("Stripe PM added event:",l),X("Merging PM fields with form fields...");const u=_u(r,l),d=Fe(u,n.get.onValidationError);k("billing_details_received",{...d}),X("PR dialog finished. Starting payment flow...",d);const p=await Wc(i,{fields:d,checkoutPaymentMethod:e}),_=vu(p);X("Confirming PR with Stripe..."),await Na(_,l);const f=await q(i);if(f.mode==="setup"){X("Confirming payment flow for setup...");const h=await ce(i,{secure_token:f.token});return{mode:"setup",result:Mt(h)}}else{X("Performing checkout...");const h={secure_token:f.token,payment_input:{provider_type:e.provider},customer_first_name:d[m.FIRST_NAME],customer_last_name:d[m.LAST_NAME],customer_email:d[m.EMAIL],customer_zip_code:d[m.ZIP_CODE],customer_country:d[m.COUNTRY],promotion_code:d[m.PROMOTION_CODE],line_items:f.line_items,total_amount_atom:f.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Zr(i,h)}}}),_u=(t,e)=>{var d,p,_,f;const r={...t},[n,...o]=((p=(d=e.payerName)==null?void 0:d.trim())==null?void 0:p.split(/\s+/))??[],s=o.join(" ")||void 0,i=(f=(_=e.paymentMethod)==null?void 0:_.billing_details)==null?void 0:f.address,c=e.shippingAddress;r[m.EMAIL]=r[m.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",r[m.ZIP_CODE]=r[m.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",r[m.COUNTRY]=r[m.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US";const l=r[m.FIRST_NAME]||n||"",u=r[m.LAST_NAME]||s||"";return l||u?(r[m.FIRST_NAME]=l,r[m.LAST_NAME]=u):(r[m.FIRST_NAME]="_OP_UNKNOWN",r[m.LAST_NAME]=""),X("Final form inputs:",r),r},gu=(t,e,r,n,o)=>{t.update({total:{amount:e.amountAtom,label:o??"Total",pending:r},currency:e.currency,applePay:n})},vu=t=>{if(t.required_user_actions.length!==1)throw new Error(`Error occurred.
25
+ Details: got ${t.required_user_actions.length} required user actions`);return Aa.parse(t.required_user_actions[0])},Ft=(t,e,r)=>{const n=t.filter(o=>{const s=r===void 0?!0:o.processor_name===r,i=o.provider===e;return s&&i});if(n.length===0)throw console.warn("CPMs list",t),new Error(`No CPMs found with provider '${e}' and processor '${r}'`);return n.length!==1&&(console.warn("CPMs list",t),console.warn(`More than one CPM found with provider '${e}' and processor '${r}'`),k("more_than_one_cpm_found",{provider:e,processor:r,cpms:t})),n[0]},z={commonCC:{init:async()=>{},run:ql},stripePR:{init:hu,run:yu},stripeLink:{init:lu,run:uu},pockytPaypal:{run:su},airwallexGooglePay:{init:El,run:kl},airwallexApplePay:{init:vl,run:wl},loopCrypto:{init:ru,run:nu},authorizeNetApplePay:{init:Pl,run:Al},authorizeNetGooglePay:{init:Tl,run:xl}},{log__:wu,err__:bu}=F("init-flows"),Be=(t,e)=>{const r=new Ot;return{publisher:r,initialize:async n=>{try{if(r.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(n);wu(`✔ ${t} flow initialized successfully. Result:`,o),r.set(o)}catch(o){bu(`𝙭 ${t} flow initialization failed. Error:`,ne(o),"Details:",o),r.throw(o,ne(o))}}}},Eu=async(t,e,r)=>{await Promise.all(Object.values(t).map(n=>n.initialize({context:e,formCallbacks:r})))},ku=()=>({stripePR:Be("Stripe PR",z.stripePR.init),stripeLink:Be("Stripe Link",z.stripeLink.init),airwallexGooglePay:Be("Airwallex GooglePay",z.airwallexGooglePay.init),airwallexApplePay:Be("Airwallex ApplePay",z.airwallexApplePay.init),loop:Be("Loop",z.loopCrypto.init),authorizeNetGooglePay:Be("Authnet GooglePay",z.authorizeNetGooglePay.init),authorizeNetApplePay:Be("Authnet ApplePay",z.authorizeNetApplePay.init)}),{err__:Cu}=F("form-callbacks"),pe=a.function().optional(),Lo=a.object({onFocus:pe,onBlur:pe,onChange:pe,onLoad:pe,onLoadError:pe,onValidationError:pe,onCheckoutStarted:pe,onCheckoutSuccess:pe,onSetupPaymentMethodSuccess:pe,onCheckoutError:pe,onPaymentRequestLoad:pe}),Ee=class Ee{constructor(){this.setCallbacks=e=>{this._callbacks=Ee.createEmptyCallbacks(),Object.entries(e).forEach(([r,n])=>{const o=Ks(r,n??Ee.NOOP,Cu);this._callbacks[r]=o})},this._callbacks=Ee.createEmptyCallbacks()}get get(){return{...this._callbacks}}};Ee.NOOP=()=>{},Ee.createEmptyCallbacks=()=>{const e={};return Object.keys(Lo.keyof().enum).forEach(r=>{e[r]=Ee.NOOP}),e},Ee.fromObject=e=>{const r=new Ee;return r.setCallbacks(Lo.parse(e)),r};let Br=Ee;const jo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ut=32,Su=16,Fo=10,Uo=0xffffffffffff;var qe;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID"})(qe||(qe={}));class $t extends Error{constructor(e,r){super(`${r} (${e})`),this.name="ULIDError",this.code=e}}function Pu(t){let e=Math.floor(t()*Ut);return e===Ut&&(e=Ut-1),jo.charAt(e)}function Au(t){const e=Tu(),r=e&&(e.crypto||e.msCrypto)||null;if(typeof(r==null?void 0:r.getRandomValues)=="function")return()=>{const n=new Uint8Array(1);return r.getRandomValues(n),n[0]/255};if(typeof(r==null?void 0:r.randomBytes)=="function")return()=>r.randomBytes(1).readUInt8()/255;throw new $t(qe.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Tu(){return Ru()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function xu(t,e){let r="";for(;t>0;t--)r=Pu(e)+r;return r}function Iu(t,e=Fo){if(isNaN(t))throw new $t(qe.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>Uo)throw new $t(qe.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Uo}: ${t}`);if(t<0)throw new $t(qe.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===!1)throw new $t(qe.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let r,n="";for(let o=e;o>0;o--)r=t%Ut,n=jo.charAt(r)+n,t=(t-r)/Ut;return n}function Ru(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Nu(t,e){const r=Au(),n=Date.now();return Iu(n,Fo)+xu(Su,r)}const $o="op_analytics_device_token",Ou=()=>{const t=document.cookie.split(";").find(r=>r.includes($o));if(t)return t.split("=")[1];const e=Nu();return Mu(e),e},Mu=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${$o}=${t}; path=/; expires=${e.toUTCString()}`};function Du(){try{const t=$();if(t!=null&&t.next||t!=null&&t.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";const e=$();if(e!=null&&e.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(n=>n.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(n=>n._reactRootContainer))return"react";const r=$();return r!=null&&r.Vue||r!=null&&r.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function Lu(t){var e,r,n;try{switch(t){case"react":return null;case"nextjs":{const o=$();return((e=o==null?void 0:o.next)==null?void 0:e.version)||((r=o==null?void 0:o.__NEXT_DATA__)==null?void 0:r.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const o=(n=$())==null?void 0:n.document,s=o==null?void 0:o.querySelector("[ng-version]");return s?s.getAttribute("ng-version"):null}default:return null}}catch{return null}}function ju(){const t=Du(),e=Lu(t);return{framework:t,version:e}}class Fu{constructor(e,r,n,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if(Zo(s.origin)!==Zo(this.baseUrl)||typeof s.data=="object"&&s.data.penpal||typeof s.data=="object"&&s.data.source&&s.data.source==="react-devtools-bridge")return;let i=null;try{i=Ua(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=r,this.formCallbacks=n,this.internalCallbacks=o}}const Zo=t=>new URL(t).origin;async function Uu(t,e){const n=await vn({iframe:t,debug:!1,childOrigin:e}).promise,o=await ii(n);if(!ci(n,o))throw new Error("Got invalid CDE connection object");return n}class $u{constructor(){this.connections=new Map}addConnection(e,r){this.connections.set(e,r)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Zu=(t,e,r)=>{const{stripePR:n}=t;n.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&Vo("apple_pay",s,e,r,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Vo("google_pay",s,e,r,u)}}};r.get.onPaymentRequestLoad(l)}})},Vo=(t,e,r,n,o)=>z.stripePR.run({context:r,checkoutPaymentMethod:Ft(r.checkoutPaymentMethods,t),nonCdeFormInputs:_e(r.formDiv),formCallbacks:n,customParams:{provider:t,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),zo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:be,err__:xe}=F("op-form"),Ie=class Ie{constructor(e){var o;this.cdeLoadEvent=new Ot,this.anyCdeConn=new Ot,this.context=new Ot,this.initFlows=ku(),this.startFormInit=async()=>{try{const s=this.createElement(ye.CDE_BRIDGE);s.node.id="__op_internal_cde_bridge",s.node.ariaHidden="true",Object.assign(s.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),s.mount("body"),be("CDE bridge element mounted"),be("Initializing OpenPay form:"),be("├ Waiting for CDE load event...");const i=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:zo});be("├ CDE load event received"),be("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:zo});be("├ CDE connection received"),await tl(c,this.deviceToken),be("├ Creating OJS context, setting up handlers...");const l=Ie.buildOjsFlowContext(this.config,i,c,this.getFormDiv());this.context.set(l),Zu(this.initFlows,l,this.formCallbacks),be("├ Starting OJS init flows..."),await Eu(this.initFlows,l,this.formCallbacks),this.formCallbacks.get.onLoad(i.totalAmountAtoms,i.currency),be("╰ Done initializing OJS flows."),k("form_loaded")}catch(s){const i=ne(s);xe("╰ Error initializing OP form:",i),k("form_init_error",{error:i}),this.formCallbacks.get.onLoadError(i)}},this.setFormHeight=s=>{this.formProperties.height=s,this.registeredElements&&Object.values(this.registeredElements).forEach(i=>{!i||i.type===ye.CDE_BRIDGE||(i.node.style.height=s)})},this.onCdeLoaded=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(s),k("cde_loaded"))},this.onCdeLoadError=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(s),s),k("cde_load_error",{error:s}))},this.createElement=(s,i={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const c=Qs.parse(s),l=document.createElement("iframe"),u=this.buildQueryString(i);l.name=`${c}-element`;const d=new URL(`/app/v1/${l.name}/`,this.config.baseUrl);return d.search=u.toString(),l.src=d.href,l.style.border="none",l.style.width="100%",this.registerIframe(c,l)},this.registerIframe=(s,i)=>{const c={type:s,node:i,mount:l=>{var u;(u=document.querySelector(l))==null||u.appendChild(i),k("element_mounted",{element_type:s})}};return this.connectToElement({type:c.type,node:c.node}),this.registeredElements||(this.registeredElements={[ye.CARD]:void 0,[ye.CARD_NUMBER]:void 0,[ye.CARD_EXPIRY]:void 0,[ye.CARD_CVC]:void 0,[ye.CDE_BRIDGE]:void 0}),this.registeredElements[s]=c,c},this.buildQueryString=s=>{const i=new URLSearchParams;return i.append("referer",this.referrer),i.append("formId",this.formId),s.styles&&i.append("styles",Ma(s.styles)),i.append("secureToken",this.config.checkoutSecureToken),i},this.connectToElement=s=>{Uu(s.node).then(i=>{this.connectionManager.addConnection(s.type,i),!this.anyCdeConn.current.isSuccess&&s.type===ye.CDE_BRIDGE&&this.anyCdeConn.set(i)}).catch(i=>xe("[FORM] Error connecting to CDE iframe",i))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{k("submit_card");const s=this.context.getValueIfLoadedElse(null);if(!s){xe("Please wait for the form to finish loading before submitting.");return}z.commonCC.run({context:s,checkoutPaymentMethod:Ft(s.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:_e(s.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){xe("Please wait for the form to finish loading before getting available payment methods.");return}const i={airwallexGooglePay:re.airwallexGooglePay,airwallexApplePay:re.airwallexApplePay,authorizeNetGooglePay:re.authorizenetGooglePay,authorizeNetApplePay:re.authorizenetApplePay},c=Object.entries(this.initFlows).map(([l,u])=>({name:i[l]??l,...u.publisher.getValueIfLoadedElse(null)}));return k("get_available_payment_methods",{available_payment_methods:c}),c},this.generalSubmit=(s,i)=>{k("general_form_submit",{method:s,settings:i});const c=this.context.getValueIfLoadedElse(null);if(!c){xe("Please wait for the form to finish loading before submitting.");return}switch(s){case re.pockytPaypal:return z.pockytPaypal.run({context:c,checkoutPaymentMethod:Ft(c.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:_e(c.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:i},initResult:void 0});case re.airwallexGooglePay:{const l=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!l){xe("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.airwallexApplePay:{const l=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!l){xe("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.authorizenetGooglePay:{const l=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!l){xe("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.authorizenetApplePay:{const l=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!l){xe("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.loopCrypto:return z.loopCrypto.run({context:c,checkoutPaymentMethod:Ft(c.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:_e(c.formDiv),formCallbacks:this.formCallbacks,customParams:i,initResult:void 0});default:lr(s)}},this.submit=this.submitCard,this.destroy=()=>{var s;be("Destroying OpenPay form...");for(const i of Object.values(this.registeredElements??{}))i&&i.node.remove();(s=$())==null||s.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),zc(),this.registeredElements=null,delete window.ojs,k("form_destroyed")},this.updateCallbacks=s=>{this.formCallbacks.setCallbacks(s)},Ie.assignAsSingleton(this),this.ojsVersion="0.2.32",this.ojsReleaseVersion="0.2.32",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Br.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Xt()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new $u,this.deviceToken=Ou(),Vc();const{framework:r,version:n}=ju();Jn(this.baseUrl).then(s=>{if(!$r.current.isSuccess){const i={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:s,framework:r,frameworkVersion:n,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl};$r.set(i)}}),k("form_init"),this.eventHandler=new Fu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),(o=$())==null||o.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}};Ie.ojsFlows=z,Ie.assignAsSingleton=e=>{if(Ie.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},Ie.getInstance=()=>window.ojs??null,Ie.buildOjsFlowContext=(e,r,n,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??He).origin,formDiv:o,elementsSessionId:r.sessionId,checkoutPaymentMethods:r.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let qr=Ie;Ce.FieldName=m,Ce.OpenPayForm=qr,Ce.SubmitMethod=Js,Ce.SubmitMethods=re,Object.defineProperty(Ce,Symbol.toStringTag,{value:"Module"})});