@getopenpay/openpay-js 0.1.13 → 0.1.15-alpha.09caa9f

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,24 +1,23 @@
1
- (function(ae,xe){typeof exports=="object"&&typeof module<"u"?xe(exports):typeof define=="function"&&define.amd?define(["exports"],xe):(ae=typeof globalThis<"u"?globalThis:ae||self,xe(ae.OpenPay={}))})(this,function(ae){"use strict";const xe="https://cde.getopenpay.com";var k;(function(n){n.assertEqual=s=>s;function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},n.getValidEnumValues=s=>{const o=n.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(const c of o)a[c]=s[c];return n.objectValues(a)},n.objectValues=s=>n.objectKeys(s).map(function(o){return s[o]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},n.find=(s,o)=>{for(const a of s)if(o(a))return a},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}n.joinValues=r,n.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(k||(k={}));var vt;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(vt||(vt={}));const m=k.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ee=n=>{switch(typeof n){case"undefined":return m.undefined;case"string":return m.string;case"number":return isNaN(n)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":return Array.isArray(n)?m.array:n===null?m.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?m.promise:typeof Map<"u"&&n instanceof Map?m.map:typeof Set<"u"&&n instanceof Set?m.set:typeof Date<"u"&&n instanceof Date?m.date:m.object;default:return m.unknown}},f=k.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"]),Jn=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:");class $ extends Error{constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(o){return o.message},r={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(t(a));else{let c=r,d=0;for(;d<a.path.length;){const l=a.path[d];d===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(t(a))):c[l]=c[l]||{_errors:[]},c=c[l],d++}}};return s(this),r}static assert(e){if(!(e instanceof $))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,k.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},r=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}$.create=n=>new $(n);const he=(n,e)=>{let t;switch(n.code){case f.invalid_type:n.received===m.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case f.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,k.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:t=`Unrecognized key(s) in object: ${k.joinValues(n.keys,", ")}`;break;case f.invalid_union:t="Invalid input";break;case f.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${k.joinValues(n.options)}`;break;case f.invalid_enum_value:t=`Invalid enum value. Expected ${k.joinValues(n.options)}, received '${n.received}'`;break;case f.invalid_arguments:t="Invalid function arguments";break;case f.invalid_return_type:t="Invalid function return type";break;case f.invalid_date:t="Invalid date";break;case f.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:k.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case f.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case f.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case f.custom:t="Invalid input";break;case f.invalid_intersection_types:t="Intersection results could not be merged";break;case f.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case f.not_finite:t="Number must be finite";break;default:t=e.defaultError,k.assertNever(n)}return{message:t}};let Bt=he;function Qn(n){Bt=n}function Qe(){return Bt}const Xe=n=>{const{data:e,path:t,errorMaps:r,issueData:s}=n,o=[...t,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let c="";const d=r.filter(l=>!!l).slice().reverse();for(const l of d)c=l(a,{data:e,defaultError:c}).message;return{...s,path:o,message:c}},Xn=[];function h(n,e){const t=Qe(),r=Xe({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===he?void 0:he].filter(s=>!!s)});n.common.issues.push(r)}class A{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if(s.status==="aborted")return g;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const s of t){const o=await s.key,a=await s.value;r.push({key:o,value:a})}return A.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return g;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[o.value]=a.value)}return{status:e.value,value:r}}}const g=Object.freeze({status:"aborted"}),me=n=>({status:"dirty",value:n}),L=n=>({status:"valid",value:n}),bt=n=>n.status==="aborted",wt=n=>n.status==="dirty",Se=n=>n.status==="valid",Te=n=>typeof Promise<"u"&&n instanceof Promise;function et(n,e,t,r){if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(n)}function qt(n,e,t,r,s){if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}typeof SuppressedError=="function"&&SuppressedError;var p;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(p||(p={}));var Oe,Re;class q{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ht=(n,e)=>{if(Se(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new $(n.common.issues);return this._error=t,this._error}}};function _(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,c)=>{var d,l;const{message:u}=n;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(d=u??r)!==null&&d!==void 0?d:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(l=u??t)!==null&&l!==void 0?l:c.defaultError}},description:s}}class b{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 ee(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ee(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new A,ctx:{common:e.parent.common,data:e.data,parsedType:ee(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Te(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const s={common:{issues:[],async:(r=t==null?void 0:t.async)!==null&&r!==void 0?r:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ee(e)},o=this._parseSync({data:e,path:s.path,parent:s});return Ht(s,o)}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ee(e)},s=this._parse({data:e,path:r.path,parent:r}),o=await(Te(s)?s:Promise.resolve(s));return Ht(r,o)}refine(e,t){const r=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,o)=>{const a=e(s),c=()=>o.addIssue({code:f.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(d=>d?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(e,t){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new V({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return W.create(this,this._def)}nullable(){return se.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return U.create(this,this._def)}promise(){return _e.create(this,this._def)}or(e){return Ne.create([this,e],this._def)}and(e){return je.create(this,e,this._def)}transform(e){return new V({..._(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Ze({..._(this._def),innerType:this,defaultValue:t,typeName:y.ZodDefault})}brand(){return new Ct({typeName:y.ZodBranded,type:this,..._(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Fe({..._(this._def),innerType:this,catchValue:t,typeName:y.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Ue.create(this,e)}readonly(){return Ve.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const er=/^c[^\s-]{8,}$/i,tr=/^[0-9a-z]+$/,nr=/^[0-9A-HJKMNP-TV-Z]{26}$/,rr=/^[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,sr=/^[a-z0-9_-]{21}$/i,or=/^[-+]?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)?)??$/,ir=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ar="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let kt;const cr=/^(?:(?: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])$/,lr=/^(([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})))$/,dr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Wt="((\\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])))",ur=new RegExp(`^${Wt}$`);function Yt(n){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`),e}function fr(n){return new RegExp(`^${Yt(n)}$`)}function Kt(n){let e=`${Wt}T${Yt(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function hr(n,e){return!!((e==="v4"||!e)&&cr.test(n)||(e==="v6"||!e)&&lr.test(n))}class F extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==m.string){const o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.string,received:o.parsedType}),g}const r=new A;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),h(s,{code:f.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),h(s,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const a=e.data.length>o.value,c=e.data.length<o.value;(a||c)&&(s=this._getOrReturnCtx(e,s),a?h(s,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&h(s,{code:f.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")ir.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"email",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")kt||(kt=new RegExp(ar,"u")),kt.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"emoji",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")rr.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"uuid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")sr.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"nanoid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")er.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"cuid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")tr.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"cuid2",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")nr.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"ulid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),h(s,{validation:"url",code:f.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"regex",code:f.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Kt(o).test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?ur.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?fr(o).test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?or.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"duration",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?hr(e.data,o.version)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"ip",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?dr.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"base64",code:f.invalid_string,message:o.message}),r.dirty()):k.assertNever(o);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:f.invalid_string,...p.errToObj(r)})}_addCheck(e){return new F({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...p.errToObj(e)})}url(e){return this._addCheck({kind:"url",...p.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...p.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...p.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...p.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...p.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...p.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...p.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...p.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...p.errToObj(e)})}datetime(e){var t,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(r=e==null?void 0:e.local)!==null&&r!==void 0?r:!1,...p.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,...p.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...p.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...p.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...p.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...p.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...p.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...p.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...p.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...p.errToObj(t)})}nonempty(e){return this.min(1,p.errToObj(e))}trim(){return new F({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new F({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new F({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}F.create=n=>{var e;return new F({checks:[],typeName:y.ZodString,coerce:(e=n==null?void 0:n.coerce)!==null&&e!==void 0?e:!1,..._(n)})};function mr(n,e){const t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,o=parseInt(n.toFixed(s).replace(".","")),a=parseInt(e.toFixed(s).replace(".",""));return o%a/Math.pow(10,s)}class te extends b{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)!==m.number){const o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.number,received:o.parsedType}),g}let r;const s=new A;for(const o of this._def.checks)o.kind==="int"?k.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),h(r,{code:f.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),h(r,{code:f.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),h(r,{code:f.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?mr(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),h(r,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),h(r,{code:f.not_finite,message:o.message}),s.dirty()):k.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,p.toString(t))}gt(e,t){return this.setLimit("min",e,!1,p.toString(t))}lte(e,t){return this.setLimit("max",e,!0,p.toString(t))}lt(e,t){return this.setLimit("max",e,!1,p.toString(t))}setLimit(e,t,r,s){return new te({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:p.toString(s)}]})}_addCheck(e){return new te({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:p.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:p.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:p.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:p.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:p.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:p.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:p.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:p.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:p.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&k.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}te.create=n=>new te({checks:[],typeName:y.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,..._(n)});class ne extends b{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)!==m.bigint){const o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.bigint,received:o.parsedType}),g}let r;const s=new A;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),h(r,{code:f.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),h(r,{code:f.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),h(r,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):k.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,p.toString(t))}gt(e,t){return this.setLimit("min",e,!1,p.toString(t))}lte(e,t){return this.setLimit("max",e,!0,p.toString(t))}lt(e,t){return this.setLimit("max",e,!1,p.toString(t))}setLimit(e,t,r,s){return new ne({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:p.toString(s)}]})}_addCheck(e){return new ne({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:p.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:p.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:p.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:p.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:p.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ne.create=n=>{var e;return new ne({checks:[],typeName:y.ZodBigInt,coerce:(e=n==null?void 0:n.coerce)!==null&&e!==void 0?e:!1,..._(n)})};class Pe extends b{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==m.boolean){const r=this._getOrReturnCtx(e);return h(r,{code:f.invalid_type,expected:m.boolean,received:r.parsedType}),g}return L(e.data)}}Pe.create=n=>new Pe({typeName:y.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,..._(n)});class ce extends b{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==m.date){const o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.date,received:o.parsedType}),g}if(isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_date}),g}const r=new A;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),h(s,{code:f.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),h(s,{code:f.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):k.assertNever(o);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ce({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:p.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:p.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ce.create=n=>new ce({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:y.ZodDate,..._(n)});class tt extends b{_parse(e){if(this._getType(e)!==m.symbol){const r=this._getOrReturnCtx(e);return h(r,{code:f.invalid_type,expected:m.symbol,received:r.parsedType}),g}return L(e.data)}}tt.create=n=>new tt({typeName:y.ZodSymbol,..._(n)});class Ie extends b{_parse(e){if(this._getType(e)!==m.undefined){const r=this._getOrReturnCtx(e);return h(r,{code:f.invalid_type,expected:m.undefined,received:r.parsedType}),g}return L(e.data)}}Ie.create=n=>new Ie({typeName:y.ZodUndefined,..._(n)});class Ae extends b{_parse(e){if(this._getType(e)!==m.null){const r=this._getOrReturnCtx(e);return h(r,{code:f.invalid_type,expected:m.null,received:r.parsedType}),g}return L(e.data)}}Ae.create=n=>new Ae({typeName:y.ZodNull,..._(n)});class pe extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return L(e.data)}}pe.create=n=>new pe({typeName:y.ZodAny,..._(n)});class le extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return L(e.data)}}le.create=n=>new le({typeName:y.ZodUnknown,..._(n)});class J extends b{_parse(e){const t=this._getOrReturnCtx(e);return h(t,{code:f.invalid_type,expected:m.never,received:t.parsedType}),g}}J.create=n=>new J({typeName:y.ZodNever,..._(n)});class nt extends b{_parse(e){if(this._getType(e)!==m.undefined){const r=this._getOrReturnCtx(e);return h(r,{code:f.invalid_type,expected:m.void,received:r.parsedType}),g}return L(e.data)}}nt.create=n=>new nt({typeName:y.ZodVoid,..._(n)});class U extends b{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==m.array)return h(t,{code:f.invalid_type,expected:m.array,received:t.parsedType}),g;if(s.exactLength!==null){const a=t.data.length>s.exactLength.value,c=t.data.length<s.exactLength.value;(a||c)&&(h(t,{code:a?f.too_big:f.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(h(t,{code:f.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(h(t,{code:f.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((a,c)=>s.type._parseAsync(new q(t,a,t.path,c)))).then(a=>A.mergeArray(r,a));const o=[...t.data].map((a,c)=>s.type._parseSync(new q(t,a,t.path,c)));return A.mergeArray(r,o)}get element(){return this._def.type}min(e,t){return new U({...this._def,minLength:{value:e,message:p.toString(t)}})}max(e,t){return new U({...this._def,maxLength:{value:e,message:p.toString(t)}})}length(e,t){return new U({...this._def,exactLength:{value:e,message:p.toString(t)}})}nonempty(e){return this.min(1,e)}}U.create=(n,e)=>new U({type:n,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,..._(e)});function ye(n){if(n instanceof T){const e={};for(const t in n.shape){const r=n.shape[t];e[t]=W.create(ye(r))}return new T({...n._def,shape:()=>e})}else return n instanceof U?new U({...n._def,type:ye(n.element)}):n instanceof W?W.create(ye(n.unwrap())):n instanceof se?se.create(ye(n.unwrap())):n instanceof H?H.create(n.items.map(e=>ye(e))):n}class T extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=k.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==m.object){const l=this._getOrReturnCtx(e);return h(l,{code:f.invalid_type,expected:m.object,received:l.parsedType}),g}const{status:r,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof J&&this._def.unknownKeys==="strip"))for(const l in s.data)a.includes(l)||c.push(l);const d=[];for(const l of a){const u=o[l],v=s.data[l];d.push({key:{status:"valid",value:l},value:u._parse(new q(s,v,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof J){const l=this._def.unknownKeys;if(l==="passthrough")for(const u of c)d.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")c.length>0&&(h(s,{code:f.unrecognized_keys,keys:c}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const u of c){const v=s.data[u];d.push({key:{status:"valid",value:u},value:l._parse(new q(s,v,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const u of d){const v=await u.key,E=await u.value;l.push({key:v,value:E,alwaysSet:u.alwaysSet})}return l}).then(l=>A.mergeObjectSync(r,l)):A.mergeObjectSync(r,d)}get shape(){return this._def.shape()}strict(e){return p.errToObj,new T({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{var s,o,a,c;const d=(a=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,t,r).message)!==null&&a!==void 0?a:r.defaultError;return t.code==="unrecognized_keys"?{message:(c=p.errToObj(e).message)!==null&&c!==void 0?c:d}:{message:d}}}:{}})}strip(){return new T({...this._def,unknownKeys:"strip"})}passthrough(){return new T({...this._def,unknownKeys:"passthrough"})}extend(e){return new T({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new T({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new T({...this._def,catchall:e})}pick(e){const t={};return k.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new T({...this._def,shape:()=>t})}omit(e){const t={};return k.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new T({...this._def,shape:()=>t})}deepPartial(){return ye(this)}partial(e){const t={};return k.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}),new T({...this._def,shape:()=>t})}required(e){const t={};return k.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof W;)o=o._def.innerType;t[r]=o}}),new T({...this._def,shape:()=>t})}keyof(){return Gt(k.objectKeys(this.shape))}}T.create=(n,e)=>new T({shape:()=>n,unknownKeys:"strip",catchall:J.create(),typeName:y.ZodObject,..._(e)}),T.strictCreate=(n,e)=>new T({shape:()=>n,unknownKeys:"strict",catchall:J.create(),typeName:y.ZodObject,..._(e)}),T.lazycreate=(n,e)=>new T({shape:n,unknownKeys:"strip",catchall:J.create(),typeName:y.ZodObject,..._(e)});class Ne extends b{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;function s(o){for(const c of o)if(c.result.status==="valid")return c.result;for(const c of o)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;const a=o.map(c=>new $(c.ctx.common.issues));return h(t,{code:f.invalid_union,unionErrors:a}),g}if(t.common.async)return Promise.all(r.map(async o=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const d of r){const l={...t,common:{...t.common,issues:[]},parent:null},u=d._parseSync({data:t.data,path:t.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;const c=a.map(d=>new $(d));return h(t,{code:f.invalid_union,unionErrors:c}),g}}get options(){return this._def.options}}Ne.create=(n,e)=>new Ne({options:n,typeName:y.ZodUnion,..._(e)});const Q=n=>n instanceof Le?Q(n.schema):n instanceof V?Q(n.innerType()):n instanceof De?[n.value]:n instanceof re?n.options:n instanceof $e?k.objectValues(n.enum):n instanceof Ze?Q(n._def.innerType):n instanceof Ie?[void 0]:n instanceof Ae?[null]:n instanceof W?[void 0,...Q(n.unwrap())]:n instanceof se?[null,...Q(n.unwrap())]:n instanceof Ct||n instanceof Ve?Q(n.unwrap()):n instanceof Fe?Q(n._def.innerType):[];class rt extends b{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.object)return h(t,{code:f.invalid_type,expected:m.object,received:t.parsedType}),g;const r=this.discriminator,s=t.data[r],o=this.optionsMap.get(s);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(h(t,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const s=new Map;for(const o of t){const a=Q(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const c of a){if(s.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);s.set(c,o)}}return new rt({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,..._(r)})}}function Et(n,e){const t=ee(n),r=ee(e);if(n===e)return{valid:!0,data:n};if(t===m.object&&r===m.object){const s=k.objectKeys(e),o=k.objectKeys(n).filter(c=>s.indexOf(c)!==-1),a={...n,...e};for(const c of o){const d=Et(n[c],e[c]);if(!d.valid)return{valid:!1};a[c]=d.data}return{valid:!0,data:a}}else if(t===m.array&&r===m.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<n.length;o++){const a=n[o],c=e[o],d=Et(a,c);if(!d.valid)return{valid:!1};s.push(d.data)}return{valid:!0,data:s}}else return t===m.date&&r===m.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class je extends b{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(o,a)=>{if(bt(o)||bt(a))return g;const c=Et(o.value,a.value);return c.valid?((wt(o)||wt(a))&&t.dirty(),{status:t.value,value:c.data}):(h(r,{code:f.invalid_intersection_types}),g)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}je.create=(n,e,t)=>new je({left:n,right:e,typeName:y.ZodIntersection,..._(t)});class H extends b{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==m.array)return h(r,{code:f.invalid_type,expected:m.array,received:r.parsedType}),g;if(r.data.length<this._def.items.length)return h(r,{code:f.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&r.data.length>this._def.items.length&&(h(r,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const o=[...r.data].map((a,c)=>{const d=this._def.items[c]||this._def.rest;return d?d._parse(new q(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>A.mergeArray(t,a)):A.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new H({...this._def,rest:e})}}H.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new H({items:n,typeName:y.ZodTuple,rest:null,..._(e)})};class Me extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==m.object)return h(r,{code:f.invalid_type,expected:m.object,received:r.parsedType}),g;const s=[],o=this._def.keyType,a=this._def.valueType;for(const c in r.data)s.push({key:o._parse(new q(r,c,r.path,c)),value:a._parse(new q(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?A.mergeObjectAsync(t,s):A.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof b?new Me({keyType:e,valueType:t,typeName:y.ZodRecord,..._(r)}):new Me({keyType:F.create(),valueType:e,typeName:y.ZodRecord,..._(t)})}}class st extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==m.map)return h(r,{code:f.invalid_type,expected:m.map,received:r.parsedType}),g;const s=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([c,d],l)=>({key:s._parse(new q(r,c,r.path,[l,"key"])),value:o._parse(new q(r,d,r.path,[l,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const d of a){const l=await d.key,u=await d.value;if(l.status==="aborted"||u.status==="aborted")return g;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),c.set(l.value,u.value)}return{status:t.value,value:c}})}else{const c=new Map;for(const d of a){const l=d.key,u=d.value;if(l.status==="aborted"||u.status==="aborted")return g;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),c.set(l.value,u.value)}return{status:t.value,value:c}}}}st.create=(n,e,t)=>new st({valueType:e,keyType:n,typeName:y.ZodMap,..._(t)});class de extends b{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==m.set)return h(r,{code:f.invalid_type,expected:m.set,received:r.parsedType}),g;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(h(r,{code:f.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(h(r,{code:f.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const o=this._def.valueType;function a(d){const l=new Set;for(const u of d){if(u.status==="aborted")return g;u.status==="dirty"&&t.dirty(),l.add(u.value)}return{status:t.value,value:l}}const c=[...r.data.values()].map((d,l)=>o._parse(new q(r,d,r.path,l)));return r.common.async?Promise.all(c).then(d=>a(d)):a(c)}min(e,t){return new de({...this._def,minSize:{value:e,message:p.toString(t)}})}max(e,t){return new de({...this._def,maxSize:{value:e,message:p.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}de.create=(n,e)=>new de({valueType:n,minSize:null,maxSize:null,typeName:y.ZodSet,..._(e)});class ge extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.function)return h(t,{code:f.invalid_type,expected:m.function,received:t.parsedType}),g;function r(c,d){return Xe({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Qe(),he].filter(l=>!!l),issueData:{code:f.invalid_arguments,argumentsError:d}})}function s(c,d){return Xe({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Qe(),he].filter(l=>!!l),issueData:{code:f.invalid_return_type,returnTypeError:d}})}const o={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof _e){const c=this;return L(async function(...d){const l=new $([]),u=await c._def.args.parseAsync(d,o).catch(w=>{throw l.addIssue(r(d,w)),l}),v=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(v,o).catch(w=>{throw l.addIssue(s(v,w)),l})})}else{const c=this;return L(function(...d){const l=c._def.args.safeParse(d,o);if(!l.success)throw new $([r(d,l.error)]);const u=Reflect.apply(a,this,l.data),v=c._def.returns.safeParse(u,o);if(!v.success)throw new $([s(u,v.error)]);return v.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ge({...this._def,args:H.create(e).rest(le.create())})}returns(e){return new ge({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ge({args:e||H.create([]).rest(le.create()),returns:t||le.create(),typeName:y.ZodFunction,..._(r)})}}class Le extends b{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Le.create=(n,e)=>new Le({getter:n,typeName:y.ZodLazy,..._(e)});class De extends b{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:f.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}}De.create=(n,e)=>new De({value:n,typeName:y.ZodLiteral,..._(e)});function Gt(n,e){return new re({values:n,typeName:y.ZodEnum,..._(e)})}class re extends b{constructor(){super(...arguments),Oe.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return h(t,{expected:k.joinValues(r),received:t.parsedType,code:f.invalid_type}),g}if(et(this,Oe)||qt(this,Oe,new Set(this._def.values)),!et(this,Oe).has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return h(t,{received:t.data,code:f.invalid_enum_value,options:r}),g}return L(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return re.create(e,{...this._def,...t})}exclude(e,t=this._def){return re.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}}Oe=new WeakMap,re.create=Gt;class $e extends b{constructor(){super(...arguments),Re.set(this,void 0)}_parse(e){const t=k.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==m.string&&r.parsedType!==m.number){const s=k.objectValues(t);return h(r,{expected:k.joinValues(s),received:r.parsedType,code:f.invalid_type}),g}if(et(this,Re)||qt(this,Re,new Set(k.getValidEnumValues(this._def.values))),!et(this,Re).has(e.data)){const s=k.objectValues(t);return h(r,{received:r.data,code:f.invalid_enum_value,options:s}),g}return L(e.data)}get enum(){return this._def.values}}Re=new WeakMap,$e.create=(n,e)=>new $e({values:n,typeName:y.ZodNativeEnum,..._(e)});class _e extends b{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.promise&&t.common.async===!1)return h(t,{code:f.invalid_type,expected:m.promise,received:t.parsedType}),g;const r=t.parsedType===m.promise?t.data:Promise.resolve(t.data);return L(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}_e.create=(n,e)=>new _e({type:n,typeName:y.ZodPromise,..._(e)});class V extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:a=>{h(r,a),a.fatal?t.abort():t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(r.data,o);if(r.common.async)return Promise.resolve(a).then(async c=>{if(t.value==="aborted")return g;const d=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return d.status==="aborted"?g:d.status==="dirty"||t.value==="dirty"?me(d.value):d});{if(t.value==="aborted")return g;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?g:c.status==="dirty"||t.value==="dirty"?me(c.value):c}}if(s.type==="refinement"){const a=c=>{const d=s.refinement(c,o);if(r.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?g:(c.status==="dirty"&&t.dirty(),a(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?g:(c.status==="dirty"&&t.dirty(),a(c.value).then(()=>({status:t.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Se(a))return a;const c=s.transform(a.value,o);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Se(a)?Promise.resolve(s.transform(a.value,o)).then(c=>({status:t.value,value:c})):a);k.assertNever(s)}}V.create=(n,e,t)=>new V({schema:n,typeName:y.ZodEffects,effect:e,..._(t)}),V.createWithPreprocess=(n,e,t)=>new V({schema:e,effect:{type:"preprocess",transform:n},typeName:y.ZodEffects,..._(t)});class W extends b{_parse(e){return this._getType(e)===m.undefined?L(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}W.create=(n,e)=>new W({innerType:n,typeName:y.ZodOptional,..._(e)});class se extends b{_parse(e){return this._getType(e)===m.null?L(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}se.create=(n,e)=>new se({innerType:n,typeName:y.ZodNullable,..._(e)});class Ze extends b{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===m.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ze.create=(n,e)=>new Ze({innerType:n,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});class Fe extends b{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Te(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new $(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new $(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Fe.create=(n,e)=>new Fe({innerType:n,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});class ot extends b{_parse(e){if(this._getType(e)!==m.nan){const r=this._getOrReturnCtx(e);return h(r,{code:f.invalid_type,expected:m.nan,received:r.parsedType}),g}return{status:"valid",value:e.data}}}ot.create=n=>new ot({typeName:y.ZodNaN,..._(n)});const pr=Symbol("zod_brand");class Ct extends b{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ue extends b{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?g:o.status==="dirty"?(t.dirty(),me(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?g:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new Ue({in:e,out:t,typeName:y.ZodPipeline})}}class Ve extends b{_parse(e){const t=this._def.innerType._parse(e),r=s=>(Se(s)&&(s.value=Object.freeze(s.value)),s);return Te(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}}Ve.create=(n,e)=>new Ve({innerType:n,typeName:y.ZodReadonly,..._(e)});function Jt(n,e={},t){return n?pe.create().superRefine((r,s)=>{var o,a;if(!n(r)){const c=typeof e=="function"?e(r):typeof e=="string"?{message:e}:e,d=(a=(o=c.fatal)!==null&&o!==void 0?o:t)!==null&&a!==void 0?a:!0,l=typeof c=="string"?{message:c}:c;s.addIssue({code:"custom",...l,fatal:d})}}):pe.create()}const yr={object:T.lazycreate};var y;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(y||(y={}));const gr=(n,e={message:`Input not instance of ${n.name}`})=>Jt(t=>t instanceof n,e),Qt=F.create,Xt=te.create,_r=ot.create,vr=ne.create,en=Pe.create,br=ce.create,wr=tt.create,kr=Ie.create,Er=Ae.create,Cr=pe.create,xr=le.create,Sr=J.create,Tr=nt.create,Or=U.create,Rr=T.create,Pr=T.strictCreate,Ir=Ne.create,Ar=rt.create,Nr=je.create,jr=H.create,Mr=Me.create,Lr=st.create,Dr=de.create,$r=ge.create,Zr=Le.create,Fr=De.create,Ur=re.create,Vr=$e.create,zr=_e.create,tn=V.create,Br=W.create,qr=se.create,Hr=V.createWithPreprocess,Wr=Ue.create;var i=Object.freeze({__proto__:null,defaultErrorMap:he,setErrorMap:Qn,getErrorMap:Qe,makeIssue:Xe,EMPTY_PATH:Xn,addIssueToContext:h,ParseStatus:A,INVALID:g,DIRTY:me,OK:L,isAborted:bt,isDirty:wt,isValid:Se,isAsync:Te,get util(){return k},get objectUtil(){return vt},ZodParsedType:m,getParsedType:ee,ZodType:b,datetimeRegex:Kt,ZodString:F,ZodNumber:te,ZodBigInt:ne,ZodBoolean:Pe,ZodDate:ce,ZodSymbol:tt,ZodUndefined:Ie,ZodNull:Ae,ZodAny:pe,ZodUnknown:le,ZodNever:J,ZodVoid:nt,ZodArray:U,ZodObject:T,ZodUnion:Ne,ZodDiscriminatedUnion:rt,ZodIntersection:je,ZodTuple:H,ZodRecord:Me,ZodMap:st,ZodSet:de,ZodFunction:ge,ZodLazy:Le,ZodLiteral:De,ZodEnum:re,ZodNativeEnum:$e,ZodPromise:_e,ZodEffects:V,ZodTransformer:V,ZodOptional:W,ZodNullable:se,ZodDefault:Ze,ZodCatch:Fe,ZodNaN:ot,BRAND:pr,ZodBranded:Ct,ZodPipeline:Ue,ZodReadonly:Ve,custom:Jt,Schema:b,ZodSchema:b,late:yr,get ZodFirstPartyTypeKind(){return y},coerce:{string:n=>F.create({...n,coerce:!0}),number:n=>te.create({...n,coerce:!0}),boolean:n=>Pe.create({...n,coerce:!0}),bigint:n=>ne.create({...n,coerce:!0}),date:n=>ce.create({...n,coerce:!0})},any:Cr,array:Or,bigint:vr,boolean:en,date:br,discriminatedUnion:Ar,effect:tn,enum:Ur,function:$r,instanceof:gr,intersection:Nr,lazy:Zr,literal:Fr,map:Lr,nan:_r,nativeEnum:Vr,never:Sr,null:Er,nullable:qr,number:Xt,object:Rr,oboolean:()=>en().optional(),onumber:()=>Xt().optional(),optional:Br,ostring:()=>Qt().optional(),pipeline:Wr,preprocess:Hr,promise:zr,record:Mr,set:Dr,strictObject:Pr,string:Qt,symbol:wr,transformer:tn,tuple:jr,undefined:kr,union:Ir,unknown:xr,void:Tr,NEVER:g,ZodIssueCode:f,quotelessJson:Jn,ZodError:$});const Yr=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()}),Kr=i.array(Yr),Gr=i.object({code:i.string(),message:i.string(),path:i.array(i.string())}),Jr=i.array(Gr),Qr={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},xt=n=>{const e=n.toLowerCase().trim();return Qr[e]??n},Xr=n=>{try{return typeof JSON.parse(n)=="object"}catch{return!1}},es=n=>n.length===1?xt(n[0].msg):`Please fix the following errors:
2
- ${n.map(t=>`• ${xt(t.msg)}`).join(`
3
- `)}`,ts=n=>`Encountered the following errors:
4
- ${n.map(t=>`- ${t.path.join("/")}: ${t.message}`).join(`
5
- `)}`,nn=n=>{if(n instanceof Error)if(Xr(n.message)){const e=JSON.parse(n.message);return Kr.safeParse(e).success?es(e):Jr.safeParse(e).success?ts(e):(console.warn(`Encountered unknown stringified JSON object:
6
- ${n.message}`),n.message)}else return xt(n.message);if(typeof n=="object")try{return JSON.stringify(n)}catch(e){return e+""}else return n+""},ze=(n,e)=>(...t)=>{try{return e(...t)}catch(r){console.error(`[form] Error running callback (${n}):`,r);return}},N=i.string().trim().min(1,{message:"Cannot be blank"}),j=i.string().trim().optional(),it=n=>i.nullable(n.optional());var C=(n=>(n.FIRST_NAME="firstName",n.LAST_NAME="lastName",n.EMAIL="email",n.ZIP_CODE="zipCode",n.CITY="city",n.STATE="state",n.COUNTRY="country",n.ADDRESS="address",n.PHONE="phone",n.PROMOTION_CODE="promotionCode",n))(C||{});const rn=i.nativeEnum(C);var sn=(n=>(n.CARD_NUMBER="cardNumber",n.CARD_EXPIRY="cardExpiry",n.CARD_CVC="cardCvc",n))(sn||{});const on=i.nativeEnum(sn),an=i.union([rn,on]);var cn=(n=>(n.CARD="card",n.CARD_NUMBER="card-number",n.CARD_EXPIRY="card-expiry",n.CARD_CVC="card-cvc",n))(cn||{});const ns=i.nativeEnum(cn),at=i.object({provider:i.string(),processor_name:it(i.string()),metadata:it(i.record(i.string(),i.any()))}),rs=i.object({id:i.string()});i.object({cardNumber:j,expiry:j,cvc:j}),i.object({backgroundColor:j,color:j,fontFamily:j,fontSize:j,fontWeight:j,margin:j,padding:j,letterSpacing:j,lineHeight:j});const z=i.enum(["LAYOUT","LOADED","BLUR","FOCUS","CHANGE","TOKENIZE_STARTED","CHECKOUT_STARTED","PAYMENT_FLOW_STARTED","TOKENIZE_SUCCESS","CHECKOUT_SUCCESS","LOAD_ERROR","VALIDATION_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR","SETUP_PAYMENT_METHOD_SUCCESS","TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),ss=z.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),os=i.object({type:ss}),is=z.extract(["BLUR","FOCUS","CHANGE"]),as=i.object({type:is,elementType:on,errors:i.array(i.string()).optional()}),cs=z.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),ls=i.object({type:cs,message:N,headers:i.record(i.string(),i.string()).optional()}),ds=z.extract(["VALIDATION_ERROR"]),us=i.object({type:ds,elementType:an,errors:i.array(i.string())}),fs=i.object({type:i.literal(z.enum.LAYOUT),height:N}),hs=i.object({type:i.literal(z.enum.LOADED),sessionId:N,totalAmountAtoms:i.number(),currency:j,checkoutPaymentMethods:i.array(at)}),ms=i.object({type:i.literal(z.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:i.record(i.string(),i.any()),paymentFlowMetadata:i.any().optional(),startPFMetadata:i.optional(i.record(i.string(),i.any()))}),ps=i.object({type:i.literal(z.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:i.string()}),Be=i.object({firstName:N,lastName:N,email:N,zipCode:N,country:N,promotionCode:j}),ys=i.object({email:N,zipCode:N,country:N,promotionCode:j}),gs=z.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),_s=i.object({type:gs,sessionId:N,checkoutPaymentMethod:at,paymentFlowMetadata:i.any().optional(),doNotUseLegacyCCFlow:i.boolean().optional(),existingCCPMId:j}).extend(Be.shape),vs=i.object({type:i.literal(z.enum.TOKENIZE_SUCCESS),isReadyForCheckout:i.boolean()}),bs=i.object({type:i.literal(z.enum.CHECKOUT_SUCCESS),invoiceUrls:i.array(i.string()),subscriptionIds:i.array(i.string()),customerId:i.string()}),ws=i.discriminatedUnion("type",[os,as,ls,us,fs,hs,_s,vs,bs,ms,ps]),ks=i.object({payload:ws,nonce:N,formId:N,elementId:N});i.object({amountAtom:i.number(),currency:N}),i.object({secure_token:i.string(),promotion_code:i.string().optional()}),i.object({secure_token:i.string(),existing_cc_pm_id:it(i.string())});const Es=i.object({payment_methods:i.array(rs)}),Cs=i.object({elementType:i.string(),errors:i.array(i.string())});i.object({session_id:i.string()});const xs=i.object({success:i.literal(!1),error_type:i.literal("validation_error"),errors:i.array(Cs)}),Ss=i.discriminatedUnion("success",[i.object({success:i.literal(!0)}),xs]);i.object({session_id:i.string(),checkout_payment_method:at,non_cde_form_fields:Be,do_not_use_legacy_cc_flow:i.boolean().optional(),existing_cc_pm_id:it(i.string())}),i.object({session_id:i.string(),checkout_payment_method:at,non_cde_form_fields:Be});var ct=(n=>(n.SUCCESS="success",n.FAILURE="failure",n.CANCELLED="cancelled",n))(ct||{});const Ts=i.object({status:i.enum(["success","failure","cancelled"])}),Os=i.object({type:i.string(),redirect_url:i.string(),initial_intent_id:i.string(),consent_id:i.string()}),Rs=n=>{const e={};return Object.entries(n).forEach(([t,r])=>{try{const s=rn.parse(t);Array.isArray(r)?e[s]=r:Array.isArray(r._errors)&&(e[s]=r._errors)}catch{return}}),e},Ps=i.object({stripe_pk:i.string(),client_secret:i.string(),stripe_pm_id:i.string()}),Is=i.object({type:i.string(),client_secret:i.string(),stripe_pk:i.string()}),As={usd:"usd",brl:"brl"},lt=async n=>{for(let t=0;t<10;t++)ln()||await Ms(500);if(!ln())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(n)},Ns=async(n,e)=>{const t=await lt(n);return{elements:t.elements(e),stripe:t}},js=async(n,e,t,r,s)=>{console.log(s);const o=await lt(n),a=As[t.toLowerCase().trim()];return o.paymentRequest({country:"US",currency:a,total:{label:"Total",amount:e,pending:r},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},Ms=n=>new Promise(e=>{setTimeout(e,n)}),ln=()=>"Stripe"in window,Ls=async n=>new Promise((e,t)=>{try{n.on("paymentmethod",async r=>{e(r)}),n.on("cancel",()=>{t(new Error("Payment cancelled, please click Submit again to pay"))})}catch(r){t(r)}}),Ds=async(n,e)=>{if(!n.stripe_pk||!n.client_secret)throw new Error(`Invalid next action metadata format: ${JSON.stringify(n)}`);const r=await(await lt(n.stripe_pk)).confirmCardSetup(n.client_secret,{payment_method:e.paymentMethod.id});if(r.error)throw e.complete("fail"),new Error(`Payment failed: ${r.error.message??"unknown"}`);return e.complete("success"),r},$s=async n=>{var s,o,a,c;const t=await(await lt(n.stripe_pk)).confirmCardSetup(n.client_secret,{payment_method:n.stripe_pm_id}),r=(s=t.setupIntent)==null?void 0:s.status;if(r==="succeeded")console.log("[3DS] CONFIRMING PM:",n.stripe_pm_id),console.log("[3DS] Setup intent created:",t.setupIntent);else throw r==="canceled"?new Error("Payment cancelled, please click Submit again to pay"):new Error(`${((o=t.error)==null?void 0:o.message)??((c=(a=t.setupIntent)==null?void 0:a.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},Zs=n=>JSON.stringify(n);for(var P=[],St=0;St<256;++St)P.push((St+256).toString(16).slice(1));function Fs(n,e=0){return(P[n[e+0]]+P[n[e+1]]+P[n[e+2]]+P[n[e+3]]+"-"+P[n[e+4]]+P[n[e+5]]+"-"+P[n[e+6]]+P[n[e+7]]+"-"+P[n[e+8]]+P[n[e+9]]+"-"+P[n[e+10]]+P[n[e+11]]+P[n[e+12]]+P[n[e+13]]+P[n[e+14]]+P[n[e+15]]).toLowerCase()}var dt,Us=new Uint8Array(16);function Vs(){if(!dt&&(dt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!dt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return dt(Us)}var zs=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const dn={randomUUID:zs};function Bs(n,e,t){if(dn.randomUUID&&!e&&!n)return dn.randomUUID();n=n||{};var r=n.random||(n.rng||Vs)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Fs(r)}const Tt=(n,e)=>Array.from(n.querySelectorAll("[data-opid]")??[]).reduce((s,o)=>{const a=o.getAttribute("data-opid");return a?{...s,[a]:o.value}:s},{}),qs=n=>{try{return ks.parse(n)}catch(e){throw console.error("Error parsing event payload:",n,e),e}},Hs=(n,e,t,r,s)=>{const o={payload:r,nonce:Bs(),formId:e,elementId:t};console.log(`[form ${e}] Sending event to child ${t}:`,o),n.postMessage(JSON.stringify(o),s)};var Y;(function(n){n.Call="call",n.Reply="reply",n.Syn="syn",n.SynAck="synAck",n.Ack="ack"})(Y||(Y={}));var ue;(function(n){n.Fulfilled="fulfilled",n.Rejected="rejected"})(ue||(ue={}));var qe;(function(n){n.ConnectionDestroyed="ConnectionDestroyed",n.ConnectionTimeout="ConnectionTimeout",n.NoIframeSrc="NoIframeSrc"})(qe||(qe={}));var Ot;(function(n){n.DataCloneError="DataCloneError"})(Ot||(Ot={}));var oe;(function(n){n.Message="message"})(oe||(oe={}));const Ws=(n,e)=>{const t=[];let r=!1;return{destroy(s){r||(r=!0,e(`${n}: Destroying connection`),t.forEach(o=>{o(s)}))},onDestroy(s){r?s():t.push(s)}}},Ys=n=>(...e)=>{n&&console.log("[Penpal]",...e)},Ks={"http:":"80","https:":"443"},Gs=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Js=["file:","data:"],Qs=n=>{if(n&&Js.find(c=>n.startsWith(c)))return"null";const e=document.location,t=Gs.exec(n);let r,s,o;t?(r=t[1]?t[1]:e.protocol,s=t[2],o=t[4]):(r=e.protocol,s=e.hostname,o=e.port);const a=o&&o!==Ks[r]?`:${o}`:"";return`${r}//${s}${a}`},un=({name:n,message:e,stack:t})=>({name:n,message:e,stack:t}),Xs=n=>{const e=new Error;return Object.keys(n).forEach(t=>e[t]=n[t]),e},eo=(n,e,t)=>{const{localName:r,local:s,remote:o,originForSending:a,originForReceiving:c}=n;let d=!1;const l=u=>{if(u.source!==o||u.data.penpal!==Y.Call)return;if(c!=="*"&&u.origin!==c){t(`${r} received message from origin ${u.origin} which did not match expected origin ${c}`);return}const v=u.data,{methodName:E,args:w,id:x}=v;t(`${r}: Received ${E}() call`);const G=Z=>fe=>{if(t(`${r}: Sending ${E}() reply`),d){t(`${r}: Unable to send ${E}() reply due to destroyed connection`);return}const X={penpal:Y.Reply,id:x,resolution:Z,returnValue:fe};Z===ue.Rejected&&fe instanceof Error&&(X.returnValue=un(fe),X.returnValueIsError=!0);try{o.postMessage(X,a)}catch(M){if(M.name===Ot.DataCloneError){const Ee={penpal:Y.Reply,id:x,resolution:ue.Rejected,returnValue:un(M),returnValueIsError:!0};o.postMessage(Ee,a)}throw M}};new Promise(Z=>Z(e[E].apply(e,w))).then(G(ue.Fulfilled),G(ue.Rejected))};return s.addEventListener(oe.Message,l),()=>{d=!0,s.removeEventListener(oe.Message,l)}};let to=0;const no=()=>++to,fn=".",hn=n=>n?n.split(fn):[],ro=n=>n.join(fn),so=(n,e)=>{const t=hn(e||"");return t.push(n),ro(t)},oo=(n,e,t)=>{const r=hn(e);return r.reduce((s,o,a)=>(typeof s[o]>"u"&&(s[o]={}),a===r.length-1&&(s[o]=t),s[o]),n),n},mn=(n,e)=>{const t={};return Object.keys(n).forEach(r=>{const s=n[r],o=so(r,e);typeof s=="object"&&Object.assign(t,mn(s,o)),typeof s=="function"&&(t[o]=s)}),t},io=n=>{const e={};for(const t in n)oo(e,t,n[t]);return e},ao=(n,e,t,r,s)=>{const{localName:o,local:a,remote:c,originForSending:d,originForReceiving:l}=e;let u=!1;s(`${o}: Connecting call sender`);const v=w=>(...x)=>{s(`${o}: Sending ${w}() call`);let G;try{c.closed&&(G=!0)}catch{G=!0}if(G&&r(),u){const Z=new Error(`Unable to send ${w}() call due to destroyed connection`);throw Z.code=qe.ConnectionDestroyed,Z}return new Promise((Z,fe)=>{const X=no(),M=Ce=>{if(Ce.source!==c||Ce.data.penpal!==Y.Reply||Ce.data.id!==X)return;if(l!=="*"&&Ce.origin!==l){s(`${o} received message from origin ${Ce.origin} which did not match expected origin ${l}`);return}const Vt=Ce.data;s(`${o}: Received ${w}() reply`),a.removeEventListener(oe.Message,M);let zt=Vt.returnValue;Vt.returnValueIsError&&(zt=Xs(zt)),(Vt.resolution===ue.Fulfilled?Z:fe)(zt)};a.addEventListener(oe.Message,M);const Ee={penpal:Y.Call,id:X,methodName:w,args:x};c.postMessage(Ee,d)})},E=t.reduce((w,x)=>(w[x]=v(x),w),{});return Object.assign(n,io(E)),()=>{u=!0}},co=(n,e,t,r,s)=>{const{destroy:o,onDestroy:a}=r;let c,d;const l={};return u=>{if(e!=="*"&&u.origin!==e){s(`Parent: Handshake - Received ACK message from origin ${u.origin} which did not match expected origin ${e}`);return}s("Parent: Handshake - Received ACK");const v={localName:"Parent",local:window,remote:u.source,originForSending:t,originForReceiving:e};c&&c(),c=eo(v,n,s),a(c),d&&d.forEach(w=>{delete l[w]}),d=u.data.methodNames;const E=ao(l,v,d,o,s);return a(E),l}},lo=(n,e,t,r)=>s=>{if(!s.source)return;if(t!=="*"&&s.origin!==t){n(`Parent: Handshake - Received SYN message from origin ${s.origin} which did not match expected origin ${t}`);return}n("Parent: Handshake - Received SYN, responding with SYN-ACK");const o={penpal:Y.SynAck,methodNames:Object.keys(e)};s.source.postMessage(o,r)},uo=6e4,fo=(n,e)=>{const{destroy:t,onDestroy:r}=e,s=setInterval(()=>{n.isConnected||(clearInterval(s),t())},uo);r(()=>{clearInterval(s)})},ho=(n,e)=>{let t;return n!==void 0&&(t=window.setTimeout(()=>{const r=new Error(`Connection timed out after ${n}ms`);r.code=qe.ConnectionTimeout,e(r)},n)),()=>{clearTimeout(t)}},mo=n=>{if(!n.src&&!n.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=qe.NoIframeSrc,e}},pn=n=>{let{iframe:e,methods:t={},childOrigin:r,timeout:s,debug:o=!1}=n;const a=Ys(o),c=Ws("Parent",a),{onDestroy:d,destroy:l}=c;r||(mo(e),r=Qs(e.src));const u=r==="null"?"*":r,v=mn(t),E=lo(a,v,r,u),w=co(v,r,u,c,a);return{promise:new Promise((G,Z)=>{const fe=ho(s,l),X=M=>{if(!(M.source!==e.contentWindow||!M.data)){if(M.data.penpal===Y.Syn){E(M);return}if(M.data.penpal===Y.Ack){const Ee=w(M);Ee&&(fe(),G(Ee));return}}};window.addEventListener(oe.Message,X),a("Parent: Awaiting handshake"),fo(e,c),d(M=>{window.removeEventListener(oe.Message,X),M&&Z(M)})}),destroy(){l()}}},po=async n=>{if(typeof n!="object"||!n)return!1;try{const e={type:"ping"},t=await n.send(e);if(t!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(t)}`);return!0}catch(e){return console.error("Invalid CDE connection check:",e),!1}},yo=(n,e)=>!!n&&e,O=n=>i.nullable(n.optional());i.string().trim().min(1,{message:"Cannot be blank"});const go=i.object({cde_response_type:i.literal("error"),message:i.string(),headers:i.record(i.string(),i.string()).optional()});i.enum(["usd","brl"]);const yn=i.object({name:i.string(),amount_atom_off:O(i.number()),percent_off:O(i.number()),currency:O(i.string()),duration:i.string(),duration_in_months:O(i.number())}),gn=i.object({amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),currency:i.string(),description:O(i.string()),price_id:i.string(),billing_interval:O(i.string()),billing_interval_count:O(i.number().int()),quantity:i.number().int()}),_o=i.record(i.string(),i.any()),vo=i.object({name:i.string(),settings:O(_o)}),He=i.object({provider:i.string(),processor_name:O(i.string()),metadata:O(i.record(i.string(),i.any()))}),bo=i.object({quantity:i.number()}),wo=i.object({id:O(i.string()),billing_interval:O(i.string()),billing_interval_count:O(i.number().int()),subscription_items:i.array(bo),trial_start:O(i.string()),trial_end:O(i.string())}),_n=i.object({amount_atom:i.number()}),ko=i.object({amount_atom:i.number(),amount_atom_considering_discount_applied:i.number(),currency:i.string(),discount_amount_atoms:i.array(_n),subscription_item_id:i.string()}),Eo=i.object({coupon:yn}),Co=i.object({currency:i.string(),discounts:i.array(Eo),hosted_invoice_url:O(i.string()),lines:i.array(ko),remaining_amount_atom:i.number(),tax_amount_atom:i.number(),total_amount_atom:i.number(),total_discount_amount_atoms:i.array(_n)}),vn=i.object({created:i.array(wo),invoices:i.array(Co)}),bn=i.object({preview:vn,preview_post_trial:O(vn),coupons:i.array(yn)}),wn=i.object({status:i.literal("open"),token:i.string(),email:O(i.string()),line_items:i.array(gn),amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),brand:vo,subs_preview:O(bn),methods_available:i.array(He)}),kn=i.discriminatedUnion("mode",[i.object({mode:i.literal("setup"),currency:i.nullable(i.undefined())}).extend(wn.shape),i.object({mode:i.enum(["payment","subscription"]),currency:i.string()}).extend(wn.shape)]),xo=i.object({status:i.literal("complete")}),So=i.object({status:i.literal("expired")});i.union([kn,xo,So]),i.object({logo:i.string(),icon:i.string(),primary_color:i.string(),secondary_color:i.string()});const En=i.object({invoice_urls:i.array(i.string()),subscription_ids:i.array(i.string()),customer_id:i.string()});i.object({secure_token:i.string(),payment_input:i.any(),customer_email:i.string(),customer_zip_code:i.string(),customer_country:i.string(),line_items:i.array(gn),total_amount_atom:i.number().int(),cancel_at_end:i.boolean(),checkout_payment_method:He,promotion_code:i.string().optional(),do_not_use_legacy_cc_flow:i.boolean().optional()});const To=i.object({payment_method_id:i.string()});i.object({id:i.string(),return_url:i.string()});const Oo=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()});i.array(Oo),i.object({new_customer_email:i.string().optional(),new_customer_address:i.record(i.string(),i.any()).optional(),payment_provider:i.string(),checkout_payment_method:He,existing_cc_pm_id:i.string().optional(),their_existing_pm_id:i.string().optional()});const Cn=i.object({required_user_actions:i.array(i.record(i.string(),i.any()))});i.object({fields:ys,checkoutPaymentMethod:He}),i.object({session_id:i.string(),non_cde_form_fields:Be,checkout_payment_method:He});const Ro=i.object({required_user_actions:i.array(i.record(i.string(),i.any())),cc_pm_id:i.string()});i.record(i.any());const Po=n=>n.reduce((e,t)=>e+t,0);function Io(n,e){var t=Object.setPrototypeOf;t?t(n,e):n.__proto__=e}function Ao(n,e){e===void 0&&(e=n.constructor);var t=Error.captureStackTrace;t&&t(n,e)}var No=function(){var n=function(t,r){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,o){s.__proto__=o}||function(s,o){for(var a in o)Object.prototype.hasOwnProperty.call(o,a)&&(s[a]=o[a])},n(t,r)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),jo=function(n){No(e,n);function e(t,r){var s=this.constructor,o=n.call(this,t,r)||this;return Object.defineProperty(o,"name",{value:s.name,enumerable:!1,configurable:!0}),Io(o,s.prototype),Ao(o),o}return e}(Error);class xn extends jo{constructor(e){const t=`[cde-client] Error querying CDE: ${e.message}`;super(t),this.response=e}get originalErrorMessage(){return this.response.message}}const B=async(n,e,t)=>{console.log("[cde-client] Querying CDE with path and connection:",e.type,n);const r=await n.send(e);if(console.log("[cde-client] Got response from CDE:",r),Lo(r))throw new xn(r);if(!Mo(r,t)){const s=t.safeParse(r);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",t,"Actual:",r),s.error)}return r},Mo=(n,e)=>e.safeParse(n).success,Lo=n=>go.safeParse(n).success,Do=async(n,e)=>await B(n,{type:"get_checkout_preview",payload:e},bn),We=async n=>await B(n,{type:"get_prefill",payload:{}},kn),$o=async(n,e)=>await B(n,{type:"v2_start_payment_flow",payload:e},Cn),Zo=async(n,e)=>await B(n,{type:"start_payment_flow_for_cc",payload:e},Ro),Fo=async(n,e)=>await B(n,{type:"start_payment_flow_for_pr",payload:e},Cn),Rt=async(n,e)=>await B(n,{type:"confirm_payment_flow",payload:e},Es),Uo=async(n,e,t)=>{const r=await Do(n,{secure_token:e,promotion_code:t}),s=new Set(r.preview.invoices.map(c=>c.currency));if(s.size!==1)throw new Error(`Expected exactly one currency, got ${s.size}`);const o=s.values().next().value??"usd",a=Po(r.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:o,amountAtom:a}},Sn=async(n,e,t,r)=>{if(t)return{amountAtom:0,currency:"usd"};{r=r||void 0;const s=await Uo(n,e,r);return{amountAtom:s.amountAtom,currency:s.currency}}},Vo=async(n,e)=>{if(n.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(n.values()).map(r=>B(r,{type:"tokenize_card",payload:e},Ss)))},Tn=async(n,e)=>{try{return await B(n,{type:"checkout_card_elements",payload:e},En)}catch(t){throw console.error("[cde-client] Error during checkoutCardElements:",t,JSON.stringify(t)),t}},zo=async(n,e)=>await B(n,{type:"setup_payment_method",payload:e},To),On=async(n,e)=>await B(n,{type:"checkout",payload:e},En),Rn=1e3,Bo=async(n,e)=>{console.log(e);const r=await pn({iframe:n,debug:!0,timeout:Rn,childOrigin:"*"}).promise;return(await B(r,{type:"ping-3ds-status"},Ts)).status},Pt=10,Pn=(n=0)=>e=>`\x1B[${e+n}m`,In=(n=0)=>e=>`\x1B[${38+n};5;${e}m`,An=(n=0)=>(e,t,r)=>`\x1B[${38+n};2;${e};${t};${r}m`,S={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(S.modifier);const qo=Object.keys(S.color),Ho=Object.keys(S.bgColor);[...qo,...Ho];function Wo(){const n=new Map;for(const[e,t]of Object.entries(S)){for(const[r,s]of Object.entries(t))S[r]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},t[r]=S[r],n.set(s[0],s[1]);Object.defineProperty(S,e,{value:t,enumerable:!1})}return Object.defineProperty(S,"codes",{value:n,enumerable:!1}),S.color.close="\x1B[39m",S.bgColor.close="\x1B[49m",S.color.ansi=Pn(),S.color.ansi256=In(),S.color.ansi16m=An(),S.bgColor.ansi=Pn(Pt),S.bgColor.ansi256=In(Pt),S.bgColor.ansi16m=An(Pt),Object.defineProperties(S,{rgbToAnsi256:{value(e,t,r){return e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[r]=t;r.length===3&&(r=[...r].map(o=>o+o).join(""));const s=Number.parseInt(r,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:e=>S.rgbToAnsi256(...S.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,r,s;if(e>=232)t=((e-232)*10+8)/255,r=t,s=t;else{e-=16;const c=e%36;t=Math.floor(e/36)/5,r=Math.floor(c/6)/5,s=c%6/5}const o=Math.max(t,r,s)*2;if(o===0)return 30;let a=30+(Math.round(s)<<2|Math.round(r)<<1|Math.round(t));return o===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,r)=>S.ansi256ToAnsi(S.rgbToAnsi256(e,t,r)),enumerable:!1},hexToAnsi:{value:e=>S.ansi256ToAnsi(S.hexToAnsi256(e)),enumerable:!1}}),S}const K=Wo(),ut=(()=>{if(navigator.userAgentData){const n=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(n&&n.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),Nn=ut!==0&&{level:ut,hasBasic:!0,has256:ut>=2,has16m:ut>=3},Yo={stdout:Nn,stderr:Nn};function Ko(n,e,t){let r=n.indexOf(e);if(r===-1)return n;const s=e.length;let o=0,a="";do a+=n.slice(o,r)+e+t,o=r+s,r=n.indexOf(e,o);while(r!==-1);return a+=n.slice(o),a}function Go(n,e,t,r){let s=0,o="";do{const a=n[r-1]==="\r";o+=n.slice(s,a?r-1:r)+e+(a?`\r
1
+ (function(he,Ae){typeof exports=="object"&&typeof module<"u"?Ae(exports):typeof define=="function"&&define.amd?define(["exports"],Ae):(he=typeof globalThis<"u"?globalThis:he||self,Ae(he.OpenPay={}))})(this,function(he){"use strict";const Ae="https://cde.getopenpay.com";var C;(function(r){r.assertEqual=s=>s;function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{const i={};for(const o of s)i[o]=o;return i},r.getValidEnumValues=s=>{const i=r.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),o={};for(const c of i)o[c]=s[c];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(const o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(C||(C={}));var Tt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Tt||(Tt={}));const m=C.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ie=r=>{switch(typeof r){case"undefined":return m.undefined;case"string":return m.string;case"number":return isNaN(r)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":return Array.isArray(r)?m.array:r===null?m.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?m.promise:typeof Map<"u"&&r instanceof Map?m.map:typeof Set<"u"&&r instanceof Set?m.set:typeof Date<"u"&&r instanceof Date?m.date:m.object;default:return m.unknown}},f=C.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"]),yn=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class V extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let c=n,l=0;for(;l<o.path.length;){const u=o.path[l];l===o.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(o))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};return s(this),n}static assert(e){if(!(e instanceof V))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,C.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}V.create=r=>new V(r);const _e=(r,e)=>{let t;switch(r.code){case f.invalid_type:r.received===m.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case f.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,C.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:t=`Unrecognized key(s) in object: ${C.joinValues(r.keys,", ")}`;break;case f.invalid_union:t="Invalid input";break;case f.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${C.joinValues(r.options)}`;break;case f.invalid_enum_value:t=`Invalid enum value. Expected ${C.joinValues(r.options)}, received '${r.received}'`;break;case f.invalid_arguments:t="Invalid function arguments";break;case f.invalid_return_type:t="Invalid function return type";break;case f.invalid_date:t="Invalid date";break;case f.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:C.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case f.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case f.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case f.custom:t="Invalid input";break;case f.invalid_intersection_types:t="Intersection results could not be merged";break;case f.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case f.not_finite:t="Number must be finite";break;default:t=e.defaultError,C.assertNever(r)}return{message:t}};let tr=_e;function gn(r){tr=r}function st(){return tr}const it=r=>{const{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let c="";const l=n.filter(u=>!!u).slice().reverse();for(const u of l)c=u(o,{data:e,defaultError:c}).message;return{...s,path:i,message:c}},_n=[];function h(r,e){const t=st(),n=it({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===_e?void 0:_e].filter(s=>!!s)});r.common.issues.push(n)}class M{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const s of t){if(s.status==="aborted")return b;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const s of t){const i=await s.key,o=await s.value;n.push({key:i,value:o})}return M.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return b;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}}const b=Object.freeze({status:"aborted"}),ve=r=>({status:"dirty",value:r}),Z=r=>({status:"valid",value:r}),Ot=r=>r.status==="aborted",Rt=r=>r.status==="dirty",je=r=>r.status==="valid",Ne=r=>typeof Promise<"u"&&r instanceof Promise;function ot(r,e,t,n){if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function rr(r,e,t,n,s){if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}typeof SuppressedError=="function"&&SuppressedError;var g;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(g||(g={}));var Me,Le;class G{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const nr=(r,e)=>{if(je(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new V(r.common.issues);return this._error=t,this._error}}};function k(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,c)=>{var l,u;const{message:d}=r;return o.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(l=d??n)!==null&&l!==void 0?l:c.defaultError}:o.code!=="invalid_type"?{message:c.defaultError}:{message:(u=d??t)!==null&&u!==void 0?u:c.defaultError}},description:s}}class E{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 ie(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new M,ctx:{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ne(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;const s={common:{issues:[],async:(n=t==null?void 0:t.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},i=this._parseSync({data:e,path:s.path,parent:s});return nr(s,i)}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Ne(s)?s:Promise.resolve(s));return nr(n,i)}refine(e,t){const n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{const o=e(s),c=()=>i.addIssue({code:f.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(c(),!1)):o?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new q({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return J.create(this,this._def)}nullable(){return ue.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return B.create(this,this._def)}promise(){return Ee.create(this,this._def)}or(e){return Ue.create([this,e],this._def)}and(e){return Fe.create(this,e,this._def)}transform(e){return new q({...k(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new He({...k(this._def),innerType:this,defaultValue:t,typeName:v.ZodDefault})}brand(){return new At({typeName:v.ZodBranded,type:this,...k(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Ye({...k(this._def),innerType:this,catchValue:t,typeName:v.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return We.create(this,e)}readonly(){return Ge.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const vn=/^c[^\s-]{8,}$/i,bn=/^[0-9a-z]+$/,wn=/^[0-9A-HJKMNP-TV-Z]{26}$/,kn=/^[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,En=/^[a-z0-9_-]{21}$/i,Sn=/^[-+]?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)?)??$/,Cn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Pt;const Tn=/^(?:(?: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])$/,On=/^(([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})))$/,Rn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,sr="((\\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])))",Pn=new RegExp(`^${sr}$`);function ir(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function In(r){return new RegExp(`^${ir(r)}$`)}function or(r){let e=`${sr}T${ir(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function An(r,e){return!!((e==="v4"||!e)&&Tn.test(r)||(e==="v6"||!e)&&On.test(r))}class z extends E{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==m.string){const i=this._getOrReturnCtx(e);return h(i,{code:f.invalid_type,expected:m.string,received:i.parsedType}),b}const n=new M;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),h(s,{code:f.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),h(s,{code:f.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,c=e.data.length<i.value;(o||c)&&(s=this._getOrReturnCtx(e,s),o?h(s,{code:f.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&h(s,{code:f.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Cn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"email",code:f.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Pt||(Pt=new RegExp(xn,"u")),Pt.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"emoji",code:f.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")kn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"uuid",code:f.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")En.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"nanoid",code:f.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")vn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"cuid",code:f.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")bn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"cuid2",code:f.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")wn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"ulid",code:f.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),h(s,{validation:"url",code:f.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"regex",code:f.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?or(i).test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Pn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?In(i).test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Sn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"duration",code:f.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?An(e.data,i.version)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"ip",code:f.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Rn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"base64",code:f.invalid_string,message:i.message}),n.dirty()):C.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:f.invalid_string,...g.errToObj(n)})}_addCheck(e){return new z({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...g.errToObj(e)})}url(e){return this._addCheck({kind:"url",...g.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...g.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...g.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...g.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...g.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...g.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...g.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...g.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...g.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...g.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,...g.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...g.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...g.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...g.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...g.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...g.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...g.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...g.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...g.errToObj(t)})}nonempty(e){return this.min(1,g.errToObj(e))}trim(){return new z({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new z({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new z({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}z.create=r=>{var e;return new z({checks:[],typeName:v.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...k(r)})};function jn(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=parseInt(r.toFixed(s).replace(".","")),o=parseInt(e.toFixed(s).replace(".",""));return i%o/Math.pow(10,s)}class oe extends E{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)!==m.number){const i=this._getOrReturnCtx(e);return h(i,{code:f.invalid_type,expected:m.number,received:i.parsedType}),b}let n;const s=new M;for(const i of this._def.checks)i.kind==="int"?C.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:f.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?jn(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_finite,message:i.message}),s.dirty()):C.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,g.toString(t))}gt(e,t){return this.setLimit("min",e,!1,g.toString(t))}lte(e,t){return this.setLimit("max",e,!0,g.toString(t))}lt(e,t){return this.setLimit("max",e,!1,g.toString(t))}setLimit(e,t,n,s){return new oe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:g.toString(s)}]})}_addCheck(e){return new oe({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:g.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:g.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:g.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:g.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:g.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:g.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:g.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:g.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:g.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&C.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}oe.create=r=>new oe({checks:[],typeName:v.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...k(r)});class ae extends E{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)!==m.bigint){const i=this._getOrReturnCtx(e);return h(i,{code:f.invalid_type,expected:m.bigint,received:i.parsedType}),b}let n;const s=new M;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):C.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,g.toString(t))}gt(e,t){return this.setLimit("min",e,!1,g.toString(t))}lte(e,t){return this.setLimit("max",e,!0,g.toString(t))}lt(e,t){return this.setLimit("max",e,!1,g.toString(t))}setLimit(e,t,n,s){return new ae({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:g.toString(s)}]})}_addCheck(e){return new ae({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:g.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:g.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:g.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:g.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:g.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ae.create=r=>{var e;return new ae({checks:[],typeName:v.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...k(r)})};class De extends E{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==m.boolean){const n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.boolean,received:n.parsedType}),b}return Z(e.data)}}De.create=r=>new De({typeName:v.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...k(r)});class pe extends E{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==m.date){const i=this._getOrReturnCtx(e);return h(i,{code:f.invalid_type,expected:m.date,received:i.parsedType}),b}if(isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return h(i,{code:f.invalid_date}),b}const n=new M;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),h(s,{code:f.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),h(s,{code:f.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):C.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new pe({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:g.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:g.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}pe.create=r=>new pe({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:v.ZodDate,...k(r)});class at extends E{_parse(e){if(this._getType(e)!==m.symbol){const n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.symbol,received:n.parsedType}),b}return Z(e.data)}}at.create=r=>new at({typeName:v.ZodSymbol,...k(r)});class $e extends E{_parse(e){if(this._getType(e)!==m.undefined){const n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.undefined,received:n.parsedType}),b}return Z(e.data)}}$e.create=r=>new $e({typeName:v.ZodUndefined,...k(r)});class Ze extends E{_parse(e){if(this._getType(e)!==m.null){const n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.null,received:n.parsedType}),b}return Z(e.data)}}Ze.create=r=>new Ze({typeName:v.ZodNull,...k(r)});class be extends E{constructor(){super(...arguments),this._any=!0}_parse(e){return Z(e.data)}}be.create=r=>new be({typeName:v.ZodAny,...k(r)});class me extends E{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Z(e.data)}}me.create=r=>new me({typeName:v.ZodUnknown,...k(r)});class te extends E{_parse(e){const t=this._getOrReturnCtx(e);return h(t,{code:f.invalid_type,expected:m.never,received:t.parsedType}),b}}te.create=r=>new te({typeName:v.ZodNever,...k(r)});class ct extends E{_parse(e){if(this._getType(e)!==m.undefined){const n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.void,received:n.parsedType}),b}return Z(e.data)}}ct.create=r=>new ct({typeName:v.ZodVoid,...k(r)});class B extends E{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==m.array)return h(t,{code:f.invalid_type,expected:m.array,received:t.parsedType}),b;if(s.exactLength!==null){const o=t.data.length>s.exactLength.value,c=t.data.length<s.exactLength.value;(o||c)&&(h(t,{code:o?f.too_big:f.too_small,minimum:c?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(h(t,{code:f.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(h(t,{code:f.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,c)=>s.type._parseAsync(new G(t,o,t.path,c)))).then(o=>M.mergeArray(n,o));const i=[...t.data].map((o,c)=>s.type._parseSync(new G(t,o,t.path,c)));return M.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new B({...this._def,minLength:{value:e,message:g.toString(t)}})}max(e,t){return new B({...this._def,maxLength:{value:e,message:g.toString(t)}})}length(e,t){return new B({...this._def,exactLength:{value:e,message:g.toString(t)}})}nonempty(e){return this.min(1,e)}}B.create=(r,e)=>new B({type:r,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...k(e)});function we(r){if(r instanceof R){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=J.create(we(n))}return new R({...r._def,shape:()=>e})}else return r instanceof B?new B({...r._def,type:we(r.element)}):r instanceof J?J.create(we(r.unwrap())):r instanceof ue?ue.create(we(r.unwrap())):r instanceof K?K.create(r.items.map(e=>we(e))):r}class R extends E{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=C.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==m.object){const u=this._getOrReturnCtx(e);return h(u,{code:f.invalid_type,expected:m.object,received:u.parsedType}),b}const{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof te&&this._def.unknownKeys==="strip"))for(const u in s.data)o.includes(u)||c.push(u);const l=[];for(const u of o){const d=i[u],y=s.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new G(s,y,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof te){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of c)l.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(u==="strict")c.length>0&&(h(s,{code:f.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 y=s.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new G(s,y,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of l){const y=await d.key,w=await d.value;u.push({key:y,value:w,alwaysSet:d.alwaysSet})}return u}).then(u=>M.mergeObjectSync(n,u)):M.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return g.errToObj,new R({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var s,i,o,c;const l=(o=(i=(s=this._def).errorMap)===null||i===void 0?void 0:i.call(s,t,n).message)!==null&&o!==void 0?o:n.defaultError;return t.code==="unrecognized_keys"?{message:(c=g.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new R({...this._def,unknownKeys:"strip"})}passthrough(){return new R({...this._def,unknownKeys:"passthrough"})}extend(e){return new R({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new R({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new R({...this._def,catchall:e})}pick(e){const t={};return C.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new R({...this._def,shape:()=>t})}omit(e){const t={};return C.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new R({...this._def,shape:()=>t})}deepPartial(){return we(this)}partial(e){const t={};return C.objectKeys(this.shape).forEach(n=>{const s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}),new R({...this._def,shape:()=>t})}required(e){const t={};return C.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof J;)i=i._def.innerType;t[n]=i}}),new R({...this._def,shape:()=>t})}keyof(){return ar(C.objectKeys(this.shape))}}R.create=(r,e)=>new R({shape:()=>r,unknownKeys:"strip",catchall:te.create(),typeName:v.ZodObject,...k(e)}),R.strictCreate=(r,e)=>new R({shape:()=>r,unknownKeys:"strict",catchall:te.create(),typeName:v.ZodObject,...k(e)}),R.lazycreate=(r,e)=>new R({shape:r,unknownKeys:"strip",catchall:te.create(),typeName:v.ZodObject,...k(e)});class Ue extends E{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(const c of i)if(c.result.status==="valid")return c.result;for(const c of i)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;const o=i.map(c=>new V(c.ctx.common.issues));return h(t,{code:f.invalid_union,unionErrors:o}),b}if(t.common.async)return Promise.all(n.map(async i=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i;const o=[];for(const l of n){const u={...t,common:{...t.common,issues:[]},parent:null},d=l._parseSync({data:t.data,path:t.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const c=o.map(l=>new V(l));return h(t,{code:f.invalid_union,unionErrors:c}),b}}get options(){return this._def.options}}Ue.create=(r,e)=>new Ue({options:r,typeName:v.ZodUnion,...k(e)});const re=r=>r instanceof ze?re(r.schema):r instanceof q?re(r.innerType()):r instanceof Be?[r.value]:r instanceof ce?r.options:r instanceof qe?C.objectValues(r.enum):r instanceof He?re(r._def.innerType):r instanceof $e?[void 0]:r instanceof Ze?[null]:r instanceof J?[void 0,...re(r.unwrap())]:r instanceof ue?[null,...re(r.unwrap())]:r instanceof At||r instanceof Ge?re(r.unwrap()):r instanceof Ye?re(r._def.innerType):[];class ut extends E{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.object)return h(t,{code:f.invalid_type,expected:m.object,received:t.parsedType}),b;const n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(h(t,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),b)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const s=new Map;for(const i of t){const o=re(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const c of o){if(s.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);s.set(c,i)}}return new ut({typeName:v.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...k(n)})}}function It(r,e){const t=ie(r),n=ie(e);if(r===e)return{valid:!0,data:r};if(t===m.object&&n===m.object){const s=C.objectKeys(e),i=C.objectKeys(r).filter(c=>s.indexOf(c)!==-1),o={...r,...e};for(const c of i){const l=It(r[c],e[c]);if(!l.valid)return{valid:!1};o[c]=l.data}return{valid:!0,data:o}}else if(t===m.array&&n===m.array){if(r.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<r.length;i++){const o=r[i],c=e[i],l=It(o,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return t===m.date&&n===m.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class Fe extends E{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(Ot(i)||Ot(o))return b;const c=It(i.value,o.value);return c.valid?((Rt(i)||Rt(o))&&t.dirty(),{status:t.value,value:c.data}):(h(n,{code:f.invalid_intersection_types}),b)};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(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Fe.create=(r,e,t)=>new Fe({left:r,right:e,typeName:v.ZodIntersection,...k(t)});class K extends E{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.array)return h(n,{code:f.invalid_type,expected:m.array,received:n.parsedType}),b;if(n.data.length<this._def.items.length)return h(n,{code:f.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),b;!this._def.rest&&n.data.length>this._def.items.length&&(h(n,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...n.data].map((o,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new G(n,o,n.path,c)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>M.mergeArray(t,o)):M.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new K({...this._def,rest:e})}}K.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new K({items:r,typeName:v.ZodTuple,rest:null,...k(e)})};class Ve extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.object)return h(n,{code:f.invalid_type,expected:m.object,received:n.parsedType}),b;const s=[],i=this._def.keyType,o=this._def.valueType;for(const c in n.data)s.push({key:i._parse(new G(n,c,n.path,c)),value:o._parse(new G(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?M.mergeObjectAsync(t,s):M.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof E?new Ve({keyType:e,valueType:t,typeName:v.ZodRecord,...k(n)}):new Ve({keyType:z.create(),valueType:e,typeName:v.ZodRecord,...k(t)})}}class lt extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.map)return h(n,{code:f.invalid_type,expected:m.map,received:n.parsedType}),b;const s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([c,l],u)=>({key:s._parse(new G(n,c,n.path,[u,"key"])),value:i._parse(new G(n,l,n.path,[u,"value"]))}));if(n.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of o){const u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return b;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(u.value,d.value)}return{status:t.value,value:c}})}else{const c=new Map;for(const l of o){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return b;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(u.value,d.value)}return{status:t.value,value:c}}}}lt.create=(r,e,t)=>new lt({valueType:e,keyType:r,typeName:v.ZodMap,...k(t)});class ye extends E{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.set)return h(n,{code:f.invalid_type,expected:m.set,received:n.parsedType}),b;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(h(n,{code:f.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(h(n,{code:f.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const i=this._def.valueType;function o(l){const u=new Set;for(const d of l){if(d.status==="aborted")return b;d.status==="dirty"&&t.dirty(),u.add(d.value)}return{status:t.value,value:u}}const c=[...n.data.values()].map((l,u)=>i._parse(new G(n,l,n.path,u)));return n.common.async?Promise.all(c).then(l=>o(l)):o(c)}min(e,t){return new ye({...this._def,minSize:{value:e,message:g.toString(t)}})}max(e,t){return new ye({...this._def,maxSize:{value:e,message:g.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ye.create=(r,e)=>new ye({valueType:r,minSize:null,maxSize:null,typeName:v.ZodSet,...k(e)});class ke extends E{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.function)return h(t,{code:f.invalid_type,expected:m.function,received:t.parsedType}),b;function n(c,l){return it({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,st(),_e].filter(u=>!!u),issueData:{code:f.invalid_arguments,argumentsError:l}})}function s(c,l){return it({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,st(),_e].filter(u=>!!u),issueData:{code:f.invalid_return_type,returnTypeError:l}})}const i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Ee){const c=this;return Z(async function(...l){const u=new V([]),d=await c._def.args.parseAsync(l,i).catch(p=>{throw u.addIssue(n(l,p)),u}),y=await Reflect.apply(o,this,d);return await c._def.returns._def.type.parseAsync(y,i).catch(p=>{throw u.addIssue(s(y,p)),u})})}else{const c=this;return Z(function(...l){const u=c._def.args.safeParse(l,i);if(!u.success)throw new V([n(l,u.error)]);const d=Reflect.apply(o,this,u.data),y=c._def.returns.safeParse(d,i);if(!y.success)throw new V([s(d,y.error)]);return y.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ke({...this._def,args:K.create(e).rest(me.create())})}returns(e){return new ke({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new ke({args:e||K.create([]).rest(me.create()),returns:t||me.create(),typeName:v.ZodFunction,...k(n)})}}class ze extends E{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ze.create=(r,e)=>new ze({getter:r,typeName:v.ZodLazy,...k(e)});class Be extends E{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:f.invalid_literal,expected:this._def.value}),b}return{status:"valid",value:e.data}}get value(){return this._def.value}}Be.create=(r,e)=>new Be({value:r,typeName:v.ZodLiteral,...k(e)});function ar(r,e){return new ce({values:r,typeName:v.ZodEnum,...k(e)})}class ce extends E{constructor(){super(...arguments),Me.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return h(t,{expected:C.joinValues(n),received:t.parsedType,code:f.invalid_type}),b}if(ot(this,Me)||rr(this,Me,new Set(this._def.values)),!ot(this,Me).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return h(t,{received:t.data,code:f.invalid_enum_value,options:n}),b}return Z(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ce.create(e,{...this._def,...t})}exclude(e,t=this._def){return ce.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}Me=new WeakMap,ce.create=ar;class qe extends E{constructor(){super(...arguments),Le.set(this,void 0)}_parse(e){const t=C.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==m.string&&n.parsedType!==m.number){const s=C.objectValues(t);return h(n,{expected:C.joinValues(s),received:n.parsedType,code:f.invalid_type}),b}if(ot(this,Le)||rr(this,Le,new Set(C.getValidEnumValues(this._def.values))),!ot(this,Le).has(e.data)){const s=C.objectValues(t);return h(n,{received:n.data,code:f.invalid_enum_value,options:s}),b}return Z(e.data)}get enum(){return this._def.values}}Le=new WeakMap,qe.create=(r,e)=>new qe({values:r,typeName:v.ZodNativeEnum,...k(e)});class Ee extends E{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.promise&&t.common.async===!1)return h(t,{code:f.invalid_type,expected:m.promise,received:t.parsedType}),b;const n=t.parsedType===m.promise?t.data:Promise.resolve(t.data);return Z(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ee.create=(r,e)=>new Ee({type:r,typeName:v.ZodPromise,...k(e)});class q extends E{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{h(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async c=>{if(t.value==="aborted")return b;const l=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return l.status==="aborted"?b:l.status==="dirty"||t.value==="dirty"?ve(l.value):l});{if(t.value==="aborted")return b;const c=this._def.schema._parseSync({data:o,path:n.path,parent:n});return c.status==="aborted"?b:c.status==="dirty"||t.value==="dirty"?ve(c.value):c}}if(s.type==="refinement"){const o=c=>{const l=s.refinement(c,i);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"?b:(c.status==="dirty"&&t.dirty(),o(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?b:(c.status==="dirty"&&t.dirty(),o(c.value).then(()=>({status:t.value,value:c.value}))))}if(s.type==="transform")if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!je(o))return o;const c=s.transform(o.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>je(o)?Promise.resolve(s.transform(o.value,i)).then(c=>({status:t.value,value:c})):o);C.assertNever(s)}}q.create=(r,e,t)=>new q({schema:r,typeName:v.ZodEffects,effect:e,...k(t)}),q.createWithPreprocess=(r,e,t)=>new q({schema:e,effect:{type:"preprocess",transform:r},typeName:v.ZodEffects,...k(t)});class J extends E{_parse(e){return this._getType(e)===m.undefined?Z(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}J.create=(r,e)=>new J({innerType:r,typeName:v.ZodOptional,...k(e)});class ue extends E{_parse(e){return this._getType(e)===m.null?Z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ue.create=(r,e)=>new ue({innerType:r,typeName:v.ZodNullable,...k(e)});class He extends E{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===m.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}He.create=(r,e)=>new He({innerType:r,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...k(e)});class Ye extends E{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ne(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new V(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new V(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Ye.create=(r,e)=>new Ye({innerType:r,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...k(e)});class dt extends E{_parse(e){if(this._getType(e)!==m.nan){const n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.nan,received:n.parsedType}),b}return{status:"valid",value:e.data}}}dt.create=r=>new dt({typeName:v.ZodNaN,...k(r)});const Nn=Symbol("zod_brand");class At extends E{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class We extends E{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?b:i.status==="dirty"?(t.dirty(),ve(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?b:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new We({in:e,out:t,typeName:v.ZodPipeline})}}class Ge extends E{_parse(e){const t=this._def.innerType._parse(e),n=s=>(je(s)&&(s.value=Object.freeze(s.value)),s);return Ne(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}}Ge.create=(r,e)=>new Ge({innerType:r,typeName:v.ZodReadonly,...k(e)});function cr(r,e={},t){return r?be.create().superRefine((n,s)=>{var i,o;if(!r(n)){const c=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,l=(o=(i=c.fatal)!==null&&i!==void 0?i:t)!==null&&o!==void 0?o:!0,u=typeof c=="string"?{message:c}:c;s.addIssue({code:"custom",...u,fatal:l})}}):be.create()}const Mn={object:R.lazycreate};var v;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(v||(v={}));const Ln=(r,e={message:`Input not instance of ${r.name}`})=>cr(t=>t instanceof r,e),ur=z.create,lr=oe.create,Dn=dt.create,$n=ae.create,dr=De.create,Zn=pe.create,Un=at.create,Fn=$e.create,Vn=Ze.create,zn=be.create,Bn=me.create,qn=te.create,Hn=ct.create,Yn=B.create,Wn=R.create,Gn=R.strictCreate,Kn=Ue.create,Jn=ut.create,Xn=Fe.create,Qn=K.create,es=Ve.create,ts=lt.create,rs=ye.create,ns=ke.create,ss=ze.create,is=Be.create,os=ce.create,as=qe.create,cs=Ee.create,fr=q.create,us=J.create,ls=ue.create,ds=q.createWithPreprocess,fs=We.create;var a=Object.freeze({__proto__:null,defaultErrorMap:_e,setErrorMap:gn,getErrorMap:st,makeIssue:it,EMPTY_PATH:_n,addIssueToContext:h,ParseStatus:M,INVALID:b,DIRTY:ve,OK:Z,isAborted:Ot,isDirty:Rt,isValid:je,isAsync:Ne,get util(){return C},get objectUtil(){return Tt},ZodParsedType:m,getParsedType:ie,ZodType:E,datetimeRegex:or,ZodString:z,ZodNumber:oe,ZodBigInt:ae,ZodBoolean:De,ZodDate:pe,ZodSymbol:at,ZodUndefined:$e,ZodNull:Ze,ZodAny:be,ZodUnknown:me,ZodNever:te,ZodVoid:ct,ZodArray:B,ZodObject:R,ZodUnion:Ue,ZodDiscriminatedUnion:ut,ZodIntersection:Fe,ZodTuple:K,ZodRecord:Ve,ZodMap:lt,ZodSet:ye,ZodFunction:ke,ZodLazy:ze,ZodLiteral:Be,ZodEnum:ce,ZodNativeEnum:qe,ZodPromise:Ee,ZodEffects:q,ZodTransformer:q,ZodOptional:J,ZodNullable:ue,ZodDefault:He,ZodCatch:Ye,ZodNaN:dt,BRAND:Nn,ZodBranded:At,ZodPipeline:We,ZodReadonly:Ge,custom:cr,Schema:E,ZodSchema:E,late:Mn,get ZodFirstPartyTypeKind(){return v},coerce:{string:r=>z.create({...r,coerce:!0}),number:r=>oe.create({...r,coerce:!0}),boolean:r=>De.create({...r,coerce:!0}),bigint:r=>ae.create({...r,coerce:!0}),date:r=>pe.create({...r,coerce:!0})},any:zn,array:Yn,bigint:$n,boolean:dr,date:Zn,discriminatedUnion:Jn,effect:fr,enum:os,function:ns,instanceof:Ln,intersection:Xn,lazy:ss,literal:is,map:ts,nan:Dn,nativeEnum:as,never:qn,null:Vn,nullable:ls,number:lr,object:Wn,oboolean:()=>dr().optional(),onumber:()=>lr().optional(),optional:us,ostring:()=>ur().optional(),pipeline:fs,preprocess:ds,promise:cs,record:es,set:rs,strictObject:Gn,string:ur,symbol:Un,transformer:fr,tuple:Qn,undefined:Fn,union:Kn,unknown:Bn,void:Hn,NEVER:b,ZodIssueCode:f,quotelessJson:yn,ZodError:V});const hs=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()}),ps=a.array(hs),ms=a.object({code:a.string(),message:a.string(),path:a.array(a.string())}),ys=a.array(ms),gs={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},jt=r=>{const e=r.toLowerCase().trim();return gs[e]??r},_s=r=>{try{return typeof JSON.parse(r)=="object"}catch{return!1}},vs=r=>r.length===1?jt(r[0].msg):`Please fix the following errors:
2
+ ${r.map(t=>`• ${jt(t.msg)}`).join(`
3
+ `)}`,bs=r=>`Encountered the following errors:
4
+ ${r.map(t=>`- ${t.path.join("/")}: ${t.message}`).join(`
5
+ `)}`,Ke=r=>{if(r instanceof Error)if(_s(r.message)){const e=JSON.parse(r.message);return ps.safeParse(e).success?vs(e):ys.safeParse(e).success?bs(e):(console.warn(`Encountered unknown stringified JSON object:
6
+ ${r.message}`),r.message)}else return jt(r.message);if(typeof r=="object")try{return JSON.stringify(r)}catch(e){return e+""}else return r+""},ws=(r,e,t)=>(...n)=>{try{return e(...n)}catch(s){t(`[form] Error running callback (${r}):`,s);return}},L=a.string().trim().min(1,{message:"Cannot be blank"}),D=a.string().trim().optional(),ft=r=>a.nullable(r.optional());var x=(r=>(r.FIRST_NAME="firstName",r.LAST_NAME="lastName",r.EMAIL="email",r.ZIP_CODE="zipCode",r.CITY="city",r.STATE="state",r.COUNTRY="country",r.ADDRESS="address",r.PHONE="phone",r.PROMOTION_CODE="promotionCode",r))(x||{});const hr=a.nativeEnum(x);var pr=(r=>(r.CARD_NUMBER="cardNumber",r.CARD_EXPIRY="cardExpiry",r.CARD_CVC="cardCvc",r))(pr||{});const mr=a.nativeEnum(pr),yr=a.union([hr,mr]);var Se=(r=>(r.CARD="card",r.CARD_NUMBER="card-number",r.CARD_EXPIRY="card-expiry",r.CARD_CVC="card-cvc",r))(Se||{});const ks=a.nativeEnum(Se),ht=a.object({provider:a.string(),processor_name:ft(a.string()),metadata:ft(a.record(a.string(),a.any()))}),Es=a.object({id:a.string()});a.object({cardNumber:D,expiry:D,cvc:D}),a.object({backgroundColor:D,color:D,fontFamily:D,fontSize:D,fontWeight:D,margin:D,padding:D,letterSpacing:D,lineHeight:D});const H=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"]),Ss=H.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),Cs=a.object({type:Ss}),xs=H.extract(["BLUR","FOCUS","CHANGE"]),Ts=a.object({type:xs,elementType:mr,errors:a.array(a.string()).optional()}),Os=H.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),Rs=a.object({type:Os,message:L,headers:a.record(a.string(),a.string()).optional()}),Ps=H.extract(["VALIDATION_ERROR"]),Is=a.object({type:Ps,elementType:yr,errors:a.array(a.string())}),As=a.object({type:a.literal(H.enum.LAYOUT),height:L}),js=a.object({type:a.literal(H.enum.LOADED),sessionId:L,totalAmountAtoms:a.number(),currency:D,checkoutPaymentMethods:a.array(ht)}),Ns=a.object({type:a.literal(H.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:a.record(a.string(),a.any()),paymentFlowMetadata:a.any().optional(),startPFMetadata:a.optional(a.record(a.string(),a.any()))}),Ms=a.object({type:a.literal(H.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:a.string()}),Je=a.object({firstName:L,lastName:L,email:L,zipCode:L,country:L,promotionCode:D}),Ls=a.object({email:L,zipCode:L,country:L,promotionCode:D}),Ds=H.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),$s=a.object({type:Ds,sessionId:L,checkoutPaymentMethod:ht,paymentFlowMetadata:a.any().optional(),doNotUseLegacyCCFlow:a.boolean().optional(),existingCCPMId:D}).extend(Je.shape),Zs=a.object({type:a.literal(H.enum.TOKENIZE_SUCCESS),isReadyForCheckout:a.boolean()}),Us=a.object({type:a.literal(H.enum.CHECKOUT_SUCCESS),invoiceUrls:a.array(a.string()),subscriptionIds:a.array(a.string()),customerId:a.string()}),Fs=a.discriminatedUnion("type",[Cs,Ts,Rs,Is,As,js,$s,Zs,Us,Ns,Ms]),Vs=a.object({payload:Fs,nonce:L,formId:L,elementId:L});a.object({amountAtom:a.number(),currency:L}),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:ft(a.string())});const zs=a.object({payment_methods:a.array(Es)}),Bs=a.object({elementType:a.string(),errors:a.array(a.string())});a.object({session_id:a.string()});const qs=a.object({success:a.literal(!1),error_type:a.literal("validation_error"),errors:a.array(Bs)}),Hs=a.discriminatedUnion("success",[a.object({success:a.literal(!0)}),qs]);a.object({session_id:a.string(),checkout_payment_method:ht,non_cde_form_fields:Je,do_not_use_legacy_cc_flow:a.boolean().optional(),existing_cc_pm_id:ft(a.string())}),a.object({session_id:a.string(),checkout_payment_method:ht,non_cde_form_fields:Je});var pt=(r=>(r.SUCCESS="success",r.FAILURE="failure",r.CANCELLED="cancelled",r))(pt||{});const Ys=a.object({status:a.enum(["success","failure","cancelled"])}),Ws=a.object({type:a.string(),redirect_url:a.string(),initial_intent_id:a.string(),consent_id:a.string()}),Gs=r=>{const e={};return Object.entries(r).forEach(([t,n])=>{try{const s=hr.parse(t);Array.isArray(n)?e[s]=n:Array.isArray(n._errors)&&(e[s]=n._errors)}catch{return}}),e},Ks=a.object({stripe_pk:a.string(),client_secret:a.string(),stripe_pm_id:a.string()}),Js=a.object({type:a.string(),client_secret:a.string(),stripe_pk:a.string()}),Xs={usd:"usd",brl:"brl"},mt=async r=>{for(let t=0;t<10;t++)gr()||await ti(500);if(!gr())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(r)},Qs=async(r,e)=>{const t=await mt(r);return{elements:t.elements(e),stripe:t}},ei=async(r,e,t,n,s)=>{const i=await mt(r),o=Xs[t.toLowerCase().trim()];return i.paymentRequest({country:"US",currency:o,total:{label:"Total",amount:e,pending:n},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},ti=r=>new Promise(e=>{setTimeout(e,r)}),gr=()=>"Stripe"in window,ri=async r=>new Promise((e,t)=>{try{r.on("paymentmethod",async n=>{e(n)}),r.on("cancel",()=>{t(new Error("Payment cancelled, please click Submit again to pay"))})}catch(n){t(n)}}),ni=async(r,e)=>{if(!r.stripe_pk||!r.client_secret)throw new Error(`Invalid next action metadata format: ${JSON.stringify(r)}`);const n=await(await mt(r.stripe_pk)).confirmCardSetup(r.client_secret,{payment_method:e.paymentMethod.id});if(n.error)throw e.complete("fail"),new Error(`Payment failed: ${n.error.message??"unknown"}`);return e.complete("success"),n},si=async r=>{var s,i,o,c;const t=await(await mt(r.stripe_pk)).confirmCardSetup(r.client_secret,{payment_method:r.stripe_pm_id}),n=(s=t.setupIntent)==null?void 0:s.status;if(n==="succeeded")console.log("[3DS] CONFIRMING PM:",r.stripe_pm_id),console.log("[3DS] Setup intent created:",t.setupIntent);else throw n==="canceled"?new Error("Payment cancelled, please click Submit again to pay"):new Error(`${((i=t.error)==null?void 0:i.message)??((c=(o=t.setupIntent)==null?void 0:o.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},ii=r=>JSON.stringify(r),Nt=(r,e)=>Array.from(r.querySelectorAll("[data-opid]")??[]).reduce((s,i)=>{const o=i.getAttribute("data-opid");return o?{...s,[o]:i.value}:s},{}),oi=r=>{try{return Vs.parse(r)}catch(e){throw console.error("Error parsing event payload:",r,e),e}};var X;(function(r){r.Call="call",r.Reply="reply",r.Syn="syn",r.SynAck="synAck",r.Ack="ack"})(X||(X={}));var ge;(function(r){r.Fulfilled="fulfilled",r.Rejected="rejected"})(ge||(ge={}));var Xe;(function(r){r.ConnectionDestroyed="ConnectionDestroyed",r.ConnectionTimeout="ConnectionTimeout",r.NoIframeSrc="NoIframeSrc"})(Xe||(Xe={}));var Mt;(function(r){r.DataCloneError="DataCloneError"})(Mt||(Mt={}));var le;(function(r){r.Message="message"})(le||(le={}));const ai=(r,e)=>{const t=[];let n=!1;return{destroy(s){n||(n=!0,e(`${r}: Destroying connection`),t.forEach(i=>{i(s)}))},onDestroy(s){n?s():t.push(s)}}},ci=r=>(...e)=>{r&&console.log("[Penpal]",...e)},ui={"http:":"80","https:":"443"},li=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,di=["file:","data:"],fi=r=>{if(r&&di.find(c=>r.startsWith(c)))return"null";const e=document.location,t=li.exec(r);let n,s,i;t?(n=t[1]?t[1]:e.protocol,s=t[2],i=t[4]):(n=e.protocol,s=e.hostname,i=e.port);const o=i&&i!==ui[n]?`:${i}`:"";return`${n}//${s}${o}`},_r=({name:r,message:e,stack:t})=>({name:r,message:e,stack:t}),hi=r=>{const e=new Error;return Object.keys(r).forEach(t=>e[t]=r[t]),e},pi=(r,e,t)=>{const{localName:n,local:s,remote:i,originForSending:o,originForReceiving:c}=r;let l=!1;const u=d=>{if(d.source!==i||d.data.penpal!==X.Call)return;if(c!=="*"&&d.origin!==c){t(`${n} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const y=d.data,{methodName:w,args:p,id:_}=y;t(`${n}: Received ${w}() call`);const S=O=>F=>{if(t(`${n}: Sending ${w}() reply`),l){t(`${n}: Unable to send ${w}() reply due to destroyed connection`);return}const $={penpal:X.Reply,id:_,resolution:O,returnValue:F};O===ge.Rejected&&F instanceof Error&&($.returnValue=_r(F),$.returnValueIsError=!0);try{i.postMessage($,o)}catch(A){if(A.name===Mt.DataCloneError){const Pe={penpal:X.Reply,id:_,resolution:ge.Rejected,returnValue:_r(A),returnValueIsError:!0};i.postMessage(Pe,o)}throw A}};new Promise(O=>O(e[w].apply(e,p))).then(S(ge.Fulfilled),S(ge.Rejected))};return s.addEventListener(le.Message,u),()=>{l=!0,s.removeEventListener(le.Message,u)}};let mi=0;const yi=()=>++mi,vr=".",br=r=>r?r.split(vr):[],gi=r=>r.join(vr),_i=(r,e)=>{const t=br(e||"");return t.push(r),gi(t)},vi=(r,e,t)=>{const n=br(e);return n.reduce((s,i,o)=>(typeof s[i]>"u"&&(s[i]={}),o===n.length-1&&(s[i]=t),s[i]),r),r},wr=(r,e)=>{const t={};return Object.keys(r).forEach(n=>{const s=r[n],i=_i(n,e);typeof s=="object"&&Object.assign(t,wr(s,i)),typeof s=="function"&&(t[i]=s)}),t},bi=r=>{const e={};for(const t in r)vi(e,t,r[t]);return e},wi=(r,e,t,n,s)=>{const{localName:i,local:o,remote:c,originForSending:l,originForReceiving:u}=e;let d=!1;s(`${i}: Connecting call sender`);const y=p=>(..._)=>{s(`${i}: Sending ${p}() call`);let S;try{c.closed&&(S=!0)}catch{S=!0}if(S&&n(),d){const O=new Error(`Unable to send ${p}() call due to destroyed connection`);throw O.code=Xe.ConnectionDestroyed,O}return new Promise((O,F)=>{const $=yi(),A=Ie=>{if(Ie.source!==c||Ie.data.penpal!==X.Reply||Ie.data.id!==$)return;if(u!=="*"&&Ie.origin!==u){s(`${i} received message from origin ${Ie.origin} which did not match expected origin ${u}`);return}const Qt=Ie.data;s(`${i}: Received ${p}() reply`),o.removeEventListener(le.Message,A);let er=Qt.returnValue;Qt.returnValueIsError&&(er=hi(er)),(Qt.resolution===ge.Fulfilled?O:F)(er)};o.addEventListener(le.Message,A);const Pe={penpal:X.Call,id:$,methodName:p,args:_};c.postMessage(Pe,l)})},w=t.reduce((p,_)=>(p[_]=y(_),p),{});return Object.assign(r,bi(w)),()=>{d=!0}},ki=(r,e,t,n,s)=>{const{destroy:i,onDestroy:o}=n;let c,l;const u={};return d=>{if(e!=="*"&&d.origin!==e){s(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}s("Parent: Handshake - Received ACK");const y={localName:"Parent",local:window,remote:d.source,originForSending:t,originForReceiving:e};c&&c(),c=pi(y,r,s),o(c),l&&l.forEach(p=>{delete u[p]}),l=d.data.methodNames;const w=wi(u,y,l,i,s);return o(w),u}},Ei=(r,e,t,n)=>s=>{if(!s.source)return;if(t!=="*"&&s.origin!==t){r(`Parent: Handshake - Received SYN message from origin ${s.origin} which did not match expected origin ${t}`);return}r("Parent: Handshake - Received SYN, responding with SYN-ACK");const i={penpal:X.SynAck,methodNames:Object.keys(e)};s.source.postMessage(i,n)},Si=6e4,Ci=(r,e)=>{const{destroy:t,onDestroy:n}=e,s=setInterval(()=>{r.isConnected||(clearInterval(s),t())},Si);n(()=>{clearInterval(s)})},xi=(r,e)=>{let t;return r!==void 0&&(t=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${r}ms`);n.code=Xe.ConnectionTimeout,e(n)},r)),()=>{clearTimeout(t)}},Ti=r=>{if(!r.src&&!r.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=Xe.NoIframeSrc,e}},kr=r=>{let{iframe:e,methods:t={},childOrigin:n,timeout:s,debug:i=!1}=r;const o=ci(i),c=ai("Parent",o),{onDestroy:l,destroy:u}=c;n||(Ti(e),n=fi(e.src));const d=n==="null"?"*":n,y=wr(t),w=Ei(o,y,n,d),p=ki(y,n,d,c,o);return{promise:new Promise((S,O)=>{const F=xi(s,u),$=A=>{if(!(A.source!==e.contentWindow||!A.data)){if(A.data.penpal===X.Syn){w(A);return}if(A.data.penpal===X.Ack){const Pe=p(A);Pe&&(F(),S(Pe));return}}};window.addEventListener(le.Message,$),o("Parent: Awaiting handshake"),Ci(e,c),l(A=>{window.removeEventListener(le.Message,$),A&&O(A)})}),destroy(){u()}}},Oi=async r=>{if(typeof r!="object"||!r)return!1;try{const e={type:"ping"},t=await r.send(e);if(t!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(t)}`);return!0}catch(e){return console.error("Invalid CDE connection check:",e),!1}},Ri=(r,e)=>!!r&&e,P=r=>a.nullable(r.optional());a.string().trim().min(1,{message:"Cannot be blank"});const Pi=a.object({cde_response_type:a.literal("error"),message:a.string(),headers:a.record(a.string(),a.string()).optional()});a.enum(["usd","brl"]);const Er=a.object({name:a.string(),amount_atom_off:P(a.number()),percent_off:P(a.number()),currency:P(a.string()),duration:a.string(),duration_in_months:P(a.number())}),Sr=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()}),Ii=a.record(a.string(),a.any()),Ai=a.object({name:a.string(),settings:P(Ii)}),Qe=a.object({provider:a.string(),processor_name:P(a.string()),metadata:P(a.record(a.string(),a.any()))}),ji=a.object({quantity:a.number()}),Ni=a.object({id:P(a.string()),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),subscription_items:a.array(ji),trial_start:P(a.string()),trial_end:P(a.string())}),Cr=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(Cr),subscription_item_id:a.string()}),Li=a.object({coupon:Er}),Di=a.object({currency:a.string(),discounts:a.array(Li),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(Cr)}),xr=a.object({created:a.array(Ni),invoices:a.array(Di)}),Tr=a.object({preview:xr,preview_post_trial:P(xr),coupons:a.array(Er)}),Or=a.object({status:a.literal("open"),token:a.string(),email:P(a.string()),line_items:a.array(Sr),amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),brand:Ai,subs_preview:P(Tr),methods_available:a.array(Qe)}),Rr=a.discriminatedUnion("mode",[a.object({mode:a.literal("setup"),currency:a.nullable(a.undefined())}).extend(Or.shape),a.object({mode:a.enum(["payment","subscription"]),currency:a.string()}).extend(Or.shape)]),$i=a.object({status:a.literal("complete")}),Zi=a.object({status:a.literal("expired")});a.union([Rr,$i,Zi]),a.object({logo:a.string(),icon:a.string(),primary_color:a.string(),secondary_color:a.string()});const Pr=a.object({invoice_urls:a.array(a.string()),subscription_ids:a.array(a.string()),customer_id:a.string()});a.object({secure_token:a.string(),payment_input:a.any(),customer_email:a.string(),customer_zip_code:a.string(),customer_country:a.string(),line_items:a.array(Sr),total_amount_atom:a.number().int(),cancel_at_end:a.boolean(),checkout_payment_method:Qe,promotion_code:a.string().optional(),do_not_use_legacy_cc_flow:a.boolean().optional()});const Ui=a.object({payment_method_id:a.string()});a.object({id:a.string(),return_url:a.string()});const Fi=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()});a.array(Fi),a.object({new_customer_email:a.string().optional(),new_customer_address:a.record(a.string(),a.any()).optional(),payment_provider:a.string(),checkout_payment_method:Qe,existing_cc_pm_id:a.string().optional(),their_existing_pm_id:a.string().optional()});const Ir=a.object({required_user_actions:a.array(a.record(a.string(),a.any()))});a.object({fields:Ls,checkoutPaymentMethod:Qe}),a.object({session_id:a.string(),non_cde_form_fields:Je,checkout_payment_method:Qe});const Vi=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),cc_pm_id:a.string()});a.record(a.any());const zi=r=>r.reduce((e,t)=>e+t,0);function Bi(r,e){var t=Object.setPrototypeOf;t?t(r,e):r.__proto__=e}function qi(r,e){e===void 0&&(e=r.constructor);var t=Error.captureStackTrace;t&&t(r,e)}var Hi=function(){var r=function(t,n){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,i){s.__proto__=i}||function(s,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(s[o]=i[o])},r(t,n)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Yi=function(r){Hi(e,r);function e(t,n){var s=this.constructor,i=r.call(this,t,n)||this;return Object.defineProperty(i,"name",{value:s.name,enumerable:!1,configurable:!0}),Bi(i,s.prototype),qi(i),i}return e}(Error);class Ar extends Yi{constructor(e){const t=`${e.message}`;super(t),this.response=e}get originalErrorMessage(){return this.response.message}}const Y=async(r,e,t)=>{const n=await r.send(e);if(Gi(n))throw new Ar(n);if(!Wi(n,t)){const s=t.safeParse(n);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",t,"Actual:",n),s.error)}return n},Wi=(r,e)=>e.safeParse(r).success,Gi=r=>Pi.safeParse(r).success,Ki=async(r,e)=>await Y(r,{type:"get_checkout_preview",payload:e},Tr),et=async r=>await Y(r,{type:"get_prefill",payload:{}},Rr),Ji=async(r,e)=>await Y(r,{type:"v2_start_payment_flow",payload:e},Ir),Xi=async(r,e)=>await Y(r,{type:"start_payment_flow_for_cc",payload:e},Vi),Qi=async(r,e)=>await Y(r,{type:"start_payment_flow_for_pr",payload:e},Ir),Lt=async(r,e)=>await Y(r,{type:"confirm_payment_flow",payload:e},zs),eo=async(r,e,t)=>{const n=await Ki(r,{secure_token:e,promotion_code:t}),s=new Set(n.preview.invoices.map(c=>c.currency));if(s.size!==1)throw new Error(`Expected exactly one currency, got ${s.size}`);const i=s.values().next().value??"usd",o=zi(n.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:i,amountAtom:o}},jr=async(r,e,t,n)=>{if(t)return{amountAtom:0,currency:"usd"};{n=n||void 0;const s=await eo(r,e,n);return{amountAtom:s.amountAtom,currency:s.currency}}},to=async(r,e)=>{if(r.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(r.values()).map(n=>Y(n,{type:"tokenize_card",payload:e},Hs)))},Nr=async(r,e)=>{try{return await Y(r,{type:"checkout_card_elements",payload:e},Pr)}catch(t){throw console.error("[cde-client] Error during checkoutCardElements:",t,JSON.stringify(t)),t}},ro=async(r,e)=>await Y(r,{type:"setup_payment_method",payload:e},Ui),Mr=async(r,e)=>await Y(r,{type:"checkout",payload:e},Pr),Lr=1e3,no=async(r,e)=>{console.log(e);const n=await kr({iframe:r,debug:!0,timeout:Lr,childOrigin:"*"}).promise;return(await Y(n,{type:"ping-3ds-status"},Ys)).status};function so(r){throw new Error(`Unhandled case: ${r}`)}const Dt=10,Dr=(r=0)=>e=>`\x1B[${e+r}m`,$r=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,Zr=(r=0)=>(e,t,n)=>`\x1B[${38+r};2;${e};${t};${n}m`,T={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(T.modifier);const io=Object.keys(T.color),oo=Object.keys(T.bgColor);[...io,...oo];function ao(){const r=new Map;for(const[e,t]of Object.entries(T)){for(const[n,s]of Object.entries(t))T[n]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},t[n]=T[n],r.set(s[0],s[1]);Object.defineProperty(T,e,{value:t,enumerable:!1})}return Object.defineProperty(T,"codes",{value:r,enumerable:!1}),T.color.close="\x1B[39m",T.bgColor.close="\x1B[49m",T.color.ansi=Dr(),T.color.ansi256=$r(),T.color.ansi16m=Zr(),T.bgColor.ansi=Dr(Dt),T.bgColor.ansi256=$r(Dt),T.bgColor.ansi16m=Zr(Dt),Object.defineProperties(T,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(i=>i+i).join(""));const s=Number.parseInt(n,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:e=>T.rgbToAnsi256(...T.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,s;if(e>=232)t=((e-232)*10+8)/255,n=t,s=t;else{e-=16;const c=e%36;t=Math.floor(e/36)/5,n=Math.floor(c/6)/5,s=c%6/5}const i=Math.max(t,n,s)*2;if(i===0)return 30;let o=30+(Math.round(s)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>T.ansi256ToAnsi(T.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>T.ansi256ToAnsi(T.hexToAnsi256(e)),enumerable:!1}}),T}const Q=ao(),yt=(()=>{if(navigator.userAgentData){const r=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(r&&r.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),Ur=yt!==0&&{level:yt,hasBasic:!0,has256:yt>=2,has16m:yt>=3},co={stdout:Ur,stderr:Ur};function uo(r,e,t){let n=r.indexOf(e);if(n===-1)return r;const s=e.length;let i=0,o="";do o+=r.slice(i,n)+e+t,i=n+s,n=r.indexOf(e,i);while(n!==-1);return o+=r.slice(i),o}function lo(r,e,t,n){let s=0,i="";do{const o=r[n-1]==="\r";i+=r.slice(s,o?n-1:n)+e+(o?`\r
7
7
  `:`
8
- `)+t,s=r+1,r=n.indexOf(`
9
- `,s)}while(r!==-1);return o+=n.slice(s),o}const{stdout:jn,stderr:Mn}=Yo,It=Symbol("GENERATOR"),ve=Symbol("STYLER"),Ye=Symbol("IS_EMPTY"),Ln=["ansi","ansi","ansi256","ansi16m"],be=Object.create(null),Jo=(n,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const t=jn?jn.level:0;n.level=e.level===void 0?t:e.level},Qo=n=>{const e=(...t)=>t.join(" ");return Jo(e,n),Object.setPrototypeOf(e,Ke.prototype),e};function Ke(n){return Qo(n)}Object.setPrototypeOf(Ke.prototype,Function.prototype);for(const[n,e]of Object.entries(K))be[n]={get(){const t=ft(this,Nt(e.open,e.close,this[ve]),this[Ye]);return Object.defineProperty(this,n,{value:t}),t}};be.visible={get(){const n=ft(this,this[ve],!0);return Object.defineProperty(this,"visible",{value:n}),n}};const At=(n,e,t,...r)=>n==="rgb"?e==="ansi16m"?K[t].ansi16m(...r):e==="ansi256"?K[t].ansi256(K.rgbToAnsi256(...r)):K[t].ansi(K.rgbToAnsi(...r)):n==="hex"?At("rgb",e,t,...K.hexToRgb(...r)):K[t][n](...r),Xo=["rgb","hex","ansi256"];for(const n of Xo){be[n]={get(){const{level:t}=this;return function(...r){const s=Nt(At(n,Ln[t],"color",...r),K.color.close,this[ve]);return ft(this,s,this[Ye])}}};const e="bg"+n[0].toUpperCase()+n.slice(1);be[e]={get(){const{level:t}=this;return function(...r){const s=Nt(At(n,Ln[t],"bgColor",...r),K.bgColor.close,this[ve]);return ft(this,s,this[Ye])}}}}const ei=Object.defineProperties(()=>{},{...be,level:{enumerable:!0,get(){return this[It].level},set(n){this[It].level=n}}}),Nt=(n,e,t)=>{let r,s;return t===void 0?(r=n,s=e):(r=t.openAll+n,s=e+t.closeAll),{open:n,close:e,openAll:r,closeAll:s,parent:t}},ft=(n,e,t)=>{const r=(...s)=>ti(r,s.length===1?""+s[0]:s.join(" "));return Object.setPrototypeOf(r,ei),r[It]=n,r[ve]=e,r[Ye]=t,r},ti=(n,e)=>{if(n.level<=0||!e)return n[Ye]?"":e;let t=n[ve];if(t===void 0)return e;const{openAll:r,closeAll:s}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Ko(e,t.close,t.open),t=t.parent;const o=e.indexOf(`
10
- `);return o!==-1&&(e=Go(e,s,r,o)),r+e+s};Object.defineProperties(Ke.prototype,be);const ht=Ke();Ke({level:Mn?Mn.level:0});const jt=n=>async e=>{try{e.flowCallbacks.onCheckoutStarted();const t=await n(e);if(t.mode==="setup")e.flowCallbacks.onSetupPaymentMethodSuccess(t.result.payment_method_id);else if(t.mode==="checkout")e.flowCallbacks.onCheckoutSuccess(t.result.invoice_urls,t.result.subscription_ids,t.result.customer_id);else throw new Error(`Unhandled mode: ${t}`)}catch(t){throw e.flowCallbacks.onCheckoutError(nn(t)),t}},Dn=n=>async e=>{try{return await n(e)}catch(t){const{err__:r}=ie("init-error-catcher");return r(t),{isAvailable:!1,reason:nn(t)}}},ie=n=>{const e=(...r)=>{window.console.log(`${ht.green.bold("ojs/")}${ht.bold.gray(`${n}`)} `,...r)},t=(...r)=>{window.console.error(`${ht.red.bold("ojs/")}${ht.bold.gray(`${n}`)} `,...r)};return{log:e,err:t,log__:e,err__:t}},{log__:Yi,err__:ni}=ie("common"),Mt=n=>{if(n.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${n.payment_methods.length}`);return{payment_method_id:n.payment_methods[0].id}},$n=(n,e)=>{const t=n.find(r=>e.safeParse(r).success);if(!t)throw ni("No CPMs found for model. All models:",n),new Error("No CPMs found for model");return e.parse(t)},{log__:ri,err__:Zn}=ie("common-cc"),Lt=(n,e)=>{const t=Be.safeParse(n);if(!t.success){const r=t.error.format(),s=Rs(r);for(const[o,a]of Object.entries(s))e(o,a,o);throw Zn("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return t.data},si=(n,e)=>{for(const t of n)if(t.success===!1)throw t.errors.forEach(r=>{const s=an.safeParse(r.elementType);if(!s.success)Zn(`Unknown field name in onValidationError: ${r.elementType}`);else{const o=s.data;e(o,r.errors)}}),ri(`Error tokenizing card: got validation errors: ${JSON.stringify(t.errors)}`),new Error("Got validation errors while tokenizing card")},Fn="ojs-stripe-link-btn",{log__:I,err__:oi}=ie("stripe-link"),ii=i.object({provider:i.literal("stripe_link"),processor_name:i.literal("stripe"),metadata:i.object({stripe_pk:i.string()})}),ai=i.array(i.object({our_existing_pm_id:i.string()})).length(1),ci=Dn(async({context:n,flowCallbacks:e})=>{const t=n.customInitParams.stripeLink;I("Checking if there are any CPMs for Stripe PR...");const r=$n(n.checkoutPaymentMethods,ii);I("Starting stripe link flow...");const s=Array.from(n.cdeConnections.values())[0],o=await We(s),a=o.mode==="setup";I("Creating stripe elements...");const c=await Sn(s,o.token,a,void 0),{elements:d,stripe:l}=await Ns(r.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});I("Creating express checkout...");const u=d.create("expressCheckout",{buttonHeight:t==null?void 0:t.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),v=()=>{u.mount(`#${Fn}`)},E=()=>{u.unmount()};return t!=null&&t.doNotMountOnInit?I("NOT mounting stripe link button (doNotMountOnInit is true)"):(I("Mounting stripe link button..."),v()),u.on("click",async w=>{if(I("Stripe Link button clicked"),t!=null&&t.overrideLinkSubmit&&!await t.overrideLinkSubmit()){I("Stripe Link submit aborted by overrideLinkSubmit");return}w.resolve()}),u.on("confirm",async w=>{I("Stripe Link window confirmed",w);const x=await l.createPaymentMethod({elements:d,params:{billing_details:w.billingDetails}});x.error?(oi("error",x.error),e.onCheckoutError(x.error.message??"Stripe Link unknown error")):(I("paymentMethod",x.paymentMethod),we.stripeLink.run({context:n,checkoutPaymentMethod:r,nonCdeFormInputs:Tt(n.formDiv),flowCallbacks:e,customParams:{stripePM:x.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:v,dismountButton:E,waitForButtonToMount:async()=>await ui(Fn)}}}),li=jt(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,flowCallbacks:r,customParams:s})=>{I("Running Stripe PR flow...");const o=Array.from(n.cdeConnections.values())[0];I("Merging PM fields with form fields...");const a=di(t,s.stripePM),c=Lt(a,r.onValidationError);I("Starting payment flow...");const d=await $o(o,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:s.stripePM.id});I("Start payment flow response",d);const u=ai.parse(d.required_user_actions)[0].our_existing_pm_id,v=await We(o);if(v.mode==="setup"){I("Doing payment setup...");const E=await Rt(o,{secure_token:v.token,existing_cc_pm_id:u});return{mode:"setup",result:Mt(E)}}else{I("Doing checkout...");const E={secure_token:v.token,payment_input:{provider_type:e.provider},customer_email:c[C.EMAIL],customer_zip_code:c[C.ZIP_CODE],customer_country:c[C.COUNTRY],promotion_code:c[C.PROMOTION_CODE],line_items:v.line_items,total_amount_atom:v.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await On(o,E)}}}),di=(n,e)=>{var a,c,d,l,u;const t={...n},[r,...s]=((c=(a=e.billing_details.name)==null?void 0:a.trim())==null?void 0:c.split(/\s+/))??[],o=s.join(" ")||void 0;return t[C.FIRST_NAME]=t[C.FIRST_NAME]||r||"_OP_UNKNOWN",t[C.LAST_NAME]=t[C.LAST_NAME]||o||"_OP_UNKNOWN",t[C.EMAIL]=t[C.EMAIL]||((d=e.link)==null?void 0:d.email)||e.billing_details.email||"op_unfilled@getopenpay.com",t[C.ZIP_CODE]=t[C.ZIP_CODE]||((l=e.billing_details.address)==null?void 0:l.postal_code)||"00000",t[C.COUNTRY]=t[C.COUNTRY]||((u=e.billing_details.address)==null?void 0:u.country)||"US",I("Final form inputs:",t),t},ui=n=>new Promise(e=>{const t=()=>{const r=document.getElementById(n);r?e(r):requestAnimationFrame(t)};t()}),fi="@keyframes fadeIn{0%{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}.overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483648!important;display:flex;justify-content:center;align-items:center;background-color:#00000080}.container{max-width:500px;max-height:600px;width:100%;height:100%;background-color:#fff;position:relative;animation:fadeIn .3s ease-out}.frame{max-width:500px;max-height:600px;width:100%;height:100%;border:none}.cancel-button{position:absolute;background:transparent;border:none;font-size:1rem;color:#fff;cursor:pointer;top:-1.5rem;padding:0;right:0}",hi=n=>{const e=document.createElement("template");e.innerHTML=`
8
+ `)+t,s=n+1,n=r.indexOf(`
9
+ `,s)}while(n!==-1);return i+=r.slice(s),i}const{stdout:Fr,stderr:Vr}=co,$t=Symbol("GENERATOR"),Ce=Symbol("STYLER"),tt=Symbol("IS_EMPTY"),zr=["ansi","ansi","ansi256","ansi16m"],xe=Object.create(null),fo=(r,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const t=Fr?Fr.level:0;r.level=e.level===void 0?t:e.level},ho=r=>{const e=(...t)=>t.join(" ");return fo(e,r),Object.setPrototypeOf(e,rt.prototype),e};function rt(r){return ho(r)}Object.setPrototypeOf(rt.prototype,Function.prototype);for(const[r,e]of Object.entries(Q))xe[r]={get(){const t=gt(this,Ut(e.open,e.close,this[Ce]),this[tt]);return Object.defineProperty(this,r,{value:t}),t}};xe.visible={get(){const r=gt(this,this[Ce],!0);return Object.defineProperty(this,"visible",{value:r}),r}};const Zt=(r,e,t,...n)=>r==="rgb"?e==="ansi16m"?Q[t].ansi16m(...n):e==="ansi256"?Q[t].ansi256(Q.rgbToAnsi256(...n)):Q[t].ansi(Q.rgbToAnsi(...n)):r==="hex"?Zt("rgb",e,t,...Q.hexToRgb(...n)):Q[t][r](...n),po=["rgb","hex","ansi256"];for(const r of po){xe[r]={get(){const{level:t}=this;return function(...n){const s=Ut(Zt(r,zr[t],"color",...n),Q.color.close,this[Ce]);return gt(this,s,this[tt])}}};const e="bg"+r[0].toUpperCase()+r.slice(1);xe[e]={get(){const{level:t}=this;return function(...n){const s=Ut(Zt(r,zr[t],"bgColor",...n),Q.bgColor.close,this[Ce]);return gt(this,s,this[tt])}}}}const mo=Object.defineProperties(()=>{},{...xe,level:{enumerable:!0,get(){return this[$t].level},set(r){this[$t].level=r}}}),Ut=(r,e,t)=>{let n,s;return t===void 0?(n=r,s=e):(n=t.openAll+r,s=e+t.closeAll),{open:r,close:e,openAll:n,closeAll:s,parent:t}},gt=(r,e,t)=>{const n=(...s)=>yo(n,s.length===1?""+s[0]:s.join(" "));return Object.setPrototypeOf(n,mo),n[$t]=r,n[Ce]=e,n[tt]=t,n},yo=(r,e)=>{if(r.level<=0||!e)return r[tt]?"":e;let t=r[Ce];if(t===void 0)return e;const{openAll:n,closeAll:s}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=uo(e,t.close,t.open),t=t.parent;const i=e.indexOf(`
10
+ `);return i!==-1&&(e=lo(e,s,n,i)),n+e+s};Object.defineProperties(rt.prototype,xe);const _t=rt();rt({level:Vr?Vr.level:0});const Ft=r=>async e=>{var t,n,s,i,o,c,l,u;try{(n=(t=e.formCallbacks.get).onCheckoutStarted)==null||n.call(t);const d=await r(e);if(d.mode==="setup")(i=(s=e.formCallbacks.get).onSetupPaymentMethodSuccess)==null||i.call(s,d.result.payment_method_id);else if(d.mode==="checkout")(c=(o=e.formCallbacks.get).onCheckoutSuccess)==null||c.call(o,d.result.invoice_urls,d.result.subscription_ids,d.result.customer_id);else throw new Error(`Unhandled mode: ${d}`)}catch(d){throw(u=(l=e.formCallbacks.get).onCheckoutError)==null||u.call(l,Ke(d)),d}},Br=r=>async e=>{try{return await r(e)}catch(t){const{err__:n}=ee("init-error-catcher");return n(t),{isAvailable:!1,reason:Ke(t)}}},ee=r=>{const e=(...n)=>{window.console.log(`${_t.green.bold("ojs/")}${_t.bold.gray(`${r}`)} `,...n)},t=(...n)=>{window.console.error(`${_t.red.bold("ojs/")}${_t.bold.gray(`${r}`)} `,...n)};return{log:e,err:t,log__:e,err__:t}},{log__:Ja,err__:go}=ee("common"),Vt=r=>{if(r.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${r.payment_methods.length}`);return{payment_method_id:r.payment_methods[0].id}},qr=(r,e)=>{const t=r.find(n=>e.safeParse(n).success);if(!t)throw go("No CPMs found for model. All models:",r),new Error("No CPMs found for model");return e.parse(t)},{log__:_o,err__:Hr}=ee("common-cc"),zt=(r,e)=>{const t=Je.safeParse(r);if(!t.success){const n=t.error.format(),s=Gs(n);for(const[i,o]of Object.entries(s))e(i,o,i);throw Hr("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return t.data},vo=(r,e)=>{for(const t of r)if(t.success===!1)throw t.errors.forEach(n=>{const s=yr.safeParse(n.elementType);if(!s.success)Hr(`Unknown field name in onValidationError: ${n.elementType}. Error object:`,n);else{const i=s.data;e(i,n.errors)}}),_o(`Error tokenizing card: got validation errors: ${JSON.stringify(t.errors)}`),new Error("Got validation errors while tokenizing card")},Yr="ojs-stripe-link-btn",{log__:j,err__:bo}=ee("stripe-link"),wo=a.object({provider:a.literal("stripe_link"),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),ko=a.array(a.object({our_existing_pm_id:a.string()})).length(1),Eo=Br(async({context:r,formCallbacks:e})=>{const t=r.customInitParams.stripeLink;j("Checking if there are any CPMs for Stripe PR...");const n=qr(r.checkoutPaymentMethods,wo);j("Starting stripe link flow...");const s=r.anyCdeConnection,i=await et(s),o=i.mode==="setup";j("Creating stripe elements...");const c=await jr(s,i.token,o,void 0),{elements:l,stripe:u}=await Qs(n.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});j("Creating express checkout...");const d=l.create("expressCheckout",{buttonHeight:t==null?void 0:t.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),y=()=>{d.mount(`#${Yr}`)},w=()=>{d.unmount()};return t!=null&&t.doNotMountOnInit?j("NOT mounting stripe link button (doNotMountOnInit is true)"):(j("Mounting stripe link button..."),y()),d.on("click",async p=>{if(j("Stripe Link button clicked"),t!=null&&t.overrideLinkSubmit&&!await t.overrideLinkSubmit()){j("Stripe Link submit aborted by overrideLinkSubmit");return}p.resolve()}),d.on("confirm",async p=>{var S,O;j("Stripe Link window confirmed",p);const _=await u.createPaymentMethod({elements:l,params:{billing_details:p.billingDetails}});_.error?(bo("error",_.error),(O=(S=e.get).onCheckoutError)==null||O.call(S,_.error.message??"Stripe Link unknown error")):(j("paymentMethod",_.paymentMethod),Te.stripeLink.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:Nt(r.formDiv),formCallbacks:e,customParams:{stripePM:_.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:y,dismountButton:w,waitForButtonToMount:async()=>await xo(Yr)}}}),So=Ft(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{j("Running Stripe PR flow...");const i=r.anyCdeConnection;j("Merging PM fields with form fields...");const o=Co(t,s.stripePM),c=zt(o,n.get.onValidationError??(()=>{}));j("Starting payment flow...");const l=await Ji(i,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:s.stripePM.id});j("Start payment flow response",l);const d=ko.parse(l.required_user_actions)[0].our_existing_pm_id,y=await et(i);if(y.mode==="setup"){j("Doing payment setup...");const w=await Lt(i,{secure_token:y.token,existing_cc_pm_id:d});return{mode:"setup",result:Vt(w)}}else{j("Doing checkout...");const w={secure_token:y.token,payment_input:{provider_type:e.provider},customer_email:c[x.EMAIL],customer_zip_code:c[x.ZIP_CODE],customer_country:c[x.COUNTRY],promotion_code:c[x.PROMOTION_CODE],line_items:y.line_items,total_amount_atom:y.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Mr(i,w)}}}),Co=(r,e)=>{var o,c,l,u,d;const t={...r},[n,...s]=((c=(o=e.billing_details.name)==null?void 0:o.trim())==null?void 0:c.split(/\s+/))??[],i=s.join(" ")||void 0;return t[x.FIRST_NAME]=t[x.FIRST_NAME]||n||"_OP_UNKNOWN",t[x.LAST_NAME]=t[x.LAST_NAME]||i||"_OP_UNKNOWN",t[x.EMAIL]=t[x.EMAIL]||((l=e.link)==null?void 0:l.email)||e.billing_details.email||"op_unfilled@getopenpay.com",t[x.ZIP_CODE]=t[x.ZIP_CODE]||((u=e.billing_details.address)==null?void 0:u.postal_code)||"00000",t[x.COUNTRY]=t[x.COUNTRY]||((d=e.billing_details.address)==null?void 0:d.country)||"US",j("Final form inputs:",t),t},xo=r=>new Promise(e=>{const t=()=>{const n=document.getElementById(r);n?e(n):requestAnimationFrame(t)};t()}),To="@keyframes fadeIn{0%{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}.overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483648!important;display:flex;justify-content:center;align-items:center;background-color:#00000080}.container{max-width:500px;max-height:600px;width:100%;height:100%;background-color:#fff;position:relative;animation:fadeIn .3s ease-out}.frame{max-width:500px;max-height:600px;width:100%;height:100%;border:none}.cancel-button{position:absolute;background:transparent;border:none;font-size:1rem;color:#fff;cursor:pointer;top:-1.5rem;padding:0;right:0}",Oo=r=>{const e=document.createElement("template");e.innerHTML=`
11
11
  <style>
12
- ${fi}
12
+ ${To}
13
13
  </style>
14
14
  <div class="overlay">
15
15
  <div class="container">
16
16
  <button class="cancel-button">Cancel</button>
17
- <iframe src="${n}" class="frame" id="three-ds-iframe" title="3D Secure verification" allow="payment"></iframe>
17
+ <iframe src="${r}" class="frame" id="three-ds-iframe" title="3D Secure verification" allow="payment"></iframe>
18
18
  </div>
19
19
  </div>
20
- `;const t=document.createElement("div"),r=t.attachShadow({mode:"open"});r.appendChild(e.content.cloneNode(!0));const s=r.querySelector("#three-ds-iframe"),o=r.querySelector(".cancel-button");return document.body.appendChild(t),{host:t,iframe:s,cancelButton:o}};function mi(n,e,t){const r=async()=>{try{console.log("🔄 Polling CDE connection...");const o=await Bo(n,t);o&&(console.log("🟢 CDE connection successful! Stopping polling..."),console.log("➡️ Got status:",o),clearInterval(s),e(o))}catch{}};r();const s=setInterval(r,Rn);return s}function pi({elements:n,pollingInterval:e,resolve:t}){const r=()=>{clearInterval(e),n.host.remove(),t(ct.CANCELLED)};return n.cancelButton.addEventListener("click",r),()=>{n.cancelButton.removeEventListener("click",r)}}async function yi({url:n,baseUrl:e}){const t=hi(n);return new Promise(r=>{const s=c=>{setTimeout(()=>{t.host.remove()},1e3),r(c),a==null||a()},o=mi(t.iframe,s,new URL(e).origin),a=pi({elements:t,pollingInterval:o,resolve:r})})}const{log__:R,err__:Un}=ie("common-cc"),{log__:Vn}=ie("stripe-cc"),gi=jt(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,flowCallbacks:r})=>{var l;R("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=Array.from(n.cdeConnections.values())[0],o=await We(s);R(`├ Validating non-CDE form fields [Mode: ${o.mode}]`);const a=Lt(t,r.onValidationError);R(`├ Tokenizing card info in CDE [Session: ${n.elementsSessionId}]`);const c=await Vo(n.cdeConnections,{session_id:n.elementsSessionId});si(c,r.onValidationError);const d={session_id:n.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:a};try{if(o.mode==="setup"){R(`├ Setting up payment method in CDE [Token: ${o.token}]`);const u=await zo(s,d);return R(`╰ Setup completed successfully [PM ID: ${u.payment_method_id}]`),{mode:"setup",result:u}}else{R(`├ Initial checkout flow. Checking out card info in CDE [Session: ${n.elementsSessionId}]`);const u=await Tn(s,d);return R("╰ Checkout completed successfully."),{mode:"checkout",result:u}}}catch(u){if(u instanceof xn&&u.originalErrorMessage==="3DS_REQUIRED"){R("├ Card requires 3DS, starting non-legacy payment flow"),R("error.response.headers",u.response.headers);const v=((l=u.response.headers)==null?void 0:l["op-should-use-new-flow"])==="true",E=await Zo(s,d);if(R(`├ op-should-use-new-flow: ${v}`),R("├ Payment flow result:",E),v?await bi(E,n.baseUrl):await wi(E),o.mode==="setup"){R(`├ Confirming payment flow [cc_pm_id: ${E.cc_pm_id}]`);const w=await Rt(s,{secure_token:o.token,existing_cc_pm_id:E.cc_pm_id});R("├ Confirm payment flow result received Result:",w);const x=Mt(w);return R(`╰ Setup completed successfully [PM ID: ${x.payment_method_id}]`),{mode:"setup",result:x}}else{R(`├ Checking out after 3DS flow [Flow: ${v?"new":"legacy"}]`);const w=await Tn(s,{...d,existing_cc_pm_id:E.cc_pm_id,do_not_use_legacy_cc_flow:!v});return R("╰ Checkout completed successfully."),{mode:"checkout",result:w}}}throw Un("╰ Error checking out card info in CDE"),Un(u),u}}),_i=n=>{const e=n.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Ps.parse(e)},vi=n=>{const e=n.required_user_actions.find(t=>t.type==="airwallex_payment_consent");if(!e)throw new Error("No common 3DS action found");return Os.parse(e)},bi=async(n,e)=>{const t=vi(n);R(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const r=await yi({url:t.redirect_url,baseUrl:e});if(R(`╰ 3DS verification completed [Status: ${r}]`),r===ct.CANCELLED)throw new Error("3DS verification cancelled");if(r===ct.FAILURE)throw new Error("3DS verification failed")},wi=async n=>{const e=_i(n);Vn(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await $s(e),Vn("╰ Stripe 3DS flow completed successfully")},{log__:D,err__:ki}=ie("stripe-pr"),Ei=i.object({provider:i.union([i.literal("apple_pay"),i.literal("google_pay")]),processor_name:i.literal("stripe"),metadata:i.object({stripe_pk:i.string()})}),Ci=Dn(async({context:n})=>{D("Checking if there are any CPMs for Stripe PR...");const e=$n(n.checkoutPaymentMethods,Ei);D("Initializing Stripe PR flow...");const t=Array.from(n.cdeConnections.values())[0],r=await We(t),s=r.mode==="setup";D("Getting initial preview amount");const o=await Sn(t,r.token,s,void 0),a=await js(e.metadata.stripe_pk,o.amountAtom,o.currency,s);D("Checking if can make payment");const c=await a.canMakePayment();return c===null?(ki("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"}):(D("Stripe PR flow initialized successfully. Can make payment",c),{isAvailable:!0,pr:a,availableProviders:{applePay:c.applePay,googlePay:c.googlePay}})}),xi=jt(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,flowCallbacks:r,customParams:s,initResult:o})=>{if(D("Running Stripe PR flow..."),s.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${s.provider}, got ${e.provider}`);const a=Array.from(n.cdeConnections.values())[0],c=o.pr;if(s!=null&&s.overridePaymentRequest){const x=s.overridePaymentRequest;D("Overriding PR amount with",x),Ti(c,x.amount,x.pending)}D("Showing PR dialog..."),c.show();const d=await Ls(c);D("Stripe PM added event:",d),D("Merging PM fields with form fields...");const l=Si(t,d),u=Lt(l,r.onValidationError);D("PR dialog finished. Starting payment flow...");const v=await Fo(a,{fields:u,checkoutPaymentMethod:e}),E=Oi(v);D("Confirming PR with Stripe..."),await Ds(E,d);const w=await We(a);if(w.mode==="setup"){D("Confirming payment flow for setup...");const x=await Rt(a,{secure_token:w.token});return{mode:"setup",result:Mt(x)}}else{D("Performing checkout...");const x={secure_token:w.token,payment_input:{provider_type:e.provider},customer_email:u[C.EMAIL],customer_zip_code:u[C.ZIP_CODE],customer_country:u[C.COUNTRY],promotion_code:u[C.PROMOTION_CODE],line_items:w.line_items,total_amount_atom:w.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await On(a,x)}}}),Si=(n,e)=>{var a,c,d,l;const t={...n},[r,...s]=((c=(a=e.payerName)==null?void 0:a.trim())==null?void 0:c.split(/\s+/))??[],o=s.join(" ")||void 0;return t[C.FIRST_NAME]=t[C.FIRST_NAME]||r||"_OP_UNKNOWN",t[C.LAST_NAME]=t[C.LAST_NAME]||o||"_OP_UNKNOWN",t[C.EMAIL]=t[C.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[C.ZIP_CODE]=t[C.ZIP_CODE]||((d=e.shippingAddress)==null?void 0:d.postalCode)||"00000",t[C.COUNTRY]=t[C.COUNTRY]||((l=e.shippingAddress)==null?void 0:l.country)||"US",D("Final form inputs:",t),t},Ti=(n,e,t)=>{n.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency})},Oi=n=>{if(n.required_user_actions.length!==1)throw new Error(`Error occurred.
21
- Details: got ${n.required_user_actions.length} required user actions`);return Is.parse(n.required_user_actions[0])},zn=(n,e,t)=>{const r=n.filter(s=>s.provider===e);if(r.length===0)throw console.error("CPMs list",n),new Error(`No CPMs found with provider '${e}' and processor '${t}'`);if(r.length!==1)throw console.error("CPMs list",n),new Error(`More than one CPM found with provider '${e}' and processor '${t}'`);return r[0]},we={commonCC:{run:gi},stripePR:{init:Ci,run:xi},stripeLink:{init:ci,run:li}};function Ri(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var mt={};Object.defineProperty(mt,"__esModule",{value:!0}),mt.Observable=void 0;const Bn=n=>!!Symbol[n],Dt=n=>Bn(n)?Symbol[n]:"@@"+n,Pi=Dt("iterator"),$t=Dt("observable"),qn=Dt("species");function pt(n,e){let t=n[e];if(t!=null){if(typeof t!="function")throw new TypeError(t+" is not a function");return t}}function Ge(n){let e=n.constructor;return e!==void 0&&(e=e[qn],e===null&&(e=void 0)),e!==void 0?e:gt}function Ii(n){return n instanceof gt}function ke(n){ke.log?ke.log(n):setTimeout(()=>{throw n})}function yt(n){Promise.resolve().then(()=>{try{n()}catch(e){ke(e)}})}function Hn(n){let e=n._cleanup;if(e!==void 0&&(n._cleanup=void 0,!!e))try{if(typeof e=="function")e();else{let t=pt(e,"unsubscribe");t&&t.call(e)}}catch(t){ke(t)}}function Zt(n){n._observer=void 0,n._queue=void 0,n._state="closed"}function Ai(n){let e=n._queue;if(e){n._queue=void 0,n._state="ready";for(let t=0;t<e.length&&(Wn(n,e[t].type,e[t].value),n._state!=="closed");++t);}}function Wn(n,e,t){n._state="running";let r=n._observer;try{let s=pt(r,e);switch(e){case"next":s&&s.call(r,t);break;case"error":if(Zt(n),s)s.call(r,t);else throw t;break;case"complete":Zt(n),s&&s.call(r);break}}catch(s){ke(s)}n._state==="closed"?Hn(n):n._state==="running"&&(n._state="ready")}function Ft(n,e,t){if(n._state!=="closed"){if(n._state==="buffering"){n._queue.push({type:e,value:t});return}if(n._state!=="ready"){n._state="buffering",n._queue=[{type:e,value:t}],yt(()=>Ai(n));return}Wn(n,e,t)}}class Ni{constructor(e,t){this._cleanup=void 0,this._observer=e,this._queue=void 0,this._state="initializing";let r=this,s={get closed(){return r._state==="closed"},next(o){Ft(r,"next",o)},error(o){Ft(r,"error",o)},complete(){Ft(r,"complete")}};try{this._cleanup=t.call(void 0,s)}catch(o){s.error(o)}this._state==="initializing"&&(this._state="ready")}get closed(){return this._state==="closed"}unsubscribe(){this._state!=="closed"&&(Zt(this),Hn(this))}}let gt=class _t{constructor(e){if(!(this instanceof _t))throw new TypeError("Observable cannot be called as a function");if(typeof e!="function")throw new TypeError("Observable initializer must be a function");this._subscriber=e}subscribe(e){return(typeof e!="object"||e===null)&&(e={next:e,error:arguments[1],complete:arguments[2]}),new Ni(e,this._subscriber)}forEach(e){return new Promise((t,r)=>{if(typeof e!="function"){r(new TypeError(e+" is not a function"));return}function s(){o.unsubscribe(),t()}let o=this.subscribe({next(a){try{e(a,s)}catch(c){r(c),o.unsubscribe()}},error:r,complete:t})})}map(e){if(typeof e!="function")throw new TypeError(e+" is not a function");let t=Ge(this);return new t(r=>this.subscribe({next(s){try{s=e(s)}catch(o){return r.error(o)}r.next(s)},error(s){r.error(s)},complete(){r.complete()}}))}filter(e){if(typeof e!="function")throw new TypeError(e+" is not a function");let t=Ge(this);return new t(r=>this.subscribe({next(s){try{if(!e(s))return}catch(o){return r.error(o)}r.next(s)},error(s){r.error(s)},complete(){r.complete()}}))}reduce(e){if(typeof e!="function")throw new TypeError(e+" is not a function");let t=Ge(this),r=arguments.length>1,s=!1,a=arguments[1];return new t(c=>this.subscribe({next(d){let l=!s;if(s=!0,!l||r)try{a=e(a,d)}catch(u){return c.error(u)}else a=d},error(d){c.error(d)},complete(){if(!s&&!r)return c.error(new TypeError("Cannot reduce an empty sequence"));c.next(a),c.complete()}}))}async all(){let e=[];return await this.forEach(t=>e.push(t)),e}concat(...e){let t=Ge(this);return new t(r=>{let s,o=0;function a(c){s=c.subscribe({next(d){r.next(d)},error(d){r.error(d)},complete(){o===e.length?(s=void 0,r.complete()):a(t.from(e[o++]))}})}return a(this),()=>{s&&(s.unsubscribe(),s=void 0)}})}flatMap(e){if(typeof e!="function")throw new TypeError(e+" is not a function");let t=Ge(this);return new t(r=>{let s=[],o=this.subscribe({next(c){if(e)try{c=e(c)}catch(l){return r.error(l)}let d=t.from(c).subscribe({next(l){r.next(l)},error(l){r.error(l)},complete(){let l=s.indexOf(d);l>=0&&s.splice(l,1),a()}});s.push(d)},error(c){r.error(c)},complete(){a()}});function a(){o.closed&&s.length===0&&r.complete()}return()=>{s.forEach(c=>c.unsubscribe()),o.unsubscribe()}})}[$t](){return this}static from(e){let t=typeof this=="function"?this:_t;if(e==null)throw new TypeError(e+" is not an object");let r=pt(e,$t);if(r){let s=r.call(e);if(Object(s)!==s)throw new TypeError(s+" is not an object");return Ii(s)&&s.constructor===t?s:new t(o=>s.subscribe(o))}if(Bn("iterator")&&(r=pt(e,Pi),r))return new t(s=>{yt(()=>{if(!s.closed){for(let o of r.call(e))if(s.next(o),s.closed)return;s.complete()}})});if(Array.isArray(e))return new t(s=>{yt(()=>{if(!s.closed){for(let o=0;o<e.length;++o)if(s.next(e[o]),s.closed)return;s.complete()}})});throw new TypeError(e+" is not observable")}static of(...e){let t=typeof this=="function"?this:_t;return new t(r=>{yt(()=>{if(!r.closed){for(let s=0;s<e.length;++s)if(r.next(e[s]),r.closed)return;r.complete()}})})}static get[qn](){return this}};mt.Observable=gt,Object.defineProperty(gt,Symbol("extensions"),{value:{symbol:$t,hostReportError:ke},configurable:!0});var ji=mt.Observable;const Mi=Ri(ji),{log__:Li,err__:Di}=ie("init-flows"),$i=()=>("ojs_init_results"in window||(window.ojs_init_results={}),window.ojs_init_results),Zi=(n,e)=>{const t={context:n,flowCallbacks:e};return console.log("[OJS] initializing OJS flows..."),{stripePR:Yn("stripePR",we.stripePR.init(t)),stripeLink:Yn("stripeLink",we.stripeLink.init(t))}},Yn=(n,e)=>{const t=new Mi(r=>{r.next({status:"loading"}),e.then(s=>{r.next({status:"loaded",result:s})}).catch(s=>{r.next({status:"error",message:s.message})})});return t.subscribe({next:r=>{Li(`${n} flow result`,r),$i()[n]=r},error:r=>{throw Di(`${n} flow initialization error:
22
- ${JSON.stringify(r)}`),r}}),t},Kn={isLoading:!0,isAvailable:!1,startFlow:async()=>{console.warn(`startFlow triggered while payment request is still not ready.
23
- You can check the ".isLoading" param to know when a payment request is still loading,
24
- and ".isAvailable" to know if a payment request is available.`)}},Gn={isLoading:!1,isAvailable:!1,startFlow:async()=>{console.error("startFlow triggered when payment request is not available.")}};class Fi{constructor(e){this.formInstance=e,this.config=e.config,this.formId=e.formId,this.eventTargets={},this.nonces=new Set}handleMessage(e){var c;if(!e.source)throw new Error("No source found");if(e.origin!==((c=this.formInstance.config._frameUrl)==null?void 0:c.origin)||typeof e.data=="object"&&e.data.penpal)return;const t=qs(JSON.parse(e.data));if(!this.validateEvent(t))return;const{elementId:s,payload:o}=t,a=o.type;switch(a){case"LAYOUT":this.handleLayoutEvent(o);break;case"FOCUS":this.handleFocusEvent(s,o.elementType);break;case"BLUR":this.handleBlurEvent(s,o.elementType);break;case"CHANGE":this.handleChangeEvent(s,o.elementType,o.errors);break;case"LOADED":this.handleLoadedEvent(e.source,s,o);break;case"LOAD_ERROR":this.handleLoadErrorEvent(o);break;case"VALIDATION_ERROR":this.handleValidationErrorEvent(o,s);break;default:console.warn("[form] Unhandled event type:",a)}}validateEvent(e){return e.formId!==this.formInstance.formId||!e.elementId?(console.warn("[form] Ignoring unknown event:",e),!1):this.nonces.has(e.nonce)?(console.warn("[form] Ignoring duplicate event:",e),!1):(this.nonces.add(e.nonce),!0)}handleLayoutEvent(e){const t=e.height?`${e.height}px`:"100%";this.formInstance.setFormHeight(t)}handleFocusEvent(e,t){this.config.onFocus&&this.config.onFocus(e,t)}handleBlurEvent(e,t){this.config.onBlur&&this.config.onBlur(e,t)}handleChangeEvent(e,t,r){this.config.onChange&&this.config.onChange(e,t,r)}async handleLoadedEvent(e,t,r){console.log("handleLoadedEvent is deprecated:",e,t,r),this.eventTargets[t]=e,this.formInstance.onCdeLoaded(r),this.config.onLoad&&this.config.onLoad(r.totalAmountAtoms,r.currency)}handleLoadErrorEvent(e){this.formInstance.config.onLoadError&&this.formInstance.config.onLoadError(e.message)}handleValidationErrorEvent(e,t){this.formInstance.config.onValidationError&&this.formInstance.config.onValidationError(e.elementType,e.errors,t)}postEventToFrame(e,t,r){Hs(e,this.formId,t,r,this.config.baseUrl)}}async function Ui(n,e){const r=await pn({iframe:n,debug:!1,childOrigin:e}).promise,s=await po(r);if(!yo(r,s))throw new Error("Got invalid CDE connection object");return r}class Vi{constructor(){this.connections=new Map}addConnection(e,t){this.connections.set(e,t)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Je=class Je{constructor(e){this.tryInitOjsFlows=()=>{this.ojsFlowsInitialization===null&&this.cdeLoadedPayload&&this.connectionManager.getAllConnections().size!==0&&(this.ojsFlowsInitialization=Zi(this.createOjsFlowContext(),this.createOjsFlowCallbacks()),this.ojsFlowsInitialization.stripePR.subscribe(t=>this.onStripePRStatusChange(t)))},this.onCdeLoaded=t=>{this.cdeLoadedPayload||(this.cdeLoadedPayload=t,this.tryInitOjsFlows())},this.onStripePRStatusChange=t=>{var r,s,o,a,c,d;if(t.status==="loading")(s=(r=this.config).onPaymentRequestLoad)==null||s.call(r,{apple_pay:Kn,google_pay:Kn});else if(t.status==="error")(a=(o=this.config).onPaymentRequestLoad)==null||a.call(o,{apple_pay:Gn,google_pay:Gn});else if(t.status==="loaded"){const l=t.result,u=l.isAvailable&&l.availableProviders.applePay,v=l.isAvailable&&l.availableProviders.googlePay;(d=(c=this.config).onPaymentRequestLoad)==null||d.call(c,{apple_pay:{isLoading:!1,isAvailable:u,startFlow:async E=>u?this.submitPaymentRequest("apple_pay",l,E):void 0},google_pay:{isLoading:!1,isAvailable:v,startFlow:async E=>v?this.submitPaymentRequest("google_pay",l,E):void 0}})}},this.submitPaymentRequest=(t,r,s)=>{const o=this.createOjsFlowContext();return we.stripePR.run({context:o,checkoutPaymentMethod:zn(o.checkoutPaymentMethods,t),nonCdeFormInputs:Tt(o.formDiv),flowCallbacks:this.createOjsFlowCallbacks(),customParams:{provider:t,overridePaymentRequest:s==null?void 0:s.overridePaymentRequest},initResult:r})},Je.assignAsSingleton(this),this.config={...e,baseUrl:e.baseUrl??"https://cde.getopenpay.com"},this.elements=null,this.formId=`opjs-form-${window.crypto.randomUUID()}`,this.referer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.cdeLoadedPayload=null,this.ojsFlowsInitialization=null,this.checkoutFired=!1,this.connectionManager=new Vi,this.eventHandler=new Fi(this),this.ojsVersion="0.1.13",this.ojsReleaseVersion="0.1.13",window.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler))}static assignAsSingleton(e){if(Je.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e}static getInstance(){return window.ojs??null}getConnectionManager(){return this.connectionManager}setFormHeight(e){this.formProperties.height=e,this.elements&&Object.values(this.elements).forEach(t=>{t.node.style.height=e})}createElement(e,t={}){if(!this.config)throw new Error("OpenPay form not initialized");const r=ns.parse(e),s=document.createElement("iframe"),o=this.buildQueryString(t);s.name=`${r}-element`;const a=new URL(`/app/v1/${s.name}/`,this.config.baseUrl);a.search=o.toString(),s.src=a.href,this.config._frameUrl=a,s.style.border="none",s.style.width="100%";const c={type:r,node:s,mount:d=>{var l;return(l=document.querySelector(d))==null?void 0:l.appendChild(s)}};return this.connectToElement(c),this.elements?this.elements[r]=c:this.elements={[r]:c},c}buildQueryString(e){const t=new URLSearchParams;return t.append("referer",this.referer),t.append("formId",this.formId),e.styles&&t.append("styles",Zs(e.styles)),t.append("secureToken",this.config.checkoutSecureToken),t}connectToElement(e){Ui(e.node).then(t=>{this.connectionManager.addConnection(e.type,t),this.tryInitOjsFlows()}).catch(t=>console.error("[FORM] Error connecting to CDE iframe",t))}getFormDiv(){return document.querySelector(this.formTarget)??document.body}createOjsFlowContext(){const e=this.connectionManager.getAllConnections();if(!this.cdeLoadedPayload)throw new Error("Requested context while CDE not yet loaded");if(e.size===0)throw new Error("No CDE connections found");return{baseUrl:new URL(this.config.baseUrl??xe).origin,formDiv:this.getFormDiv(),elementsSessionId:this.cdeLoadedPayload.sessionId,checkoutPaymentMethods:this.cdeLoadedPayload.checkoutPaymentMethods,cdeConnections:e,customInitParams:this.config.customInitParams??{}}}createOjsFlowCallbacks(){const e=()=>{};return{onCheckoutError:ze("onCheckoutError",this.config.onCheckoutError??e),onCheckoutStarted:ze("onCheckoutStarted",this.config.onCheckoutStarted??e),onCheckoutSuccess:ze("onCheckoutSuccess",this.config.onCheckoutSuccess??e),onSetupPaymentMethodSuccess:ze("onSetupPaymentMethodSuccess",this.config.onSetupPaymentMethodSuccess??e),onValidationError:ze("onValidationError",this.config.onValidationError??e)}}submit(){const e=this.createOjsFlowContext();we.commonCC.run({context:e,checkoutPaymentMethod:zn(e.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:Tt(e.formDiv),flowCallbacks:this.createOjsFlowCallbacks(),customParams:void 0,initResult:void 0})}onPaymentRequestError(e){console.error("[form] Error from payment request:",e),this.checkoutFired=!1,this.config.onCheckoutError&&this.config.onCheckoutError(e)}destroy(){for(const e of Object.values(this.elements??{}))e.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler))}};Je.ojsFlows=we;let Ut=Je;ae.FieldName=C,ae.OpenPayForm=Ut,Object.defineProperty(ae,Symbol.toStringTag,{value:"Module"})});
20
+ `;const t=document.createElement("div"),n=t.attachShadow({mode:"open"});n.appendChild(e.content.cloneNode(!0));const s=n.querySelector("#three-ds-iframe"),i=n.querySelector(".cancel-button");return document.body.appendChild(t),{host:t,iframe:s,cancelButton:i}};function Ro(r,e,t){const n=async()=>{try{const i=await no(r,t);i&&(clearInterval(s),e(i))}catch{}};n();const s=setInterval(n,Lr);return s}function Po({elements:r,pollingInterval:e,resolve:t}){const n=()=>{clearInterval(e),r.host.remove(),t(pt.CANCELLED)};return r.cancelButton.addEventListener("click",n),()=>{r.cancelButton.removeEventListener("click",n)}}async function Io({url:r,baseUrl:e}){const t=Oo(r);return new Promise(n=>{const s=c=>{setTimeout(()=>{t.host.remove()},1e3),n(c),o==null||o()},i=Ro(t.iframe,s,new URL(e).origin),o=Po({elements:t,pollingInterval:i,resolve:n})})}const{log__:I,err__:Wr}=ee("common-cc"),{log__:Gr}=ee("stripe-cc"),Ao=Ft(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{var d;I("├ Running common CC flow...",{checkoutPaymentMethod:e});const i=r.anyCdeConnection,o=await et(i);I(`├ Validating non-CDE form fields [Mode: ${o.mode}]`);const c=zt(t,n.get.onValidationError??(()=>{}));I(`├ Tokenizing card info in CDE [Session: ${r.elementsSessionId}]`);const l=await to(s.currentCdeConnections,{session_id:r.elementsSessionId});vo(l,n.get.onValidationError??(()=>{}));const u={session_id:r.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c};try{if(o.mode==="setup"){I(`├ Setting up payment method in CDE [Token: ${o.token}]`);const y=await ro(i,u);return I(`╰ Setup completed successfully [PM ID: ${y.payment_method_id}]`),{mode:"setup",result:y}}else{I(`├ Initial checkout flow. Checking out card info in CDE [Session: ${r.elementsSessionId}]`);const y=await Nr(i,u);return I("╰ Checkout completed successfully."),{mode:"checkout",result:y}}}catch(y){if(y instanceof Ar&&y.originalErrorMessage==="3DS_REQUIRED"){I("├ Card requires 3DS, starting non-legacy payment flow"),I("error.response.headers",y.response.headers);const w=((d=y.response.headers)==null?void 0:d["op-should-use-new-flow"])==="true",p=await Xi(i,u);if(I(`├ op-should-use-new-flow: ${w}`),I("├ Payment flow result:",p),w?await Mo(p,r.baseUrl):await Lo(p),o.mode==="setup"){I(`├ Confirming payment flow [cc_pm_id: ${p.cc_pm_id}]`);const _=await Lt(i,{secure_token:o.token,existing_cc_pm_id:p.cc_pm_id});I("├ Confirm payment flow result received Result:",_);const S=Vt(_);return I(`╰ Setup completed successfully [PM ID: ${S.payment_method_id}]`),{mode:"setup",result:S}}else{I(`├ Checking out after 3DS flow [Flow: ${w?"new":"legacy"}]`);const _=await Nr(i,{...u,existing_cc_pm_id:p.cc_pm_id,do_not_use_legacy_cc_flow:!w});return I("╰ Checkout completed successfully."),{mode:"checkout",result:_}}}throw Wr("╰ Error checking out card info in CDE"),Wr(y),y}}),jo=r=>{const e=r.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Ks.parse(e)},No=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");if(!e)throw new Error("No common 3DS action found");return Ws.parse(e)},Mo=async(r,e)=>{const t=No(r);I(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const n=await Io({url:t.redirect_url,baseUrl:e});if(I(`╰ 3DS verification completed [Status: ${n}]`),n===pt.CANCELLED)throw new Error("3DS verification cancelled");if(n===pt.FAILURE)throw new Error("3DS verification failed")},Lo=async r=>{const e=jo(r);Gr(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await si(e),Gr("╰ Stripe 3DS flow completed successfully")},{log__:U,err__:Do}=ee("stripe-pr"),$o=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()})}),Zo=Br(async({context:r})=>{U("Checking if there are any CPMs for Stripe PR...");const e=qr(r.checkoutPaymentMethods,$o);U("Initializing Stripe PR flow...");const t=r.anyCdeConnection,n=await et(t),s=n.mode==="setup";U("Getting initial preview amount");const i=await jr(t,n.token,s,void 0),o=await ei(e.metadata.stripe_pk,i.amountAtom,i.currency,s);U("Checking if can make payment");const c=await o.canMakePayment();return c===null?(Do("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"}):(U("Stripe PR flow initialized successfully. Can make payment",c),{isAvailable:!0,pr:o,availableProviders:{applePay:c.applePay,googlePay:c.googlePay}})}),Uo=Ft(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s,initResult:i})=>{if(U("Running Stripe PR flow..."),s.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${s.provider}, got ${e.provider}`);const o=r.anyCdeConnection,c=i.pr;if(s!=null&&s.overridePaymentRequest){const _=s.overridePaymentRequest;U("Overriding PR amount with",_),Vo(c,_.amount,_.pending)}U("Showing PR dialog..."),c.show();const l=await ri(c);U("Stripe PM added event:",l),U("Merging PM fields with form fields...");const u=Fo(t,l),d=zt(u,n.get.onValidationError??(()=>{}));U("PR dialog finished. Starting payment flow...");const y=await Qi(o,{fields:d,checkoutPaymentMethod:e}),w=zo(y);U("Confirming PR with Stripe..."),await ni(w,l);const p=await et(o);if(p.mode==="setup"){U("Confirming payment flow for setup...");const _=await Lt(o,{secure_token:p.token});return{mode:"setup",result:Vt(_)}}else{U("Performing checkout...");const _={secure_token:p.token,payment_input:{provider_type:e.provider},customer_email:d[x.EMAIL],customer_zip_code:d[x.ZIP_CODE],customer_country:d[x.COUNTRY],promotion_code:d[x.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 Mr(o,_)}}}),Fo=(r,e)=>{var o,c,l,u;const t={...r},[n,...s]=((c=(o=e.payerName)==null?void 0:o.trim())==null?void 0:c.split(/\s+/))??[],i=s.join(" ")||void 0;return t[x.FIRST_NAME]=t[x.FIRST_NAME]||n||"_OP_UNKNOWN",t[x.LAST_NAME]=t[x.LAST_NAME]||i||"_OP_UNKNOWN",t[x.EMAIL]=t[x.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[x.ZIP_CODE]=t[x.ZIP_CODE]||((l=e.shippingAddress)==null?void 0:l.postalCode)||"00000",t[x.COUNTRY]=t[x.COUNTRY]||((u=e.shippingAddress)==null?void 0:u.country)||"US",U("Final form inputs:",t),t},Vo=(r,e,t)=>{r.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency})},zo=r=>{if(r.required_user_actions.length!==1)throw new Error(`Error occurred.
21
+ Details: got ${r.required_user_actions.length} required user actions`);return Js.parse(r.required_user_actions[0])},Kr=(r,e,t)=>{const n=r.filter(s=>s.provider===e);if(n.length===0)throw console.error("CPMs list",r),new Error(`No CPMs found with provider '${e}' and processor '${t}'`);if(n.length!==1)throw console.error("CPMs list",r),new Error(`More than one CPM found with provider '${e}' and processor '${t}'`);return n[0]},Te={commonCC:{init:async()=>{},run:Ao},stripePR:{init:Zo,run:Uo},stripeLink:{init:Eo,run:So}};var Bt=function(r,e){return Bt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])},Bt(r,e)};function de(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Bt(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Bo(r,e,t,n){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function c(d){try{u(n.next(d))}catch(y){o(y)}}function l(d){try{u(n.throw(d))}catch(y){o(y)}}function u(d){d.done?i(d.value):s(d.value).then(c,l)}u((n=n.apply(r,e||[])).next())})}function Jr(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,s,i,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=c(0),o.throw=c(1),o.return=c(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function c(u){return function(d){return l([u,d])}}function l(u){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,u[0]&&(t=0)),t;)try{if(n=1,s&&(i=u[0]&2?s.return:u[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,u[1])).done)return i;switch(s=0,i&&(u=[u[0]&2,i.value]),u[0]){case 0:case 1:i=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,s=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){t.label=u[1];break}if(u[0]===6&&t.label<i[1]){t.label=i[1],i=u;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(u);break}i[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(r,t)}catch(d){u=[6,d],s=0}finally{n=i=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function Oe(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function vt(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)i.push(s.value)}catch(c){o={error:c}}finally{try{s&&!s.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return i}function bt(r,e,t){if(t||arguments.length===2)for(var n=0,s=e.length,i;n<s;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))}function Re(r){return this instanceof Re?(this.v=r,this):new Re(r)}function qo(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),s,i=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",o),s[Symbol.asyncIterator]=function(){return this},s;function o(p){return function(_){return Promise.resolve(_).then(p,y)}}function c(p,_){n[p]&&(s[p]=function(S){return new Promise(function(O,F){i.push([p,S,O,F])>1||l(p,S)})},_&&(s[p]=_(s[p])))}function l(p,_){try{u(n[p](_))}catch(S){w(i[0][3],S)}}function u(p){p.value instanceof Re?Promise.resolve(p.value.v).then(d,y):w(i[0][2],p)}function d(p){l("next",p)}function y(p){l("throw",p)}function w(p,_){p(_),i.shift(),i.length&&l(i[0][0],i[0][1])}}function Ho(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof Oe=="function"?Oe(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=r[i]&&function(o){return new Promise(function(c,l){o=r[i](o),s(c,l,o.done,o.value)})}}function s(i,o,c,l){Promise.resolve(l).then(function(u){i({value:u,done:c})},o)}}typeof SuppressedError=="function"&&SuppressedError;function N(r){return typeof r=="function"}function wt(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var qt=wt(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
22
+ `+t.map(function(n,s){return s+1+") "+n.toString()}).join(`
23
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function kt(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var nt=function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,s,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var c=Oe(o),l=c.next();!l.done;l=c.next()){var u=l.value;u.remove(this)}}catch(S){e={error:S}}finally{try{l&&!l.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else o.remove(this);var d=this.initialTeardown;if(N(d))try{d()}catch(S){i=S instanceof qt?S.errors:[S]}var y=this._finalizers;if(y){this._finalizers=null;try{for(var w=Oe(y),p=w.next();!p.done;p=w.next()){var _=p.value;try{en(_)}catch(S){i=i??[],S instanceof qt?i=bt(bt([],vt(i)),vt(S.errors)):i.push(S)}}}catch(S){n={error:S}}finally{try{p&&!p.done&&(s=w.return)&&s.call(w)}finally{if(n)throw n.error}}}if(i)throw new qt(i)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)en(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&kt(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&kt(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),Xr=nt.EMPTY;function Qr(r){return r instanceof nt||r&&"closed"in r&&N(r.remove)&&N(r.add)&&N(r.unsubscribe)}function en(r){N(r)?r():r.unsubscribe()}var tn={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},rn={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,bt([r,e],vt(t)))},clearTimeout:function(r){var e=rn.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function nn(r){rn.setTimeout(function(){throw r})}function sn(){}function Et(r){r()}var Ht=function(r){de(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,Qr(t)&&t.add(n)):n.destination=Ko,n}return e.create=function(t,n,s){return new Wt(t,n,s)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(nt),Yo=Function.prototype.bind;function Yt(r,e){return Yo.call(r,e)}var Wo=function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){St(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){St(n)}else St(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){St(t)}},r}(),Wt=function(r){de(e,r);function e(t,n,s){var i=r.call(this)||this,o;if(N(t)||!t)o={next:t??void 0,error:n??void 0,complete:s??void 0};else{var c;i&&tn.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return i.unsubscribe()},o={next:t.next&&Yt(t.next,c),error:t.error&&Yt(t.error,c),complete:t.complete&&Yt(t.complete,c)}):o=t}return i.destination=new Wo(o),i}return e}(Ht);function St(r){nn(r)}function Go(r){throw r}var Ko={closed:!0,next:sn,error:Go,complete:sn},Gt=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Jo(r){return r}function Xo(r){return r.length===0?Jo:r.length===1?r[0]:function(t){return r.reduce(function(n,s){return s(n)},t)}}var ne=function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var s=this,i=ea(e)?e:new Wt(e,t,n);return Et(function(){var o=s,c=o.operator,l=o.source;i.add(c?c.call(i,l):l?s._subscribe(i):s._trySubscribe(i))}),i},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=on(t),new t(function(s,i){var o=new Wt({next:function(c){try{e(c)}catch(l){i(l),o.unsubscribe()}},error:i,complete:s});n.subscribe(o)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Gt]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Xo(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=on(e),new e(function(n,s){var i;t.subscribe(function(o){return i=o},function(o){return s(o)},function(){return n(i)})})},r.create=function(e){return new r(e)},r}();function on(r){var e;return(e=r??tn.Promise)!==null&&e!==void 0?e:Promise}function Qo(r){return r&&N(r.next)&&N(r.error)&&N(r.complete)}function ea(r){return r&&r instanceof Ht||Qo(r)&&Qr(r)}function ta(r){return N(r==null?void 0:r.lift)}function ra(r){return function(e){if(ta(e))return e.lift(function(t){try{return r(t,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function na(r,e,t,n,s){return new sa(r,e,t,n,s)}var sa=function(r){de(e,r);function e(t,n,s,i,o,c){var l=r.call(this,t)||this;return l.onFinalize=o,l.shouldUnsubscribe=c,l._next=n?function(u){try{n(u)}catch(d){t.error(d)}}:r.prototype._next,l._error=i?function(u){try{i(u)}catch(d){t.error(d)}finally{this.unsubscribe()}}:r.prototype._error,l._complete=s?function(){try{s()}catch(u){t.error(u)}finally{this.unsubscribe()}}:r.prototype._complete,l}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;r.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(Ht),ia=wt(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),an=function(r){de(e,r);function e(){var t=r.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var n=new cn(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new ia},e.prototype.next=function(t){var n=this;Et(function(){var s,i;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var o=Oe(n.currentObservers),c=o.next();!c.done;c=o.next()){var l=c.value;l.next(t)}}catch(u){s={error:u}}finally{try{c&&!c.done&&(i=o.return)&&i.call(o)}finally{if(s)throw s.error}}}})},e.prototype.error=function(t){var n=this;Et(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=t;for(var s=n.observers;s.length;)s.shift().error(t)}})},e.prototype.complete=function(){var t=this;Et(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var n=t.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,s=this,i=s.hasError,o=s.isStopped,c=s.observers;return i||o?Xr:(this.currentObservers=null,c.push(t),new nt(function(){n.currentObservers=null,kt(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,s=n.hasError,i=n.thrownError,o=n.isStopped;s?t.error(i):o&&t.complete()},e.prototype.asObservable=function(){var t=new ne;return t.source=this,t},e.create=function(t,n){return new cn(t,n)},e}(ne),cn=function(r){de(e,r);function e(t,n){var s=r.call(this)||this;return s.destination=t,s.source=n,s}return e.prototype.next=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.next)===null||s===void 0||s.call(n,t)},e.prototype.error=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.error)===null||s===void 0||s.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,s;return(s=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&s!==void 0?s:Xr},e}(an),oa={now:function(){return Date.now()},delegate:void 0},aa=function(r){de(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(nt),un={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,bt([r,e],vt(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},ca=function(r){de(e,r);function e(t,n){var s=r.call(this,t,n)||this;return s.scheduler=t,s.work=n,s.pending=!1,s}return e.prototype.schedule=function(t,n){var s;if(n===void 0&&(n=0),this.closed)return this;this.state=t;var i=this.id,o=this.scheduler;return i!=null&&(this.id=this.recycleAsyncId(o,i,n)),this.pending=!0,this.delay=n,this.id=(s=this.id)!==null&&s!==void 0?s:this.requestAsyncId(o,this.id,n),this},e.prototype.requestAsyncId=function(t,n,s){return s===void 0&&(s=0),un.setInterval(t.flush.bind(t,this),s)},e.prototype.recycleAsyncId=function(t,n,s){if(s===void 0&&(s=0),s!=null&&this.delay===s&&this.pending===!1)return n;n!=null&&un.clearInterval(n)},e.prototype.execute=function(t,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var s=this._execute(t,n);if(s)return s;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,n){var s=!1,i;try{this.work(t)}catch(o){s=!0,i=o||new Error("Scheduled action threw falsy error")}if(s)return this.unsubscribe(),i},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,s=t.scheduler,i=s.actions;this.work=this.state=this.scheduler=null,this.pending=!1,kt(i,this),n!=null&&(this.id=this.recycleAsyncId(s,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(aa),ln=function(){function r(e,t){t===void 0&&(t=r.now),this.schedulerActionCtor=e,this.now=t}return r.prototype.schedule=function(e,t,n){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},r.now=oa.now,r}(),ua=function(r){de(e,r);function e(t,n){n===void 0&&(n=ln.now);var s=r.call(this,t,n)||this;return s.actions=[],s._active=!1,s}return e.prototype.flush=function(t){var n=this.actions;if(this._active){n.push(t);return}var s;this._active=!0;do if(s=t.execute(t.state,t.delay))break;while(t=n.shift());if(this._active=!1,s){for(;t=n.shift();)t.unsubscribe();throw s}},e}(ln),la=new ua(ca),da=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function fa(r){return N(r==null?void 0:r.then)}function ha(r){return N(r[Gt])}function pa(r){return Symbol.asyncIterator&&N(r==null?void 0:r[Symbol.asyncIterator])}function ma(r){return new TypeError("You provided "+(r!==null&&typeof r=="object"?"an invalid object":"'"+r+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function ya(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var ga=ya();function _a(r){return N(r==null?void 0:r[ga])}function va(r){return qo(this,arguments,function(){var t,n,s,i;return Jr(this,function(o){switch(o.label){case 0:t=r.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,Re(t.read())];case 3:return n=o.sent(),s=n.value,i=n.done,i?[4,Re(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,Re(s)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function ba(r){return N(r==null?void 0:r.getReader)}function wa(r){if(r instanceof ne)return r;if(r!=null){if(ha(r))return ka(r);if(da(r))return Ea(r);if(fa(r))return Sa(r);if(pa(r))return dn(r);if(_a(r))return Ca(r);if(ba(r))return xa(r)}throw ma(r)}function ka(r){return new ne(function(e){var t=r[Gt]();if(N(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Ea(r){return new ne(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function Sa(r){return new ne(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,nn)})}function Ca(r){return new ne(function(e){var t,n;try{for(var s=Oe(r),i=s.next();!i.done;i=s.next()){var o=i.value;if(e.next(o),e.closed)return}}catch(c){t={error:c}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}e.complete()})}function dn(r){return new ne(function(e){Ta(r,e).catch(function(t){return e.error(t)})})}function xa(r){return dn(va(r))}function Ta(r,e){var t,n,s,i;return Bo(this,void 0,void 0,function(){var o,c;return Jr(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),t=Ho(r),l.label=1;case 1:return[4,t.next()];case 2:if(n=l.sent(),!!n.done)return[3,4];if(o=n.value,e.next(o),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=l.sent(),s={error:c},[3,11];case 6:return l.trys.push([6,,9,10]),n&&!n.done&&(i=t.return)?[4,i.call(t)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(s)throw s.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Oa(r,e,t,n,s){n===void 0&&(n=0),s===void 0&&(s=!1);var i=e.schedule(function(){t(),s?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(i),!s)return i}function Ra(r,e){var t=N(r)?r:function(){return r},n=function(s){return s.error(t())};return new ne(n)}var Pa=wt(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function Ia(r,e){return new Promise(function(t,n){var s=!1,i;r.subscribe({next:function(o){i=o,s=!0},error:n,complete:function(){s?t(i):n(new Pa)}})})}function Aa(r){return r instanceof Date&&!isNaN(r)}var ja=wt(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Na(r,e){var t=Aa(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,s=t.each,i=t.with,o=i===void 0?Ma:i,c=t.scheduler,l=c===void 0?la:c,u=t.meta,d=u===void 0?null:u;if(n==null&&s==null)throw new TypeError("No timeout provided.");return ra(function(y,w){var p,_,S=null,O=0,F=function($){_=Oa(w,l,function(){try{p.unsubscribe(),wa(o({meta:d,lastValue:S,seen:O})).subscribe(w)}catch(A){w.error(A)}},$)};p=y.subscribe(na(w,function($){_==null||_.unsubscribe(),O++,w.next(S=$),s>0&&F(s)},void 0,void 0,function(){_!=null&&_.closed||_==null||_.unsubscribe(),S=null})),!O&&F(n!=null?typeof n=="number"?n:+n-l.now():s)})}function Ma(r){throw new ja(r)}class Ct{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,t)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:t},this._subject.error(e)},this.getValueIfLoadedElse=e=>this._current.status==="success"?this._current.loadedValue:e,this.subscribe=e=>{if(this._current.status==="success"){e(this._current);return}this._current.status==="error"&&e(this._current);const t=this._subject.subscribe({next:()=>{if(this._current.status!=="success")throw new Error("Invalid state (next): please make sure to update _current before the subject");e(this._current),t.unsubscribe()},error:()=>{if(this._current.status!=="error")throw new Error("Invalid state (error): please make sure to update _current before the subject");e(this._current)}})},this.waitForLoad=e=>{if(this._current.status==="success")return Promise.resolve(this._current.loadedValue);if(this._current.status==="error")return Promise.reject(this._current.error);this._current.status!=="initial"&&so(this._current);const t={first:e.timeoutSec*1e3,with:()=>Ra(()=>new Error(e.timeoutErrMsg))};return Ia(this._subject.pipe(Na(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new an}get current(){return this._current}}const{log__:La,err__:Da}=ee("init-flows"),fn=(r,e)=>{const t=new Ct;return{publisher:t,initialize:async n=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const s=await e(n);La(`✔ ${r} flow initialized successfully. Result:`,s),t.set(s)}catch(s){Da(`𝙭 ${r} flow initialization failed. Error:`,Ke(s),"Details:",s),t.throw(s,Ke(s))}}}},$a=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},Za=()=>({stripePR:fn("Stripe PR",Te.stripePR.init),stripeLink:fn("Stripe Link",Te.stripeLink.init)}),{err__:Ua}=ee("form-callbacks"),W=a.function().optional(),Fa=a.object({onFocus:W,onBlur:W,onChange:W,onLoad:W,onLoadError:W,onValidationError:W,onCheckoutStarted:W,onCheckoutSuccess:W,onSetupPaymentMethodSuccess:W,onCheckoutError:W,onPaymentRequestLoad:W}),xt=class xt{constructor(){this._callbacks={},this.setCallbacks=e=>{this._callbacks={},Object.entries(e).forEach(([t,n])=>{const s=ws(t,n??(()=>{}),Ua);this._callbacks[t]=s})}}get get(){return{...this._callbacks}}};xt.fromObject=e=>{const t=new xt;return t.setCallbacks(Fa.parse(e)),t};let Kt=xt;class Va{constructor(e,t,n,s){this.handleMessage=i=>{var y,w,p,_,S,O,F,$;if(!i.source)throw new Error("No source found");if(hn(i.origin)!==hn(this.baseUrl)||typeof i.data=="object"&&i.data.penpal)return;const o=oi(JSON.parse(i.data));if(!this.validateEvent(o))return;const{elementId:l,payload:u}=o,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":(w=(y=this.formCallbacks.get).onFocus)==null||w.call(y,l,u.elementType);break;case"BLUR":(_=(p=this.formCallbacks.get).onBlur)==null||_.call(p,l,u.elementType);break;case"CHANGE":(O=(S=this.formCallbacks.get).onChange)==null||O.call(S,l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=i.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":($=(F=this.formCallbacks.get).onValidationError)==null||$.call(F,u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=i=>i.formId!==this.formId||!i.elementId?(console.log("[OJS] formId",this.formId,i.formId),console.warn("[form] Ignoring unknown event:",i),!1):this.nonces.has(i.nonce)?(console.warn("[form] Ignoring duplicate event:",i),!1):(this.nonces.add(i.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=n,this.internalCallbacks=s}}const hn=r=>new URL(r).origin;async function za(r,e){const n=await kr({iframe:r,debug:!1,childOrigin:e}).promise,s=await Oi(n);if(!Ri(n,s))throw new Error("Got invalid CDE connection object");return n}class Ba{constructor(){this.connections=new Map}addConnection(e,t){this.connections.set(e,t)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const qa=(r,e,t)=>{const{stripePR:n}=r;n.publisher.subscribe(s=>{var i,o;if(s.isSuccess){const c=s.loadedValue,l=c.isAvailable&&c.availableProviders.applePay,u=c.isAvailable&&c.availableProviders.googlePay,d={apple_pay:{isLoading:!1,isAvailable:l,startFlow:async y=>{l&&pn("apple_pay",c,e,t,y)}},google_pay:{isLoading:!1,isAvailable:u,startFlow:async y=>{u&&pn("google_pay",c,e,t,y)}}};(o=(i=t.get).onPaymentRequestLoad)==null||o.call(i,d)}})},pn=(r,e,t,n,s)=>Te.stripePR.run({context:t,checkoutPaymentMethod:Kr(t.checkoutPaymentMethods,r),nonCdeFormInputs:Nt(t.formDiv),formCallbacks:n,customParams:{provider:r,overridePaymentRequest:s==null?void 0:s.overridePaymentRequest},initResult:e}),mn="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:fe,err__:Jt}=ee("op-form"),se=class se{constructor(e){this.cdeLoadEvent=new Ct,this.anyCdeConn=new Ct,this.context=new Ct,this.initFlows=Za(),this.startFormInit=async()=>{var t,n,s,i;try{fe("Initializing OpenPay form:"),fe("├ Waiting for CDE load event...");const o=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:mn});fe("├ CDE load event received"),fe("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:mn});fe("├ CDE connection received"),fe("├ Creating OJS context, setting up handlers...");const l=se.buildOjsFlowContext(this.config,o,c,this.getFormDiv());this.context.set(l),qa(this.initFlows,l,this.formCallbacks),fe("├ Starting OJS init flows..."),await $a(this.initFlows,l,this.formCallbacks),(n=(t=this.formCallbacks.get).onLoad)==null||n.call(t,o.totalAmountAtoms,o.currency),fe("╰ Done initializing OJS flows.")}catch(o){const c=Ke(o);Jt("╰ Error initializing OP form:",c),(i=(s=this.formCallbacks.get).onLoadError)==null||i.call(s,c)}},this.setFormHeight=t=>{this.formProperties.height=t,this.registeredElements&&Object.values(this.registeredElements).forEach(n=>{n&&(n.node.style.height=t)})},this.onCdeLoaded=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.set(t)},this.onCdeLoadError=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.throw(new Error(t),t)},this.createElement=(t,n={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const s=ks.parse(t),i=document.createElement("iframe"),o=this.buildQueryString(n);i.name=`${s}-element`;const c=new URL(`/app/v1/${i.name}/`,this.config.baseUrl);return c.search=o.toString(),i.src=c.href,i.style.border="none",i.style.width="100%",this.registerIframe(s,i)},this.registerIframe=(t,n)=>{const s={type:t,node:n,mount:i=>{var o;return(o=document.querySelector(i))==null?void 0:o.appendChild(n)}};return this.connectToElement({type:s.type,node:s.node}),this.registeredElements||(this.registeredElements={[Se.CARD]:void 0,[Se.CARD_NUMBER]:void 0,[Se.CARD_EXPIRY]:void 0,[Se.CARD_CVC]:void 0}),this.registeredElements[t]=s,s},this.buildQueryString=t=>{const n=new URLSearchParams;return n.append("referer",this.referrer),n.append("formId",this.formId),t.styles&&n.append("styles",ii(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{za(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Jt("[FORM] Error connecting to CDE iframe",n))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{const t=this.context.getValueIfLoadedElse(null);if(!t){Jt("Please wait for the form to finish loading before submitting.");return}Te.commonCC.run({context:t,checkoutPaymentMethod:Kr(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:Nt(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.submit=this.submitCard,this.destroy=()=>{for(const t of Object.values(this.registeredElements??{}))t&&t.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler))},se.assignAsSingleton(this),this.ojsVersion="0.1.15",this.ojsReleaseVersion="0.1.15-alpha.09caa9f",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Kt.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${window.crypto.randomUUID()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Ba,this.eventHandler=new Va(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),window.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}};se.ojsFlows=Te,se.assignAsSingleton=e=>{if(se.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},se.getInstance=()=>window.ojs??null,se.buildOjsFlowContext=(e,t,n,s)=>({baseUrl:new URL(e.baseUrl??Ae).origin,formDiv:s,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Xt=se;he.FieldName=x,he.OpenPayForm=Xt,Object.defineProperty(he,Symbol.toStringTag,{value:"Module"})});