@alter-ai/connect 0.11.0 → 0.12.0

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.
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).AlterConnect=t()}(this,function(){"use strict";const e="https://backend.alterauth.com";function t(e,...t){e.debug&&console.log("[Alter Connect]",...t)}class n{constructor(){this.events=new Map}on(e,t){return this.events.has(e)||this.events.set(e,new Set),this.events.get(e).add(t),()=>this.off(e,t)}off(e,t){const n=this.events.get(e);n&&n.delete(t)}emit(e,...t){const n=this.events.get(e);n&&n.forEach(n=>{try{n(...t)}catch(t){console.error(`[Alter Connect] Error in event handler for '${e}':`,t)}})}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}}class r{constructor(){this.state={isOpen:!1,sessionToken:null,error:null},this.listeners=new Set}getState(){return{...this.state}}get(e){return this.state[e]}setState(e){this.state={...this.state,...e},this.notifyListeners()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clearListeners(){this.listeners.clear()}notifyListeners(){const e=this.getState();this.listeners.forEach(t=>{try{t(e)}catch(e){console.error("[Alter Connect] Error in state listener:",e)}})}}var o;function i(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:s,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const o=s.prototype,i=Object.keys(o);for(let e=0;e<i.length;e++){const t=i[e];t in n||(n[t]=o[t].bind(n))}}const o=n?.Parent??Object;class i extends o{}function s(e){var t;const o=n?.Parent?new i:this;r(o,e),(t=o._zod).deferred??(t.deferred=[]);for(const e of o._zod.deferred)e();return o}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class s extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class a extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(o=globalThis).__zod_globalConfig??(o.__zod_globalConfig={});const c=globalThis.__zod_globalConfig;function u(e){return c}function d(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function p(e,t){return"bigint"==typeof t?t.toString():t}function l(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function h(e){return null==e}function f(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const m=Symbol("evaluating");function g(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==m)return void 0===r&&(r=m,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function _(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function v(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function y(e){return JSON.stringify(e)}const w="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function z(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const b=l(()=>{if(c.jitless)return!1;if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function k(e){if(!1===z(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==z(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function O(e){return k(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const $=new Set(["string","number","symbol"]);function S(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function E(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function Z(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function A(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function x(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!1===e.issues[n]?.continue)return!0;return!1}function P(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function T(e){return"string"==typeof e?e:e?.message}function I(e,t,n){const r=e.message?e.message:T(e.inst?._zod.def?.error?.(e))??T(t?.error?.(e))??T(n.customError?.(e))??T(n.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=r,t?.reportInput&&(a.input=s),a}function j(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function C(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const R=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,p,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},U=i("$ZodError",R),N=i("$ZodError",R,{Parent:Error});const L=e=>(t,n,r,o)=>{const i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new s;if(a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>I(e,i,u())));throw w(t,o?.callee),t}return a.value},D=e=>async(t,n,r,o)=>{const i=r?{...r,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new(o?.Err??e)(s.issues.map(e=>I(e,i,u())));throw w(t,o?.callee),t}return s.value},J=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new s;return i.issues.length?{success:!1,error:new(e??U)(i.issues.map(e=>I(e,o,u())))}:{success:!0,data:i.value}},F=J(N),M=e=>async(t,n,r)=>{const o=r?{...r,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>I(e,o,u())))}:{success:!0,data:i.value}},W=M(N),H=e=>(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return L(e)(t,n,o)},V=e=>(t,n,r)=>L(e)(t,n,r),K=e=>async(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return D(e)(t,n,o)},B=e=>async(t,n,r)=>D(e)(t,n,r),q=e=>(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return J(e)(t,n,o)},G=e=>(t,n,r)=>J(e)(t,n,r),Y=e=>async(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return M(e)(t,n,o)},X=e=>async(t,n,r)=>M(e)(t,n,r),Q=/^[cC][0-9a-z]{6,}$/,ee=/^[0-9a-z]+$/,te=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ne=/^[0-9a-vA-V]{20}$/,re=/^[A-Za-z0-9]{27}$/,oe=/^[a-zA-Z0-9_-]{21}$/,ie=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,se=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ae=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ce=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;const ue=/^(?:(?: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])$/,de=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,pe=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,le=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,he=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,fe=/^[A-Za-z0-9_-]*$/,me=/^https?$/,ge=/^\+[1-9]\d{6,14}$/,_e="(?:(?:\\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])))",ve=new RegExp(`^${_e}$`);function ye(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const we=/^[^A-Z]*$/,ze=/^[^a-z]*$/,be=i("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ke=i("$ZodCheckMaxLength",(e,t)=>{var n;be.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!h(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const o=j(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Oe=i("$ZodCheckMinLength",(e,t)=>{var n;be.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!h(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const o=j(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),$e=i("$ZodCheckLengthEquals",(e,t)=>{var n;be.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!h(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,o=r.length;if(o===t.length)return;const i=j(r),s=o>t.length;n.issues.push({origin:i,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Se=i("$ZodCheckStringFormat",(e,t)=>{var n,r;be.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Ee=i("$ZodCheckRegex",(e,t)=>{Se.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ze=i("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=we),Se.init(e,t)}),Ae=i("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ze),Se.init(e,t)}),xe=i("$ZodCheckIncludes",(e,t)=>{be.init(e,t);const n=S(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Pe=i("$ZodCheckStartsWith",(e,t)=>{be.init(e,t);const n=new RegExp(`^${S(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Te=i("$ZodCheckEndsWith",(e,t)=>{be.init(e,t);const n=new RegExp(`.*${S(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Ie=i("$ZodCheckOverwrite",(e,t)=>{be.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class je{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of r)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const Ce={major:4,minor:4,patch:3},Re=i("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ce;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const t of r)for(const n of t._zod.onattach)n(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,o=A(e);for(const i of t){if(i._zod.def.when){if(x(e))continue;if(!i._zod.def.when(e))continue}else if(o)continue;const t=e.issues.length,a=i._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new s;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a;e.issues.length!==t&&(o||(o=A(e,t)))});else{if(e.issues.length===t)continue;o||(o=A(e,t))}}return r?r.then(()=>e):e},n=(n,o,i)=>{if(A(n))return n.aborted=!0,n;const a=t(o,r,i);if(a instanceof Promise){if(!1===i.async)throw new s;return a.then(t=>e._zod.parse(t,i))}return e._zod.parse(a,i)};e._zod.run=(o,i)=>{if(i.skipChecks)return e._zod.parse(o,i);if("backward"===i.direction){const t=e._zod.parse({value:o.value,issues:[]},{...i,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,o,i)):n(t,o,i)}const a=e._zod.parse(o,i);if(a instanceof Promise){if(!1===i.async)throw new s;return a.then(e=>t(e,r,i))}return t(a,r,i)}}g(e,"~standard",()=>({validate:t=>{try{const n=F(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return W(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),Ue=i("$ZodString",(e,t)=>{var n;Re.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ne=i("$ZodStringFormat",(e,t)=>{Se.init(e,t),Ue.init(e,t)}),Le=i("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=se),Ne.init(e,t)}),De=i("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ae(e))}else t.pattern??(t.pattern=ae());Ne.init(e,t)}),Je=i("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ce),Ne.init(e,t)}),Fe=i("$ZodURL",(e,t)=>{Ne.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===me.source&&!/^https?:\/\//i.test(r))return void n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});const o=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=o.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Me=i("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ne.init(e,t)}),We=i("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=oe),Ne.init(e,t)}),He=i("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Q),Ne.init(e,t)}),Ve=i("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ee),Ne.init(e,t)}),Ke=i("$ZodULID",(e,t)=>{t.pattern??(t.pattern=te),Ne.init(e,t)}),Be=i("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ne),Ne.init(e,t)}),qe=i("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=re),Ne.init(e,t)}),Ge=i("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=ye({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${_e}T(?:${r})$`)}(t)),Ne.init(e,t)}),Ye=i("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ve),Ne.init(e,t)}),Xe=i("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${ye(t)}$`)),Ne.init(e,t)}),Qe=i("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ie),Ne.init(e,t)}),et=i("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ue),Ne.init(e,t),e._zod.bag.format="ipv4"}),tt=i("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=de),Ne.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),nt=i("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=pe),Ne.init(e,t)}),rt=i("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=le),Ne.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ot(e){if(""===e)return!0;if(/\s/.test(e))return!1;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const it=i("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=he),Ne.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ot(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});const st=i("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=fe),Ne.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!fe.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return ot(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),at=i("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ge),Ne.init(e,t)});const ct=i("$ZodJWT",(e,t)=>{Ne.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&"JWT"!==o?.typ||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),ut=i("$ZodUnknown",(e,t)=>{Re.init(e,t),e._zod.parse=e=>e}),dt=i("$ZodNever",(e,t)=>{Re.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function pt(e,t,n){e.issues.length&&t.issues.push(...P(n,e.issues)),t.value[n]=e.value}const lt=i("$ZodArray",(e,t)=>{Re.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let e=0;e<o.length;e++){const s=o[e],a=t.element._zod.run({value:s,issues:[]},r);a instanceof Promise?i.push(a.then(t=>pt(t,n,e))):pt(a,n,e)}return i.length?Promise.all(i).then(()=>n):n}});function ht(e,t,n,r,o,i){const s=n in r;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...P(n,e.issues))}s||o?void 0===e.value?s&&(t.value[n]=void 0):t.value[n]=e.value:e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]})}function ft(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function mt(e,t,n,r,o,i){const s=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d="optional"===c.optin,p="optional"===c.optout;for(const o in t){if("__proto__"===o)continue;if(a.has(o))continue;if("never"===u){s.push(o);continue}const i=c.run({value:t[o],issues:[]},r);i instanceof Promise?e.push(i.then(e=>ht(e,n,o,t,d,p))):ht(i,n,o,t,d,p)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const gt=i("$ZodObject",(e,t)=>{Re.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const r=l(()=>ft(t));g(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n});const o=z,i=t.catchall;let s;e._zod.parse=(t,n)=>{s??(s=r.value);const a=t.value;if(!o(a))return t.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),t;t.value={};const c=[],u=s.shape;for(const e of s.keys){const r=u[e],o="optional"===r._zod.optin,i="optional"===r._zod.optout,s=r._zod.run({value:a[e],issues:[]},n);s instanceof Promise?c.push(s.then(n=>ht(n,t,e,a,o,i))):ht(s,t,e,a,o,i)}return i?mt(c,a,t,n,r.value,e):c.length?Promise.all(c).then(()=>t):t}}),_t=i("$ZodObjectJIT",(e,t)=>{gt.init(e,t);const n=e._zod.parse,r=l(()=>ft(t));let o;const i=z,s=!c.jitless,a=s&&b.value,u=t.catchall;let d;e._zod.parse=(c,p)=>{d??(d=r.value);const l=c.value;return i(l)?s&&a&&!1===p?.async&&!0!==p.jitless?(o||(o=(e=>{const t=new je(["shape","payload","ctx"]),n=r.value,o=e=>{const t=y(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=Object.create(null);let s=0;for(const e of n.keys)i[e]="key_"+s++;t.write("const newResult = {};");for(const r of n.keys){const n=i[r],s=y(r),a=e[r],c="optional"===a?._zod?.optin,u="optional"===a?._zod?.optout;t.write(`const ${n} = ${o(r)};`),c&&u?t.write(`\n if (${n}.issues.length) {\n if (${s} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `):c?t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `):t.write(`\n const ${n}_present = ${s} in input;\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n if (!${n}_present && !${n}.issues.length) {\n payload.issues.push({\n code: "invalid_type",\n expected: "nonoptional",\n input: undefined,\n path: [${s}]\n });\n }\n\n if (${n}_present) {\n if (${n}.value === undefined) {\n newResult[${s}] = undefined;\n } else {\n newResult[${s}] = ${n}.value;\n }\n }\n\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,n)=>a(e,t,n)})(t.shape)),c=o(c,p),u?mt([],l,c,p,d,e):c):n(c,p):(c.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),c)}});function vt(e,t,n,r){for(const n of e)if(0===n.issues.length)return t.value=n.value,t;const o=e.filter(e=>!A(e));return 1===o.length?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>I(e,r,u())))}),t)}const yt=i("$ZodUnion",(e,t)=>{Re.init(e,t),g(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),g(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),g(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),g(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>f(e.source)).join("|")})$`)}});const n=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let i=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},o);if(t instanceof Promise)s.push(t),i=!0;else{if(0===t.issues.length)return t;s.push(t)}}return i?Promise.all(s).then(t=>vt(t,r,e,o)):vt(s,r,e,o)}}),wt=i("$ZodIntersection",(e,t)=>{Re.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,o=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([t,n])=>bt(e,t,n)):bt(e,o,i)}});function zt(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(k(e)&&k(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),o={...e,...t};for(const n of r){const r=zt(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};o[n]=r.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=zt(e[r],t[r]);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function bt(e,t,n){const r=new Map;let o;for(const n of t.issues)if("unrecognized_keys"===n.code){o??(o=n);for(const e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(const t of n.issues)if("unrecognized_keys"===t.code)for(const e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);const i=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(i.length&&o&&e.issues.push({...o,keys:i}),A(e))return e;const s=zt(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const kt=i("$ZodEnum",(e,t)=>{Re.init(e,t);const n=d(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>$.has(typeof e)).map(e=>"string"==typeof e?S(e):e.toString()).join("|")})$`),e._zod.parse=(t,o)=>{const i=t.value;return r.has(i)||t.issues.push({code:"invalid_value",values:n,input:i,inst:e}),t}}),Ot=i("$ZodLiteral",(e,t)=>{if(Re.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?S(e):e?S(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,o)=>{const i=r.value;return n.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),$t=i("$ZodTransform",(e,t)=>{Re.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new a(e.constructor.name);const o=t.transform(n.value,n);if(r.async){return(o instanceof Promise?o:Promise.resolve(o)).then(e=>(n.value=e,n.fallback=!0,n))}if(o instanceof Promise)throw new s;return n.value=o,n.fallback=!0,n}});function St(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Et=i("$ZodOptional",(e,t)=>{Re.init(e,t),e._zod.optin="optional",e._zod.optout="optional",g(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),g(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${f(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=e.value,o=t.innerType._zod.run(e,n);return o instanceof Promise?o.then(e=>St(e,r)):St(o,r)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Zt=i("$ZodExactOptional",(e,t)=>{Et.init(e,t),g(e._zod,"values",()=>t.innerType._zod.values),g(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),At=i("$ZodNullable",(e,t)=>{Re.init(e,t),g(e._zod,"optin",()=>t.innerType._zod.optin),g(e._zod,"optout",()=>t.innerType._zod.optout),g(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${f(e.source)}|null)$`):void 0}),g(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),xt=i("$ZodDefault",(e,t)=>{Re.init(e,t),e._zod.optin="optional",g(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Pt(e,t)):Pt(r,t)}});function Pt(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const Tt=i("$ZodPrefault",(e,t)=>{Re.init(e,t),e._zod.optin="optional",g(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),It=i("$ZodNonOptional",(e,t)=>{Re.init(e,t),g(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(t=>jt(t,e)):jt(o,e)}});function jt(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Ct=i("$ZodCatch",(e,t)=>{Re.init(e,t),e._zod.optin="optional",g(e._zod,"optout",()=>t.innerType._zod.optout),g(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>I(e,n,u()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>I(e,n,u()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Rt=i("$ZodPipe",(e,t)=>{Re.init(e,t),g(e._zod,"values",()=>t.in._zod.values),g(e._zod,"optin",()=>t.in._zod.optin),g(e._zod,"optout",()=>t.out._zod.optout),g(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Ut(e,t.in,n)):Ut(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Ut(e,t.out,n)):Ut(r,t.out,n)}});function Ut(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const Nt=i("$ZodReadonly",(e,t)=>{Re.init(e,t),g(e._zod,"propValues",()=>t.innerType._zod.propValues),g(e._zod,"values",()=>t.innerType._zod.values),g(e._zod,"optin",()=>t.innerType?._zod?.optin),g(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Lt):Lt(r)}});function Lt(e){return e.value=Object.freeze(e.value),e}const Dt=i("$ZodCustom",(e,t)=>{be.init(e,t),Re.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(t=>Jt(t,n,r,e));Jt(o,n,r,e)}});function Jt(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(C(e))}}var Ft;class Mt{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}(Ft=globalThis).__zod_globalRegistry??(Ft.__zod_globalRegistry=new Mt);const Wt=globalThis.__zod_globalRegistry;function Ht(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Z(t)})}function Vt(e,t){return new ke({check:"max_length",...Z(t),maximum:e})}function Kt(e,t){return new Oe({check:"min_length",...Z(t),minimum:e})}function Bt(e,t){return new $e({check:"length_equals",...Z(t),length:e})}function qt(e){return new Ie({check:"overwrite",tx:e})}function Gt(e,t){const n=function(e,t){const n=new be({check:"custom",...Z(t)});return n._zod.check=e,n}(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(C(e,t.value,n._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=t.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),t.issues.push(C(r))}},e(t.value,t)),t);return n}function Yt(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Wt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Xt(e,t,n={path:[],schemaPath:[]}){var r;const o=e._zod.def,i=t.seen.get(e);if(i){i.count++;return n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema}const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,r);else{const n=s.schema,i=t.processors[o.type];if(!i)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);i(e,t,n,r)}const i=e._zod.parent;i&&(s.ref||(s.ref=i),Xt(i,t,r),t.seen.get(i).isParent=!0)}const c=t.metadataRegistry.get(e);c&&Object.assign(s.schema,c),"input"===t.io&&tn(e)&&(delete s.schema.examples,delete s.schema.default),"input"===t.io&&"_prefault"in s.schema&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault;return t.seen.get(e).schema}function Qt(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=r.get(n);if(e&&e!==t[0])throw new Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}const o=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:o,defId:i}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,o=e.external.uri??(e=>e);if(n)return{ref:o(n)};const i=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=i,{defId:i,ref:`${o("__shared")}#/${r}/${i}`}}if(t[1]===n)return{ref:"#"};const o=`#/${r}/`,i=t[1].schema.id??"__schema"+e.counter++;return{defId:i,ref:o+i}})(t);r.def={...r.schema},i&&(r.defId=i);const s=r.schema;for(const e in s)delete s[e];s.$ref=o};if("throw"===e.cycles)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const n of e.seen.entries()){const r=n[1];if(t===n[0]){o(n);continue}if(e.external){const r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){o(n);continue}}const i=e.metadataRegistry.get(n[0])?.id;i?o(n):(r.cycle||r.count>1&&"ref"===e.reused)&&o(n)}}function en(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const o=n.def??n.schema,i={...o},s=n.ref;if(n.ref=null,s){r(s);const n=e.seen.get(s),a=n.schema;!a.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(o,a):(o.allOf=o.allOf??[],o.allOf.push(a)),Object.assign(o,i);if(t._zod.parent===s)for(const e in o)"$ref"!==e&&"allOf"!==e&&(e in i||delete o[e]);if(a.$ref&&n.def)for(const e in o)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(o[e])===JSON.stringify(n.def[e])&&delete o[e]}const a=t._zod.parent;if(a&&a!==s){r(a);const t=e.seen.get(a);if(t?.schema.$ref&&(o.$ref=t.schema.$ref,t.def))for(const e in o)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(o[e])===JSON.stringify(t.def[e])&&delete o[e]}e.override({zodSchema:t,jsonSchema:o,path:n.path??[]})};for(const t of[...e.seen.entries()].reverse())r(t[0]);const o={};if("draft-2020-12"===e.target?o.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?o.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(n)}Object.assign(o,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;void 0!==i&&o.id===i&&delete o.id;const s=e.external?.defs??{};for(const t of e.seen.entries()){const e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,s[e.defId]=e.def)}e.external||Object.keys(s).length>0&&("draft-2020-12"===e.target?o.$defs=s:o.definitions=s);try{const n=JSON.parse(JSON.stringify(o));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:nn(t,"input",e.processors),output:nn(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw new Error("Error converting schema to JSON.")}}function tn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return tn(r.element,n);if("set"===r.type)return tn(r.valueType,n);if("lazy"===r.type)return tn(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return tn(r.innerType,n);if("intersection"===r.type)return tn(r.left,n)||tn(r.right,n);if("record"===r.type||"map"===r.type)return tn(r.keyType,n)||tn(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(tn(r.in,n)||tn(r.out,n));if("object"===r.type){for(const e in r.shape)if(tn(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(tn(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(tn(e,n))return!0;return!(!r.rest||!tn(r.rest,n))}return!1}const nn=(e,t,n={})=>r=>{const{libraryOptions:o,target:i}=r??{},s=Yt({...o??{},target:i,io:t,processors:n});return Xt(e,s),Qt(s,e),en(s,e)},rn={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},on=(e,t,n,r)=>{const o=e._zod.def;Xt(o.innerType,t,r);t.seen.get(e).ref=o.innerType},sn=i("ZodISODateTime",(e,t)=>{Ge.init(e,t),jn.init(e,t)});function an(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Z(t)})}(sn,e)}const cn=i("ZodISODate",(e,t)=>{Ye.init(e,t),jn.init(e,t)});function un(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...Z(t)})}(cn,e)}const dn=i("ZodISOTime",(e,t)=>{Xe.init(e,t),jn.init(e,t)});function pn(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Z(t)})}(dn,e)}const ln=i("ZodISODuration",(e,t)=>{Qe.init(e,t),jn.init(e,t)});function hn(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...Z(t)})}(ln,e)}const fn=(e,t)=>{U.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=(e,o=[])=>{for(const i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map(e=>r({issues:e},[...o,...i.path]));else if("invalid_key"===i.code)r({issues:i.issues},[...o,...i.path]);else if("invalid_element"===i.code)r({issues:i.issues},[...o,...i.path]);else{const e=[...o,...i.path];if(0===e.length)n._errors.push(t(i));else{let r=n,o=0;for(;o<e.length;){const n=e[o];o===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(i))):r[n]=r[n]||{_errors:[]},r=r[n],o++}}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,p,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,p,2)}},isEmpty:{get:()=>0===e.issues.length}})},mn=i("ZodError",fn,{Parent:Error}),gn=L(mn),_n=D(mn),vn=J(mn),yn=M(mn),wn=H(mn),zn=V(mn),bn=K(mn),kn=B(mn),On=q(mn),$n=G(mn),Sn=Y(mn),En=X(mn),Zn=new WeakMap;function An(e,t,n){const r=Object.getPrototypeOf(e);let o=Zn.get(r);if(o||(o=new Set,Zn.set(r,o)),!o.has(t)){o.add(t);for(const e in n){const t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){const n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}const xn=i("ZodType",(e,t)=>(Re.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:nn(e,"input"),output:nn(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=Yt({...n,processors:t});return Xt(e,r),Qt(r,e),en(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>gn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>vn(e,t,n),e.parseAsync=async(t,n)=>_n(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>yn(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>wn(e,t,n),e.decode=(t,n)=>zn(e,t,n),e.encodeAsync=async(t,n)=>bn(e,t,n),e.decodeAsync=async(t,n)=>kn(e,t,n),e.safeEncode=(t,n)=>On(e,t,n),e.safeDecode=(t,n)=>$n(e,t,n),e.safeEncodeAsync=async(t,n)=>Sn(e,t,n),e.safeDecodeAsync=async(t,n)=>En(e,t,n),An(e,"ZodType",{check(...e){const t=this.def;return this.clone(v(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return E(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Z(n)})}(Er,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return Gt(e,t)}(e,t))},overwrite(e){return this.check(qt(e))},optional(){return gr(this)},exactOptional(){return new _r({type:"optional",innerType:this})},nullable(){return yr(this)},nullish(){return gr(yr(this))},nonoptional(e){return function(e,t){return new br({type:"nonoptional",innerType:e,...Z(t)})}(this,e)},array(){return ir(this)},or(e){return new cr({type:"union",options:[this,e],...Z(t)});var t},and(e){return new ur({type:"intersection",left:this,right:e})},transform(e){return $r(this,new fr({type:"transform",transform:e}))},default(e){return t=e,new wr({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():O(t)}});var t},prefault(e){return t=e,new zr({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():O(t)}});var t},catch(e){return new kr({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:()=>t});var t},pipe(e){return $r(this,e)},readonly(){return new Sr({type:"readonly",innerType:this})},describe(e){const t=this.clone();return Wt.add(t,{description:e}),t},meta(...e){if(0===e.length)return Wt.get(this);const t=this.clone();return Wt.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get:()=>Wt.get(e)?.description,configurable:!0}),e)),Pn=i("_ZodString",(e,t)=>{Ue.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:o,maximum:i,format:s,patterns:a,contentEncoding:c}=e._zod.bag;if("number"==typeof o&&(r.minLength=o),"number"==typeof i&&(r.maxLength=i),s&&(r.format=rn[s]??s,""===r.format&&delete r.format,"time"===s&&delete r.format),c&&(r.contentEncoding=c),a&&a.size>0){const e=[...a];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,An(e,"_ZodString",{regex(...e){return this.check(function(e,t){return new Ee({check:"string_format",format:"regex",...Z(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new xe({check:"string_format",format:"includes",...Z(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new Pe({check:"string_format",format:"starts_with",...Z(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new Te({check:"string_format",format:"ends_with",...Z(t),suffix:e})}(...e))},min(...e){return this.check(Kt(...e))},max(...e){return this.check(Vt(...e))},length(...e){return this.check(Bt(...e))},nonempty(...e){return this.check(Kt(1,...e))},lowercase(e){return this.check(function(e){return new Ze({check:"string_format",format:"lowercase",...Z(e)})}(e))},uppercase(e){return this.check(function(e){return new Ae({check:"string_format",format:"uppercase",...Z(e)})}(e))},trim(){return this.check(qt(e=>e.trim()))},normalize(...e){return this.check(function(e){return qt(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(qt(e=>e.toLowerCase()))},toUpperCase(){return this.check(qt(e=>e.toUpperCase()))},slugify(){return this.check(qt(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})}),Tn=i("ZodString",(e,t)=>{Ue.init(e,t),Pn.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Z(t)})}(Cn,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Z(t)})}(Nn,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Z(t)})}(Qn,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Z(t)})}(Ln,t)),e.guid=t=>e.check(Ht(Rn,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Z(t)})}(Un,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Z(t)})}(Un,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Z(t)})}(Un,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Z(t)})}(Un,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Z(t)})}(Dn,t)),e.guid=t=>e.check(Ht(Rn,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Z(t)})}(Jn,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Z(t)})}(Fn,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Z(t)})}(Mn,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Z(t)})}(Gn,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Z(t)})}(Yn,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Z(t)})}(Wn,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Z(t)})}(Hn,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Z(t)})}(Vn,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Z(t)})}(Kn,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Z(t)})}(Bn,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Z(t)})}(qn,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Z(t)})}(Xn,t)),e.datetime=t=>e.check(an(t)),e.date=t=>e.check(un(t)),e.time=t=>e.check(pn(t)),e.duration=t=>e.check(hn(t))});function In(e){return function(e,t){return new e({type:"string",...Z(t)})}(Tn,e)}const jn=i("ZodStringFormat",(e,t)=>{Ne.init(e,t),Pn.init(e,t)}),Cn=i("ZodEmail",(e,t)=>{Je.init(e,t),jn.init(e,t)}),Rn=i("ZodGUID",(e,t)=>{Le.init(e,t),jn.init(e,t)}),Un=i("ZodUUID",(e,t)=>{De.init(e,t),jn.init(e,t)}),Nn=i("ZodURL",(e,t)=>{Fe.init(e,t),jn.init(e,t)}),Ln=i("ZodEmoji",(e,t)=>{Me.init(e,t),jn.init(e,t)}),Dn=i("ZodNanoID",(e,t)=>{We.init(e,t),jn.init(e,t)}),Jn=i("ZodCUID",(e,t)=>{He.init(e,t),jn.init(e,t)}),Fn=i("ZodCUID2",(e,t)=>{Ve.init(e,t),jn.init(e,t)}),Mn=i("ZodULID",(e,t)=>{Ke.init(e,t),jn.init(e,t)}),Wn=i("ZodXID",(e,t)=>{Be.init(e,t),jn.init(e,t)}),Hn=i("ZodKSUID",(e,t)=>{qe.init(e,t),jn.init(e,t)}),Vn=i("ZodIPv4",(e,t)=>{et.init(e,t),jn.init(e,t)}),Kn=i("ZodIPv6",(e,t)=>{tt.init(e,t),jn.init(e,t)}),Bn=i("ZodCIDRv4",(e,t)=>{nt.init(e,t),jn.init(e,t)}),qn=i("ZodCIDRv6",(e,t)=>{rt.init(e,t),jn.init(e,t)}),Gn=i("ZodBase64",(e,t)=>{it.init(e,t),jn.init(e,t)}),Yn=i("ZodBase64URL",(e,t)=>{st.init(e,t),jn.init(e,t)}),Xn=i("ZodE164",(e,t)=>{at.init(e,t),jn.init(e,t)}),Qn=i("ZodJWT",(e,t)=>{ct.init(e,t),jn.init(e,t)}),er=i("ZodUnknown",(e,t)=>{ut.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function tr(){return new er({type:"unknown"})}const nr=i("ZodNever",(e,t)=>{dt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function rr(e){return function(e,t){return new e({type:"never",...Z(t)})}(nr,e)}const or=i("ZodArray",(e,t)=>{lt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;"number"==typeof s&&(o.minItems=s),"number"==typeof a&&(o.maxItems=a),o.type="array",o.items=Xt(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,An(e,"ZodArray",{min(e,t){return this.check(Kt(e,t))},nonempty(e){return this.check(Kt(1,e))},max(e,t){return this.check(Vt(e,t))},length(e,t){return this.check(Bt(e,t))},unwrap(){return this.element}})});function ir(e,t){return function(e,t,n){return new e({type:"array",element:t,...Z(n)})}(or,e,t)}const sr=i("ZodObject",(e,t)=>{_t.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object",o.properties={};const s=i.shape;for(const e in s)o.properties[e]=Xt(s[e],t,{...r,path:[...r.path,"properties",e]});const a=new Set(Object.keys(s)),c=new Set([...a].filter(e=>{const n=i.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(o.required=Array.from(c)),"never"===i.catchall?._zod.def.type?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=Xt(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),g(e,"shape",()=>t.shape),An(e,"ZodObject",{keyof(){return pr(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:tr()})},loose(){return this.clone({...this._zod.def,catchall:tr()})},strict(){return this.clone({...this._zod.def,catchall:rr()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return function(e,t){if(!k(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=v(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return _(this,"shape",n),n}});return E(e,r)}(this,e)},safeExtend(e){return function(e,t){if(!k(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=v(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return _(this,"shape",n),n}});return E(e,n)}(this,e)},merge(e){return function(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=v(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return _(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return E(e,n)}(this,e)},pick(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return E(e,v(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return _(this,"shape",e),e},checks:[]}))}(this,e)},omit(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const o=v(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return _(this,"shape",r),r},checks:[]});return E(e,o)}(this,e)},partial(...e){return function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const o=v(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)o[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return _(this,"shape",o),o},checks:[]});return E(t,o)}(mr,this,e[0])},required(...e){return function(e,t,n){const r=v(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in o))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)o[t]=new e({type:"nonoptional",innerType:r[t]});return _(this,"shape",o),o}});return E(t,r)}(br,this,e[0])}})});function ar(e,t){const n={type:"object",shape:e??{},...Z(t)};return new sr(n)}const cr=i("ZodUnion",(e,t)=>{yt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=!1===o.inclusive,s=o.options.map((e,n)=>Xt(e,t,{...r,path:[...r.path,i?"oneOf":"anyOf",n]}));i?n.oneOf=s:n.anyOf=s})(e,t,n,r),e.options=t.options});const ur=i("ZodIntersection",(e,t)=>{wt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Xt(o.left,t,{...r,path:[...r.path,"allOf",0]}),s=Xt(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=c})(e,t,n,r)});const dr=i("ZodEnum",(e,t)=>{kt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=d(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const o={};for(const r of e){if(!n.has(r))throw new Error(`Key ${r} not found in enum`);o[r]=t.entries[r]}return new dr({...t,checks:[],...Z(r),entries:o})},e.exclude=(e,r)=>{const o={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete o[t]}return new dr({...t,checks:[],...Z(r),entries:o})}});function pr(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new dr({type:"enum",entries:n,...Z(t)})}const lr=i("ZodLiteral",(e,t)=>{Ot.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=e._zod.def,o=[];for(const e of r.values)if(void 0===e){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(e))}else o.push(e);if(0===o.length);else if(1===o.length){const e=o[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else o.every(e=>"number"==typeof e)&&(n.type="number"),o.every(e=>"string"==typeof e)&&(n.type="string"),o.every(e=>"boolean"==typeof e)&&(n.type="boolean"),o.every(e=>null===e)&&(n.type="null"),n.enum=o})(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function hr(e,t){return new lr({type:"literal",values:Array.isArray(e)?e:[e],...Z(t)})}const fr=i("ZodTransform",(e,t)=>{$t.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new a(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(C(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(C(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});const mr=i("ZodOptional",(e,t)=>{Et.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>on(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function gr(e){return new mr({type:"optional",innerType:e})}const _r=i("ZodExactOptional",(e,t)=>{Zt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>on(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});const vr=i("ZodNullable",(e,t)=>{At.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Xt(o.innerType,t,r),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function yr(e){return new vr({type:"nullable",innerType:e})}const wr=i("ZodDefault",(e,t)=>{xt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Xt(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});const zr=i("ZodPrefault",(e,t)=>{Tt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Xt(o.innerType,t,r),t.seen.get(e).ref=o.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});const br=i("ZodNonOptional",(e,t)=>{It.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Xt(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});const kr=i("ZodCatch",(e,t)=>{Ct.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;Xt(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});const Or=i("ZodPipe",(e,t)=>{Rt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s="input"===t.io?i?o.out:o.in:o.out;Xt(s,t,r),t.seen.get(e).ref=s})(e,t,0,r),e.in=t.in,e.out=t.out});function $r(e,t){return new Or({type:"pipe",in:e,out:t})}const Sr=i("ZodReadonly",(e,t)=>{Nt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Xt(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});const Er=i("ZodCustom",(e,t)=>{Dt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)});function Zr(){const e=navigator.userAgent||navigator.vendor||window.opera||"",t=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(e),n="ontouchstart"in window||navigator.maxTouchPoints>0||(navigator.msMaxTouchPoints??0)>0,r=window.innerWidth<=768;return t||n&&r}function Ar(){return Zr()&&window.innerWidth<=480?"phone":Zr()&&window.innerWidth>480&&window.innerWidth<=1024?"tablet":"desktop"}function xr(e){return"pending"===e?"pending":"error"===e?"error":"active"}const Pr=In().min(1),Tr=ar({account_display_name:In().optional(),account_email:In().optional()}).catchall(tr()),Ir=ar({grant_id:Pr,provider:Pr,provider_name:In().optional(),account_identifier:In().optional(),timestamp:In().optional(),operation:pr(["creation","reauth"]).optional().default("creation"),scopes:ir(In()).optional().default([]),status:pr(["active","pending","error"]).optional().default("active"),metadata:Tr.optional()}).transform(e=>{const t={grant_id:e.grant_id,provider:e.provider,provider_name:e.provider_name??e.provider,account_identifier:e.account_identifier??"",timestamp:e.timestamp??(new Date).toISOString(),operation:e.operation,scopes:e.scopes,status:e.status};return void 0!==e.metadata&&(t.metadata=e.metadata),t}),jr=ar({provider_id:Pr,reason:Pr,message:Pr}).transform(e=>({providerId:e.provider_id,reason:e.reason,message:e.message})),Cr=ar({type:pr(["alter_connect_success","alter_connect_error"])}),Rr=ar({type:hr("alter_connect_success"),grants:ir(Ir),failed_grants:ir(jr).optional().default([])}),Ur=ar({type:hr("alter_connect_error"),error:In().catch("oauth_error"),error_description:In().catch("OAuth authorization failed")}).loose();function Nr(e){const t=e.issues[0]?.path[0];return"failed_grants"===t?"Server returned malformed failed_grants data":"grants"===t&&1===e.issues[0]?.path.length?"Server returned success without grants array":"Server returned malformed grant data"}function Lr(e){sessionStorage.removeItem("alter_oauth_state");try{const t=new URL(e);window.history.replaceState({},document.title,t.pathname+t.search+t.hash)}catch{window.history.replaceState({},document.title,window.location.pathname)}}class Dr{constructor(t){this.popup=null,this.pollInterval=null,this.messageListener=null,this.settled=!1,this.options={baseURL:t.baseURL,onSuccess:t.onSuccess,onError:t.onError,onCancel:t.onCancel,popupWidth:t.popupWidth||500,popupHeight:t.popupHeight||700,debug:t.debug||!1,expectedOrigin:t.expectedOrigin||""};try{this.expectedOrigin=new URL(t.baseURL).origin}catch{throw new Error(`Invalid baseURL: "${t.baseURL}". Must be a full URL with protocol (e.g., "${e}").`)}}startOAuth(e){if(!this.options.expectedOrigin)try{const t=new URL(e);this.options.expectedOrigin=t.origin,this.log("Derived expected origin:",this.options.expectedOrigin)}catch{return this.log("Failed to parse OAuth URL for origin validation:",e),void this.options.onError({code:"invalid_oauth_url",message:"Failed to determine origin from OAuth URL. Cannot proceed securely."})}!function(){const e=Ar();return"phone"===e||"tablet"===e&&window.innerHeight>window.innerWidth}()?(this.log("Using popup flow for desktop"),this.openPopup(e)):(this.log("Using redirect flow for mobile device"),this.startRedirectFlow(e))}startRedirectFlow(e){this.log("Starting redirect flow:",e);const t={timestamp:Date.now(),returnUrl:window.location.href};try{sessionStorage.setItem("alter_oauth_state",JSON.stringify(t))}catch(e){return this.log("Failed to save state:",e),void this.options.onError({code:"redirect_error",message:"Failed to start OAuth flow: could not save session state",details:{error:e}})}window.location.href=e}static checkOAuthReturn(e,t){const n=sessionStorage.getItem("alter_oauth_state");if(!n)return!1;try{const o=JSON.parse(n);if(Date.now()-o.timestamp>3e5)return sessionStorage.removeItem("alter_oauth_state"),!1;const i=new URLSearchParams(window.location.search),s=i.get("alter_connect_success"),a=i.get("alter_connect_error");if("true"===s){const n=i.get("grant_id"),s=i.get("provider"),a=i.get("account_identifier");if(!n||!s||!a)return Lr(o.returnUrl),t({code:"invalid_response",message:"OAuth redirect returned incomplete grant data"}),!0;const c={grant_id:n,provider:s,provider_name:i.get("provider_name")||s,account_identifier:a,timestamp:i.get("timestamp")||(new Date).toISOString(),operation:(r=i.get("operation"),"reauth"===r?"reauth":"creation"),scopes:i.get("scopes")?.split(",")||[],status:xr(i.get("status"))};Lr(o.returnUrl);const u=[c];return e(u,{grants:u,failedGrants:[]}),!0}if(a){const e={code:i.get("error_code")||"oauth_error",message:i.get("error_description")||"OAuth authorization failed"};return Lr(o.returnUrl),t(e),!0}return!1}catch(e){return console.error("[OAuth Handler] Failed to check OAuth return:",e),sessionStorage.removeItem("alter_oauth_state"),!1}var r}openPopup(e){const t=window.screenX+(window.outerWidth-this.options.popupWidth)/2,n=window.screenY+(window.outerHeight-this.options.popupHeight)/2,r=[`width=${this.options.popupWidth}`,`height=${this.options.popupHeight}`,`left=${t}`,`top=${n}`,"resizable=yes","scrollbars=yes","status=yes"].join(",");this.log("Opening OAuth popup:",e),this.popup=window.open(e,"alter_oauth_popup",r),this.popup?(this.startPolling(),this.setupMessageListener()):this.options.onError({code:"popup_blocked",message:"Popup was blocked by browser. Please allow popups for this site."})}close(){this.log("Closing OAuth handler"),this.popup&&!this.popup.closed&&this.popup.close(),this.popup=null,null!==this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null)}startPolling(){this.pollInterval=window.setInterval(()=>{this.settled||this.popup&&!this.popup.closed||(this.log("Popup closed by user"),this.settled=!0,this.close(),this.options.onCancel())},500)}setupMessageListener(){this.messageListener=e=>{if(this.settled)return;if(e.origin!==this.expectedOrigin)return void this.log("Rejected message from unexpected origin:",e.origin,"(expected:",this.expectedOrigin+")");this.log("Received message from",e.origin);const t=Cr.safeParse(e.data);if(!t.success)return;if("alter_connect_success"===t.data.type){this.log("OAuth success");const t=Rr.safeParse(e.data);if(!t.success)return this.settled=!0,this.close(),void this.options.onError({code:"invalid_response",message:Nr(t.error)});const{grants:n,failed_grants:r}=t.data;if(this.log("Connect completion:",n.length,"grants"),0===n.length)return this.settled=!0,this.close(),void(r.length>0?this.options.onError({code:"grant_policy_application_failed",message:"The connection was not completed because the selected usage limits could not be applied.",failedGrants:r}):this.options.onError({code:"invalid_response",message:"Server returned empty grants array"}));const o={grants:n,failedGrants:r};return this.settled=!0,this.close(),void this.options.onSuccess(n,o)}const n=Ur.safeParse(e.data);if(n.success){this.log("OAuth error");const e={code:n.data.error,message:n.data.error_description,details:n.data};this.settled=!0,this.close(),this.options.onError(e)}},window.addEventListener("message",this.messageListener)}log(...e){this.options.debug&&console.log("[OAuth Handler]",...e)}}const Jr="0.2.0";let Fr=!1;class Mr{constructor(o={}){if(this._oauthHandler=null,this._perOpenCleanups=[],function(e){if(void 0!==e.baseURL)throw e.baseURL,new Error("AlterConnectConfig.baseURL is reserved and not yet supported. Omit the field to use the production Alter host.")}(o),this.config=function(e){return{debug:e.debug??!1}}(o),this._baseURL=(o.baseURL??e).replace(/\/+$/,""),this._baseURL!==e&&!Fr){Fr=!0;const e=new URL(this._baseURL).origin;console.warn(`[alter-connect] Using non-default Alter host: ${e}. Unset baseURL in AlterConnect.create() for production.`)}this.eventEmitter=new n,this.stateManager=new r,this._isInitialized=!0,t(this.config,"Alter Connect SDK initialized",{version:Jr,baseURL:this._baseURL}),this.checkRedirectReturn()}checkRedirectReturn(){Dr.checkOAuthReturn((e,n)=>{t(this.config,"OAuth redirect return - success:",e),this.eventEmitter.emit("success",e,n)},e=>{t(this.config,"OAuth redirect return - error:",e),this.eventEmitter.emit("error",e)})&&t(this.config,"OAuth redirect return detected and handled")}static create(e){return new Mr(e)}async open(e){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call open() - SDK instance has been destroyed");if(t(this.config,"Opening Connect UI"),!e.token||"string"!=typeof e.token)throw this.createError("invalid_options","Session token is required. Create one from the application backend with an Alter SDK.");if(!e.onSuccess||"function"!=typeof e.onSuccess)throw this.createError("invalid_options","onSuccess callback is required");if(this.isOpen())return void t(this.config,"Connect UI is already open");this._oauthHandler=new Dr({baseURL:this._baseURL,onSuccess:(e,n)=>{t(this.config,"OAuth success:",e),this.handleOAuthSuccess(e,n)},onError:e=>{t(this.config,"OAuth error:",e),this.handleOAuthError(e)},onCancel:()=>{t(this.config,"OAuth cancelled (popup closed)"),this.handleOAuthCancel()},popupWidth:500,popupHeight:700,debug:this.config.debug}),this.stateManager.setState({isOpen:!0,error:null,sessionToken:e.token}),this.registerEventHandlers(e);const n=`${this._baseURL}/sdk/oauth/connect#session=${encodeURIComponent(e.token)}`;t(this.config,"Connect URL:",n),this._oauthHandler.startOAuth(n),e.onEvent&&e.onEvent("connect_opened",{timestamp:(new Date).toISOString()}),t(this.config,"Connect UI opened successfully")}close(){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call close() - SDK instance has been destroyed");t(this.config,"Closing Connect UI"),this._oauthHandler&&(this._oauthHandler.close(),this._oauthHandler=null),this._perOpenCleanups.forEach(e=>e()),this._perOpenCleanups=[],this.stateManager.setState({isOpen:!1}),this.eventEmitter.emit("close")}destroy(){this._isInitialized&&(t(this.config,"Destroying SDK instance"),this._oauthHandler&&(this._oauthHandler.close(),this._oauthHandler=null),this.stateManager.get("isOpen")&&this.stateManager.setState({isOpen:!1}),this.eventEmitter.removeAllListeners(),this.stateManager.clearListeners(),this._isInitialized=!1)}on(e,t){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call on() - SDK instance has been destroyed");return this.eventEmitter.on(e,t)}off(e,t){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call off() - SDK instance has been destroyed");this.eventEmitter.off(e,t)}isOpen(){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call isOpen() - SDK instance has been destroyed");return this.stateManager.get("isOpen")}getVersion(){return Jr}cleanupHandler(){this._oauthHandler=null}handleOAuthSuccess(e,t){this.cleanupHandler(),this.eventEmitter.emit("success",e,t)}handleOAuthError(e){this.cleanupHandler(),this.stateManager.setState({error:e}),this.eventEmitter.emit("error",e)}handleOAuthCancel(){this.cleanupHandler(),this.eventEmitter.emit("exit")}registerEventHandlers(e){e.onSuccess&&this._perOpenCleanups.push(this.eventEmitter.on("success",(t,n)=>{e.onSuccess(t,n),this.close()})),e.onExit&&this._perOpenCleanups.push(this.eventEmitter.on("exit",()=>{e.onExit(),this.close()})),this._perOpenCleanups.push(this.eventEmitter.on("error",t=>{e.onError&&e.onError(t),this.close()})),e.onEvent&&this._perOpenCleanups.push(this.eventEmitter.on("event",(t,n)=>{e.onEvent(t,n)}))}createError(e,t,n){const r=new Error(t);return r.code=e,r.details=n,r}}return Mr});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).AlterConnect=t()}(this,function(){"use strict";const e="https://backend.alterauth.com";function t(e,...t){e.debug&&console.log("[Alter Connect]",...t)}class n{constructor(){this.events=new Map}on(e,t){return this.events.has(e)||this.events.set(e,new Set),this.events.get(e).add(t),()=>this.off(e,t)}off(e,t){const n=this.events.get(e);n&&n.delete(t)}hasListeners(e){const t=this.events.get(e);return void 0!==t&&t.size>0}emit(e,...t){const n=this.events.get(e);n&&n.forEach(n=>{try{n(...t)}catch(t){console.error(`[Alter Connect] Error in event handler for '${e}':`,t)}})}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}}class s{constructor(){this.state={isOpen:!1,sessionToken:null,error:null},this.listeners=new Set}getState(){return{...this.state}}get(e){return this.state[e]}setState(e){this.state={...this.state,...e},this.notifyListeners()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clearListeners(){this.listeners.clear()}notifyListeners(){const e=this.getState();this.listeners.forEach(t=>{try{t(e)}catch(e){console.error("[Alter Connect] Error in state listener:",e)}})}}var r;function o(e,t,n){function s(n,s){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:s,constr:i,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,s);const r=i.prototype,o=Object.keys(r);for(let e=0;e<o.length;e++){const t=o[e];t in n||(n[t]=r[t].bind(n))}}const r=n?.Parent??Object;class o extends r{}function i(e){var t;const r=n?.Parent?new o:this;s(r,e),(t=r._zod).deferred??(t.deferred=[]);for(const e of r._zod.deferred)e();return r}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class i extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class a extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(r=globalThis).__zod_globalConfig??(r.__zod_globalConfig={});const c=globalThis.__zod_globalConfig;function u(e){return c}function l(e,t){return"bigint"==typeof t?t.toString():t}const d=Symbol("evaluating");function h(e,t,n){let s;Object.defineProperty(e,t,{get(){if(s!==d)return void 0===s&&(s=d,s=n()),s},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}const p="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function f(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function g(e){return function(e){if(!1===f(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==f(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const m=new Set(["string","number","symbol"]);function _(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function v(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function y(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!1===e.issues[n]?.continue)return!0;return!1}function w(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function b(e){return"string"==typeof e?e:e?.message}function z(e,t,n){const s=e.message?e.message:b(e.inst?._zod.def?.error?.(e))??b(t?.error?.(e))??b(n.customError?.(e))??b(n.localeError?.(e))??"Invalid input",{inst:r,continue:o,input:i,...a}=e;return a.path??(a.path=[]),a.message=s,t?.reportInput&&(a.input=i),a}const O=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,l,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},E=o("$ZodError",O),S=o("$ZodError",O,{Parent:Error}),k=(e=>(t,n,s,r)=>{const o=s?{...s,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new i;if(a.issues.length){const t=new(r?.Err??e)(a.issues.map(e=>z(e,o,u())));throw p(t,r?.callee),t}return a.value})(S),A=(e=>async(t,n,s,r)=>{const o=s?{...s,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){const t=new(r?.Err??e)(i.issues.map(e=>z(e,o,u())));throw p(t,r?.callee),t}return i.value})(S),P=(e=>(t,n,s)=>{const r=s?{...s,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)throw new i;return o.issues.length?{success:!1,error:new(e??E)(o.issues.map(e=>z(e,r,u())))}:{success:!0,data:o.value}})(S),R=(e=>async(t,n,s)=>{const r=s?{...s,async:!0}:{async:!0};let o=t._zod.run({value:n,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>z(e,r,u())))}:{success:!0,data:o.value}})(S),U=o("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),L=o("$ZodCheckMinLength",(e,t)=>{var n;U.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!(n=t,null==n||void 0===t.length);var n}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const s=n.value;if(s.length>=t.minimum)return;const r=function(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}(s);n.issues.push({origin:r,code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),C={major:4,minor:4,patch:3},$=o("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=C;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const t of s)for(const n of t._zod.onattach)n(e);if(0===s.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let s,r=v(e);for(const o of t){if(o._zod.def.when){if(y(e))continue;if(!o._zod.def.when(e))continue}else if(r)continue;const t=e.issues.length,a=o._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new i;if(s||a instanceof Promise)s=(s??Promise.resolve()).then(async()=>{await a;e.issues.length!==t&&(r||(r=v(e,t)))});else{if(e.issues.length===t)continue;r||(r=v(e,t))}}return s?s.then(()=>e):e},n=(n,r,o)=>{if(v(n))return n.aborted=!0,n;const a=t(r,s,o);if(a instanceof Promise){if(!1===o.async)throw new i;return a.then(t=>e._zod.parse(t,o))}return e._zod.parse(a,o)};e._zod.run=(r,o)=>{if(o.skipChecks)return e._zod.parse(r,o);if("backward"===o.direction){const t=e._zod.parse({value:r.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,o)):n(t,r,o)}const a=e._zod.parse(r,o);if(a instanceof Promise){if(!1===o.async)throw new i;return a.then(e=>t(e,s,o))}return t(a,s,o)}}h(e,"~standard",()=>({validate:t=>{try{const n=P(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return R(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),I=o("$ZodString",(e,t)=>{var n;$.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=String(n.value)}catch(s){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),j=o("$ZodUnknown",(e,t)=>{$.init(e,t),e._zod.parse=e=>e});function T(e,t,n){e.issues.length&&t.issues.push(...w(n,e.issues)),t.value[n]=e.value}const M=o("$ZodArray",(e,t)=>{$.init(e,t),e._zod.parse=(n,s)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const o=[];for(let e=0;e<r.length;e++){const i=r[e],a=t.element._zod.run({value:i,issues:[]},s);a instanceof Promise?o.push(a.then(t=>T(t,n,e))):T(a,n,e)}return o.length?Promise.all(o).then(()=>n):n}});function x(e,t,n,s,r,o){const i=n in s;if(e.issues.length){if(r&&o&&!i)return;t.issues.push(...w(n,e.issues))}i||r?void 0===e.value?i&&(t.value[n]=void 0):t.value[n]=e.value:e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]})}function Z(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(s=e.shape,Object.keys(s).filter(e=>"optional"===s[e]._zod.optin&&"optional"===s[e]._zod.optout));var s;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}const H=o("$ZodObject",(e,t)=>{$.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const s=(r=()=>Z(t),{get value(){{const e=r();return Object.defineProperty(this,"value",{value:e}),e}}});var r;h(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const s=e[t]._zod;if(s.values){n[t]??(n[t]=new Set);for(const e of s.values)n[t].add(e)}}return n});const o=f,i=t.catchall;let a;e._zod.parse=(t,n)=>{a??(a=s.value);const r=t.value;if(!o(r))return t.issues.push({expected:"object",code:"invalid_type",input:r,inst:e}),t;t.value={};const c=[],u=a.shape;for(const e of a.keys){const s=u[e],o="optional"===s._zod.optin,i="optional"===s._zod.optout,a=s._zod.run({value:r[e],issues:[]},n);a instanceof Promise?c.push(a.then(n=>x(n,t,e,r,o,i))):x(a,t,e,r,o,i)}return i?function(e,t,n,s,r,o){const i=[],a=r.keySet,c=r.catchall._zod,u=c.def.type,l="optional"===c.optin,d="optional"===c.optout;for(const r in t){if("__proto__"===r)continue;if(a.has(r))continue;if("never"===u){i.push(r);continue}const o=c.run({value:t[r],issues:[]},s);o instanceof Promise?e.push(o.then(e=>x(e,n,r,t,l,d))):x(o,n,r,t,l,d)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}(c,r,t,n,s.value,e):c.length?Promise.all(c).then(()=>t):t}}),D=o("$ZodEnum",(e,t)=>{$.init(e,t);const n=function(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}(t.entries),s=new Set(n);e._zod.values=s,e._zod.pattern=new RegExp(`^(${n.filter(e=>m.has(typeof e)).map(e=>"string"==typeof e?_(e):e.toString()).join("|")})$`),e._zod.parse=(t,r)=>{const o=t.value;return s.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),W=o("$ZodLiteral",(e,t)=>{if($.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?_(e):e?_(e.toString()):String(e)).join("|")})$`),e._zod.parse=(s,r)=>{const o=s.value;return n.has(o)||s.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),s}}),V=o("$ZodTransform",(e,t)=>{$.init(e,t),e._zod.optin="optional",e._zod.parse=(n,s)=>{if("backward"===s.direction)throw new a(e.constructor.name);const r=t.transform(n.value,n);if(s.async){return(r instanceof Promise?r:Promise.resolve(r)).then(e=>(n.value=e,n.fallback=!0,n))}if(r instanceof Promise)throw new i;return n.value=r,n.fallback=!0,n}});function F(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const K=o("$ZodOptional",(e,t)=>{$.init(e,t),e._zod.optin="optional",e._zod.optout="optional",h(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),h(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${function(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const s=e.value,r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>F(e,s)):F(r,s)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),N=o("$ZodDefault",(e,t)=>{$.init(e,t),e._zod.optin="optional",h(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(e=>G(e,t)):G(s,t)}});function G(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const J=o("$ZodCatch",(e,t)=>{$.init(e,t),e._zod.optin="optional",h(e._zod,"optout",()=>t.innerType._zod.optout),h(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(s=>(e.value=s.value,s.issues.length&&(e.value=t.catchValue({...e,error:{issues:s.issues.map(e=>z(e,n,u()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=s.value,s.issues.length&&(e.value=t.catchValue({...e,error:{issues:s.issues.map(e=>z(e,n,u()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),q=o("$ZodPipe",(e,t)=>{$.init(e,t),h(e._zod,"values",()=>t.in._zod.values),h(e._zod,"optin",()=>t.in._zod.optin),h(e._zod,"optout",()=>t.out._zod.optout),h(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const s=t.out._zod.run(e,n);return s instanceof Promise?s.then(e=>B(e,t.in,n)):B(s,t.in,n)}const s=t.in._zod.run(e,n);return s instanceof Promise?s.then(e=>B(e,t.out,n)):B(s,t.out,n)}});function B(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Y;class X{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const s={...n,...this._map.get(e)};return Object.keys(s).length?s:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}(Y=globalThis).__zod_globalRegistry??(Y.__zod_globalRegistry=new X);const Q=o("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");$.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>k(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>P(e,t,n),e.parseAsync=async(t,n)=>A(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>R(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>function(e,t,n){const s=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(s._zod.parent=e),s}(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.apply=t=>t(e)}),ee=o("ZodMiniString",(e,t)=>{I.init(e,t),Q.init(e,t)});function te(e){return new ee({type:"string"})}const ne=o("ZodMiniUnknown",(e,t)=>{j.init(e,t),Q.init(e,t)});function se(){return new ne({type:"unknown"})}const re=o("ZodMiniArray",(e,t)=>{M.init(e,t),Q.init(e,t)});function oe(e,t){return new re({type:"array",element:e})}const ie=o("ZodMiniObject",(e,t)=>{H.init(e,t),Q.init(e,t),h(e,"shape",()=>t.shape)});function ae(e,t){return new ie({type:"object",shape:e??{}})}const ce=o("ZodMiniEnum",(e,t)=>{D.init(e,t),Q.init(e,t),e.options=Object.values(t.entries)});function ue(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ce({type:"enum",entries:n})}const le=o("ZodMiniLiteral",(e,t)=>{W.init(e,t),Q.init(e,t)});function de(e,t){return new le({type:"literal",values:Array.isArray(e)?e:[e]})}const he=o("ZodMiniTransform",(e,t)=>{V.init(e,t),Q.init(e,t)});function pe(e){return new he({type:"transform",transform:e})}const fe=o("ZodMiniOptional",(e,t)=>{K.init(e,t),Q.init(e,t)});function ge(e){return new fe({type:"optional",innerType:e})}const me=o("ZodMiniDefault",(e,t)=>{N.init(e,t),Q.init(e,t)});function _e(e,t){return new me({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():g(t)}})}const ve=o("ZodMiniCatch",(e,t)=>{J.init(e,t),Q.init(e,t)});function ye(e,t){return new ve({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const we=o("ZodMiniPipe",(e,t)=>{q.init(e,t),Q.init(e,t)});function be(e,t){return new we({type:"pipe",in:e,out:t})}function ze(){const e=navigator.userAgent||navigator.vendor||window.opera||"",t=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(e),n="ontouchstart"in window||navigator.maxTouchPoints>0||(navigator.msMaxTouchPoints??0)>0,s=window.innerWidth<=768;return t||n&&s}function Oe(){return ze()&&window.innerWidth<=480?"phone":ze()&&window.innerWidth>480&&window.innerWidth<=1024?"tablet":"desktop"}function Ee(e){return"pending"===e?"pending":"error"===e?"error":"active"}const Se=te().check(new L({check:"min_length",minimum:1}));const ke=function(e,t){return e.clone({...e._zod.def,catchall:t})}(ae({account_display_name:ge(te()),account_email:ge(te())}),se()),Ae=be(ae({grant_id:Se,provider:Se,provider_name:ge(te()),account_identifier:ge(te()),timestamp:ge(te()),operation:_e(ge(ue(["creation","reauth"])),"creation"),scopes:_e(ge(oe(te())),[]),status:_e(ge(ue(["active","pending","error"])),"active"),metadata:ge(ke)}),pe(e=>{const t={grant_id:e.grant_id,provider:e.provider,provider_name:e.provider_name??e.provider,account_identifier:e.account_identifier??"",timestamp:e.timestamp??(new Date).toISOString(),operation:e.operation,scopes:e.scopes,status:e.status};return void 0!==e.metadata&&(t.metadata=e.metadata),t})),Pe=be(ae({provider_id:Se,reason:Se,message:Se}),pe(e=>({providerId:e.provider_id,reason:e.reason,message:e.message}))),Re=ae({type:ue(["alter_connect_success","alter_connect_error"])}),Ue=ae({type:de("alter_connect_success"),grants:oe(Ae),failed_grants:_e(ge(oe(Pe)),[])}),Le=(Ce={type:de("alter_connect_error"),error:ye(te(),"oauth_error"),error_description:ye(te(),"OAuth authorization failed")},new ie({type:"object",shape:Ce,catchall:se()}));var Ce;function $e(e){const t=e.issues[0]?.path[0];return"failed_grants"===t?"Server returned malformed failed_grants data":"grants"===t&&1===e.issues[0]?.path.length?"Server returned success without grants array":"Server returned malformed grant data"}const Ie="alter_oauth_state",je="alter_connect_nonce",Te=["alter_connect_success","alter_connect_error",je,"grant_id","provider","provider_name","account_identifier","timestamp","operation","scopes","status","error_code","error_message"];function Me(){const e=new URLSearchParams(window.location.search);return null!==e.get("alter_connect_success")||null!==e.get("alter_connect_error")}function xe(e){sessionStorage.removeItem(Ie);try{const t=new URL(e);if(t.pathname===window.location.pathname)return void window.history.replaceState({},document.title,t.pathname+t.search+t.hash)}catch{}Ze()}function Ze(){const e=new URL(window.location.href);for(const t of Te)e.searchParams.delete(t);window.history.replaceState({},document.title,e.pathname+e.search+e.hash)}class He{constructor(t){this.popup=null,this.pollInterval=null,this.messageListener=null,this.settled=!1,this.options={baseURL:t.baseURL,onSuccess:t.onSuccess,onError:t.onError,onCancel:t.onCancel,popupWidth:t.popupWidth||500,popupHeight:t.popupHeight||700,debug:t.debug||!1,expectedOrigin:t.expectedOrigin||""};try{this.expectedOrigin=new URL(t.baseURL).origin}catch{throw new Error(`Invalid baseURL: "${t.baseURL}". Must be a full URL with protocol (e.g., "${e}").`)}}startOAuth(e){if(!this.options.expectedOrigin)try{const t=new URL(e);this.options.expectedOrigin=t.origin,this.log("Derived expected origin:",this.options.expectedOrigin)}catch{return this.log("Failed to parse OAuth URL for origin validation:",e),void this.options.onError({code:"invalid_oauth_url",message:"Failed to determine origin from OAuth URL. Cannot proceed securely."})}!function(){const e=Oe();return"phone"===e||"tablet"===e&&window.innerHeight>window.innerWidth}()?(this.log("Using popup flow for desktop"),this.openPopup(e)):(this.log("Using redirect flow for mobile device"),this.startRedirectFlow(e))}startRedirectFlow(e){this.log("Starting redirect flow:",e);const t=function(){const e=globalThis.crypto;if(!e)return null;if("function"==typeof e.randomUUID)return e.randomUUID();if("function"==typeof e.getRandomValues){const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}return null}();if(null===t)return this.log("No cryptographic randomness available; refusing redirect flow"),void this.options.onError({code:"redirect_error",message:"Failed to start OAuth flow: this browser provides no secure random source, so the OAuth callback could not be bound to this flow"});let n;try{const s=new URL(e);s.searchParams.set(je,t),n=s.toString()}catch{return this.log("Failed to parse OAuth URL for redirect flow:",e),void this.options.onError({code:"invalid_oauth_url",message:"Failed to start OAuth flow: the OAuth URL is not a valid absolute URL"})}const s={timestamp:Date.now(),returnUrl:window.location.href,nonce:t};try{sessionStorage.setItem(Ie,JSON.stringify(s))}catch(e){return this.log("Failed to save state:",e),void this.options.onError({code:"redirect_error",message:"Failed to start OAuth flow: could not save session state",details:{error:e}})}window.location.href=n}static checkOAuthReturn(e,t){const n=sessionStorage.getItem(Ie);if(!n)return!!Me()&&(Ze(),t({code:"redirect_state_missing",message:"Received an Alter Connect redirect callback, but no matching flow state exists on this origin. The return URL must be on the SAME origin (scheme, host and port) as the page that called open() — browsers scope the flow's session storage to one origin, so a callback delivered elsewhere cannot be completed.",details:{origin:window.location.origin}}),!0);try{const r=function(e){let t;try{t=JSON.parse(e)}catch{return null}if("object"!=typeof t||null===t)return null;const{timestamp:n,returnUrl:s,nonce:r}=t;return"number"==typeof n&&Number.isFinite(n)?"string"!=typeof s||0===s.length||"string"!=typeof r||0===r.length?null:{timestamp:n,returnUrl:s,nonce:r}:null}(n);if(null===r)return sessionStorage.removeItem(Ie),Me()&&Ze(),!1;const o=Date.now()-r.timestamp;if(o<0||o>3e5)return sessionStorage.removeItem(Ie),Me()&&Ze(),!1;const i=new URLSearchParams(window.location.search),a=i.get("alter_connect_success"),c=i.get("alter_connect_error");if(null===a&&null===c)return!1;if(i.get(je)!==r.nonce)return console.warn("[OAuth Handler] Ignoring OAuth callback parameters that do not carry this flow's nonce"),Ze(),!1;if("true"===a){const n=i.get("grant_id"),o=i.get("provider"),a=i.get("account_identifier");if(!n||!o||!a)return xe(r.returnUrl),t({code:"invalid_response",message:"OAuth redirect returned incomplete grant data"}),!0;const c={grant_id:n,provider:o,provider_name:i.get("provider_name")||o,account_identifier:a,timestamp:i.get("timestamp")||(new Date).toISOString(),operation:(s=i.get("operation"),"reauth"===s?"reauth":"creation"),scopes:i.get("scopes")?.split(",")||[],status:Ee(i.get("status"))};xe(r.returnUrl);const u=[c];return e(u,{grants:u,failedGrants:[]}),!0}if(c){const e={code:i.get("error_code")||"oauth_error",message:i.get("error_description")||"OAuth authorization failed"};return xe(r.returnUrl),t(e),!0}return xe(r.returnUrl),!1}catch(e){return console.error("[OAuth Handler] Failed to check OAuth return:",e),sessionStorage.removeItem(Ie),Me()&&Ze(),!1}var s}openPopup(e){const t=window.screenX+(window.outerWidth-this.options.popupWidth)/2,n=window.screenY+(window.outerHeight-this.options.popupHeight)/2,s=[`width=${this.options.popupWidth}`,`height=${this.options.popupHeight}`,`left=${t}`,`top=${n}`,"resizable=yes","scrollbars=yes","status=yes"].join(",");this.log("Opening OAuth popup:",e),this.popup=window.open(e,"alter_oauth_popup",s),this.popup?(this.startPolling(),this.setupMessageListener()):this.options.onError({code:"popup_blocked",message:"Popup was blocked by browser. Please allow popups for this site."})}close(){this.log("Closing OAuth handler"),this.popup&&!this.popup.closed&&this.popup.close(),this.popup=null,null!==this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null)}startPolling(){this.pollInterval=window.setInterval(()=>{this.settled||this.popup&&!this.popup.closed||(this.log("Popup closed by user"),this.settled=!0,this.close(),this.options.onCancel())},500)}setupMessageListener(){this.messageListener=e=>{if(this.settled)return;if(e.origin!==this.expectedOrigin)return void this.log("Rejected message from unexpected origin:",e.origin,"(expected:",this.expectedOrigin+")");this.log("Received message from",e.origin);const t=Re.safeParse(e.data);if(!t.success)return;if("alter_connect_success"===t.data.type){this.log("OAuth success");const t=Ue.safeParse(e.data);if(!t.success)return this.settled=!0,this.close(),void this.options.onError({code:"invalid_response",message:$e(t.error)});const{grants:n,failed_grants:s}=t.data;if(this.log("Connect completion:",n.length,"grants"),0===n.length)return this.settled=!0,this.close(),void(s.length>0?this.options.onError({code:"grant_policy_application_failed",message:"The connection was not completed because the selected usage limits could not be applied.",failedGrants:s}):this.options.onError({code:"invalid_response",message:"Server returned empty grants array"}));const r={grants:n,failedGrants:s};return this.settled=!0,this.close(),void this.options.onSuccess(n,r)}const n=Le.safeParse(e.data);if(n.success){this.log("OAuth error");const e={code:n.data.error,message:n.data.error_description,details:n.data};this.settled=!0,this.close(),this.options.onError(e)}},window.addEventListener("message",this.messageListener)}log(...e){this.options.debug&&console.log("[OAuth Handler]",...e)}}const De="0.2.0";let We=!1;class Ve{constructor(r={}){if(this._oauthHandler=null,this._perOpenCleanups=[],this.pendingRedirectOutcome=null,function(e){if(void 0!==e.baseURL)throw new Error("AlterConnectConfig.baseURL is reserved and not yet supported. Omit the field to use the production Alter host.")}(r),this.config=function(e){return{debug:e.debug??!1}}(r),this._baseURL=(r.baseURL??e).replace(/\/+$/,""),this._baseURL!==e&&!We){We=!0;const e=new URL(this._baseURL).origin;console.warn(`[alter-connect] Using non-default Alter host: ${e}. Unset baseURL in AlterConnect.create() for production.`)}this.eventEmitter=new n,this.stateManager=new s,this._isInitialized=!0,t(this.config,"Alter Connect SDK initialized",{version:De,baseURL:this._baseURL}),this.checkRedirectReturn()}checkRedirectReturn(){He.checkOAuthReturn((e,n)=>{t(this.config,"OAuth redirect return - success:",e),this.deliverRedirectOutcome("success",[e,n])},e=>{t(this.config,"OAuth redirect return - error:",e),this.deliverRedirectOutcome("error",[e])})&&t(this.config,"OAuth redirect return detected and handled")}deliverRedirectOutcome(e,t){this.eventEmitter.hasListeners(e)?this.eventEmitter.emit(e,...t):this.pendingRedirectOutcome={event:e,args:t}}flushRedirectOutcome(e){const t=this.pendingRedirectOutcome;null!==t&&t.event===e&&(this.pendingRedirectOutcome=null,this.eventEmitter.emit(t.event,...t.args))}static create(e){return new Ve(e)}async open(e){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call open() - SDK instance has been destroyed");if(t(this.config,"Opening Connect UI"),!e.token||"string"!=typeof e.token)throw this.createError("invalid_options","Session token is required. Create one from the application backend with an Alter SDK.");if(!e.onSuccess||"function"!=typeof e.onSuccess)throw this.createError("invalid_options","onSuccess callback is required");if(this.isOpen())return void t(this.config,"Connect UI is already open");this._oauthHandler=new He({baseURL:this._baseURL,onSuccess:(e,n)=>{t(this.config,"OAuth success:",e),this.handleOAuthSuccess(e,n)},onError:e=>{t(this.config,"OAuth error:",e),this.handleOAuthError(e)},onCancel:()=>{t(this.config,"OAuth cancelled (popup closed)"),this.handleOAuthCancel()},popupWidth:500,popupHeight:700,debug:this.config.debug}),this.stateManager.setState({isOpen:!0,error:null,sessionToken:e.token}),this.registerEventHandlers(e);const n=`${this._baseURL}/sdk/oauth/connect#session=${encodeURIComponent(e.token)}`;t(this.config,"Connect URL:",n),this._oauthHandler.startOAuth(n),e.onEvent&&e.onEvent("connect_opened",{timestamp:(new Date).toISOString()}),t(this.config,"Connect UI opened successfully")}close(){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call close() - SDK instance has been destroyed");t(this.config,"Closing Connect UI"),this._oauthHandler&&(this._oauthHandler.close(),this._oauthHandler=null),this._perOpenCleanups.forEach(e=>e()),this._perOpenCleanups=[],this.stateManager.setState({isOpen:!1}),this.eventEmitter.emit("close")}destroy(){this._isInitialized&&(t(this.config,"Destroying SDK instance"),this._oauthHandler&&(this._oauthHandler.close(),this._oauthHandler=null),this.stateManager.get("isOpen")&&this.stateManager.setState({isOpen:!1}),this.pendingRedirectOutcome=null,this.eventEmitter.removeAllListeners(),this.stateManager.clearListeners(),this._isInitialized=!1)}on(e,t){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call on() - SDK instance has been destroyed");const n=this.eventEmitter.on(e,t);return this.flushRedirectOutcome(e),n}off(e,t){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call off() - SDK instance has been destroyed");this.eventEmitter.off(e,t)}isOpen(){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call isOpen() - SDK instance has been destroyed");return this.stateManager.get("isOpen")}getVersion(){return De}cleanupHandler(){this._oauthHandler=null}handleOAuthSuccess(e,t){this.cleanupHandler(),this.eventEmitter.emit("success",e,t)}handleOAuthError(e){this.cleanupHandler(),this.stateManager.setState({error:e}),this.eventEmitter.emit("error",e)}handleOAuthCancel(){this.cleanupHandler(),this.eventEmitter.emit("exit")}registerEventHandlers(e){e.onSuccess&&this._perOpenCleanups.push(this.eventEmitter.on("success",(t,n)=>{e.onSuccess(t,n),this.close()})),e.onExit&&this._perOpenCleanups.push(this.eventEmitter.on("exit",()=>{e.onExit(),this.close()})),this._perOpenCleanups.push(this.eventEmitter.on("error",t=>{e.onError&&e.onError(t),this.close()})),e.onEvent&&this._perOpenCleanups.push(this.eventEmitter.on("event",(t,n)=>{e.onEvent(t,n)}))}createError(e,t,n){const s=new Error(t);return s.code=e,s.details=n,s}}return Ve});
2
2
  //# sourceMappingURL=alter-connect.umd.js.map