gazesight 0.5.2 → 0.5.3

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.
@@ -59,4 +59,4 @@ ${u}`:u:"",d=Function,m=`return (input) => {
59
59
  ${u}
60
60
  }`,p;try{p=new d(...a,m)(...s)}catch(f){throw new L(`this schema (generated code failed to evaluate: ${f.message})`)}return r?.debug&&(p.code=c),p.definite=o.definite,p}function E(e,r){for(let[o,t]of e.constants)if(t===r)return o;let i=`c${e.constantCounter++}`;return e.constants.set(i,r),i}function _t(e,r){return e.definite=!1,E(e,r)}function N(e){return`v${e.varCounter++}`}function N$(e,r){let i=e._zod.run({value:r,issues:[]},{});if(i&&typeof i.then=="function")return ge;let o=i;return o.issues.length===0?o.value:ge}function ce(e,r,i,o,t=!0){let n=e.content.length,a=r.constants.size,s=r.constantCounter,u=r.varCounter;try{return q(e,r,i,o,t)}catch(c){if(!(c instanceof L)||!c.islandable)throw c;if(e.content.length=n,r.constants.size>a){let d=Array.from(r.constants.keys()).slice(a);for(let m of d)r.constants.delete(m)}return r.constantCounter=s,r.varCounter=u,U$(e,r,i,o)}}function U$(e,r,i,o){r.definite=!1;let t=E(r,i),n=E(r,N$),a=N(r);return e.write(`const ${a} = ${n}(${t}, ${o});`),e.write(`if (${a} === INVALID) return INVALID;`),a}var E$=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function C$(e,r,i,o){let t=i._zod.def.checks;if(!t||t.length===0)return o;let n=o;for(let a of t){let s=a._zod.def;if(s.when&&!E$.has(s.check))throw new L('check with a custom "when" condition');switch(s.check){case"greater_than":Z$(e,r,s,n);break;case"less_than":R$(e,r,s,n);break;case"multiple_of":L$(e,r,s,n);break;case"number_format":Hf(e,s,n);break;case"min_length":{let u=$t(s.minimum,"min_length"),c=Zu(e,r,n,`${n}.length >= ${u} && ${n}.length < ${s.minimum*2}`);e.write(`if (${c} < ${u}) return INVALID;`);break}case"max_length":{let u=$t(s.maximum,"max_length"),c=Zu(e,r,n,`${n}.length > ${u}`);e.write(`if (${c} > ${u}) return INVALID;`);break}case"length_equals":{let u=$t(s.length,"length_equals"),c=Zu(e,r,n,`${n}.length >= ${u} && ${n}.length <= ${s.length*2}`);e.write(`if (${c} !== ${u}) return INVALID;`);break}case"min_size":e.write(`if (${n}.size < ${$t(s.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${n}.size > ${$t(s.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${n}.size !== ${$t(s.size,"size_equals")}) return INVALID;`);break;case"string_format":n=Xf(e,r,s,n);break;case"custom":n=J$(e,r,a,n);break;case"bigint_format":M$(e,s,n);break;case"mime_type":V$(e,r,s,n);break;case"property":G$(e,r,s,n);break;case"properties":F$(e,r,s,n);break;case"overwrite":{let u=N(r);B$(e,r,a,n,u),n=u;break}default:throw new L(`check type ${s.check}`)}}return n}function Zu(e,r,i,o){let t=E(r,gt),n=N(r);return e.write(`const ${n} = typeof ${i} === "string" && ${o} ? ${t}(${i}) : ${i}.length;`),n}function $t(e,r){if(typeof e!="number"||!Number.isFinite(e))throw new L(`${r} bound of type ${typeof e}`);return`${e}`}function Kf(e,r){if(typeof r=="bigint")return`${r}n`;if(typeof r=="number"){if(Number.isNaN(r))throw new L("comparison check with NaN bound");return`${r}`}if(r instanceof Date){if(Number.isNaN(r.getTime()))throw new L("comparison check with Invalid Date bound");return E(e,r)}throw new L(`comparison check bound of type ${typeof r}`)}function Z$(e,r,i,o){let t=i.inclusive?"<":"<=";e.write(`if (${o} ${t} ${Kf(r,i.value)}) return INVALID;`)}function R$(e,r,i,o){let t=i.inclusive?">":">=";e.write(`if (${o} ${t} ${Kf(r,i.value)}) return INVALID;`)}function L$(e,r,i,o){if(typeof i.value=="bigint"){if(i.value===BigInt(0))throw new L("multiple_of check with a zero divisor");e.write(`if (${o} % ${i.value}n !== 0n) return INVALID;`)}else{let t=E(r,kr);e.write(`if (${t}(${o}, ${$t(i.value,"multiple_of")}) !== 0) return INVALID;`)}}function Hf(e,r,i){let o=r.format;switch(o){case"safeint":e.write(`if (!Number.isSafeInteger(${i})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${i}) || ${i} < -2147483648 || ${i} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${i}) || ${i} < 0 || ${i} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${i}) || ${i} < -3.4028234663852886e38 || ${i} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${i})) return INVALID;`);break;default:throw new L(`number format ${o}`)}}function M$(e,r,i){let o=r.format;if(o)switch(o){case"int64":e.write(`if (${i} < -9223372036854775808n || ${i} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${i} < 0n || ${i} > 18446744073709551615n) return INVALID;`);break;default:throw new L(`bigint format ${o}`)}}function V$(e,r,i,o){let t=i.mime;if(t&&t.length>0){let n=E(r,new Set(t));e.write(`if (!${n}.has(${o}.type)) return INVALID;`)}}function F$(e,r,i,o){if(i.when)throw new L('check with a custom "when" condition');e.write(`if (${o} == null) return INVALID;`);let t=i.shape;for(let n of Reflect.ownKeys(t)){let a=typeof n=="symbol"?E(r,n):fe(n),s=N(r);e.write(`const ${s} = ${o}[${a}];`),ce(e,r,t[n],s,!1)}}function G$(e,r,i,o){let t=`${o}[${JSON.stringify(i.property)}]`;q(e,r,i.schema,t)}function B$(e,r,i,o,t){let n=i._zod.def.tx;if(!n)throw new L("overwrite check without a transform function");if(wt(n))throw new Ue("z.compile: async overwrite transforms are not supported");let a=E(r,n);e.write(`const ${t} = ${a}(${o});`)}function Ru(){throw new we}function Vu(e){this.issues.push(e)}function J$(e,r,i,o){let t=i._zod.def;if(t.fn){if(wt(t.fn))throw new Ue("z.compile: async .refine() predicates are not supported");let n=_t(r,t.fn),a=E(r,Ru),s=N(r);return e.write(`const ${s} = ${n}(${o});`),e.write(`if (${s} instanceof Promise) ${a}();`),e.write(`if (!${s}) return INVALID;`),o}if(i._zod.check){if(wt(i._zod.check))throw new Ue("z.compile: async .superRefine() / check functions are not supported");let n=i._zod.check,s=_t(r,c=>{let d={value:c,issues:[],addIssue:Vu};return n(d)instanceof Promise&&Ru(),d.issues.length===0?d.value:ge}),u=N(r);return e.write(`const ${u} = ${s}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}throw new L("custom check without a predicate or check function")}var W$=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function Xf(e,r,i,o,t=!0){let n=i.format;if(n==="base64"){let c=E(r,Fr);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(n==="base64url"){let c=E(r,fi);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(n==="jwt"){let c=E(r,hi),d=E(r,i.alg??null);return e.write(`if (!${c}(${o}, ${d})) return INVALID;`),o}if(n==="ipv6"){let c=E(r,Vr);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(n==="cidrv6"){let c=E(r,di);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(n==="credit_card"){let c=E(r,pi);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(n==="iban"){let c=E(r,gi);return e.write(`if (!${c}(${o})) return INVALID;`),o}let a=i;if(n==="url"||n==="httpurl"||a.normalize||a.hostname!==void 0||a.protocol!==void 0){let c=E(r,ui),d=E(r,i),m=N(r),p=N(r);if(e.write(`const ${m} = ${o}.trim();`),e.write(`const ${p} = ${c}(${m}, ${d});`),e.write(`if (typeof ${p} === "number") return INVALID;`),a.hostname!==void 0){let _=E(r,ci);e.write(`if (!${_}(${p}, ${d}.hostname)) return INVALID;`)}if(a.protocol!==void 0){let _=E(r,li);e.write(`if (!${_}(${p}, ${d}.protocol)) return INVALID;`)}if(!t)return null;let f=N(r),h=a.normalize?`${p}.href`:`${E(r,Mr)}(${m})`;return e.write(`const ${f} = ${h};`),f}let s=i.fn;if(s){if(wt(s))throw new L(`async string format ${n}`);let c=E(r,s);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(W$.has(n)&&i.pattern){let c=E(r,i.pattern);return e.write(`${c}.lastIndex = 0;`),e.write(`if (!${c}.test(${o})) return INVALID;`),o}let u=i.format;switch(u){case"regex":throw new L("regex format without a pattern");case"lowercase":e.write(`if (${o} !== ${o}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${o} !== ${o}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${o}.includes(${fe(i.includes)})) return INVALID;`);break;case"starts_with":{let c=i.prefix;e.write(`if (${o}.slice(0, ${c.length}) !== ${fe(c)}) return INVALID;`);break}case"ends_with":{let c=i.suffix;e.write(`if (${o}.slice(-${c.length}) !== ${fe(c)}) return INVALID;`);break}default:throw new L(`string format ${u}`)}return o}function q(e,r,i,o,t=!0){let n=i._zod.def,a=n.type;if(n.coerce)throw new L(`coercion (z.coerce.${a}())`);let s=t||!!n.checks?.length,u;switch(a){case"string":u=K$(e,r,i,o,s);break;case"number":u=H$(e,i,o);break;case"boolean":u=X$(e,o);break;case"bigint":u=q$(e,i,o);break;case"symbol":u=Y$(e,o);break;case"undefined":u=Q$(e,o);break;case"null":u=ey(e,o);break;case"any":case"unknown":u=o;break;case"never":e.write("return INVALID;"),u=o;break;case"void":u=ty(e,o);break;case"nan":u=ry(e,o);break;case"date":u=ny(e,o);break;case"object":u=iy(e,r,i,o,s);break;case"optional":u=oy(e,r,i,o,s);break;case"nullable":u=uy(e,r,i,o,s);break;case"array":u=cy(e,r,i,o,s);break;case"literal":u=ly(e,r,i,o);break;case"enum":u=dy(e,r,i,o);break;case"readonly":{let c=Bf(e,r,i,o),d=N(r);e.write(`const ${d} = Object.freeze(${c});`),u=d;break}case"success":Bf(e,r,i,o),u="true";break;case"default":case"prefault":u=my(e,r,i,o);break;case"nonoptional":u=fy(e,r,i,o);break;case"tuple":u=py(e,r,i,o);break;case"union":u=gy(e,r,i,o);break;case"intersection":u=by(e,r,i,o);break;case"record":u=$y(e,r,i,o);break;case"map":u=_y(e,r,i,o);break;case"set":u=wy(e,r,i,o);break;case"file":u=xy(e,o);break;case"template_literal":u=ky(e,r,i,o);break;case"lazy":u=Iy(e,r,i,o);break;case"pipe":u=Sy(e,r,i,o);break;case"custom":u=zy(e,r,i,o);break;case"transform":u=Py(e,r,i,o);break;case"catch":u=Ty(e,r,i,o);break;default:throw new L(`schema type ${a}`)}return u===null?null:C$(e,r,i,u)}function K$(e,r,i,o,t=!0){e.write(`if (typeof ${o} !== "string") return INVALID;`);let n=i._zod.def;return n.format===void 0?o:Xf(e,r,n,o,t)}function H$(e,r,i){e.write(`if (typeof ${i} !== "number" || !Number.isFinite(${i})) return INVALID;`);let o=r._zod.def;return o.check==="number_format"&&o.format&&Hf(e,{format:o.format},i),i}function X$(e,r){return e.write(`if (typeof ${r} !== "boolean") return INVALID;`),r}function q$(e,r,i){e.write(`if (typeof ${i} !== "bigint") return INVALID;`);let o=r._zod.def;if(o.format)switch(o.format){case"int64":e.write(`if (${i} < -9223372036854775808n || ${i} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${i} < 0n || ${i} > 18446744073709551615n) return INVALID;`);break}return i}function Y$(e,r){return e.write(`if (typeof ${r} !== "symbol") return INVALID;`),r}function Q$(e,r){return e.write(`if (${r} !== undefined) return INVALID;`),r}function ey(e,r){return e.write(`if (${r} !== null) return INVALID;`),r}function ty(e,r){return e.write(`if (${r} !== undefined) return INVALID;`),r}function ry(e,r){return e.write(`if (typeof ${r} !== "number" || !Number.isNaN(${r})) return INVALID;`),r}function ny(e,r){return e.write(`if (!(${r} instanceof Date) || Number.isNaN(${r}.getTime())) return INVALID;`),r}function iy(e,r,i,o,t=!0){let n=i._zod.def;e.write(`if (typeof ${o} !== "object" || ${o} === null || Array.isArray(${o})) return INVALID;`);let a=n.shape,s=Object.keys(a),u=Object.getOwnPropertySymbols(a),c=u.length?[...s,...u]:s,d=T=>typeof T=="symbol"?E(r,T):fe(T),m=T=>typeof T=="symbol"?`[${d(T)}]`:fe(T),p=a;if(s.includes("__proto__"))throw new L('object shape key "__proto__"');let f=new Map;for(let T of c){let U=p[T],I=d(T),A=N(r);if(e.write(`const ${A} = ${o}[${I}];`),U._zod.optin!==void 0){let S=N(r);e.write(`let ${S} = (() => {`),e.indented(j=>{let M=ce(j,r,U,A);j.write(`return ${M};`)}),e.write("})();"),U._zod.optout==="optional"?(e.write(`if (${S} === INVALID) {`),e.indented(j=>{j.write(`if (${I} in ${o}) return INVALID;`),j.write(`${S} = undefined;`)}),e.write("}")):e.write(`if (${S} === INVALID) return INVALID;`),f.set(T,S)}else{sy(U)&&e.write(`if (!(${I} in ${o})) return INVALID;`);let S=ce(e,r,U,A,t);S!==null&&f.set(T,S)}}let h=n.catchall,_="none";if(h){let T=h._zod.def.type;if(T==="never"){let U=s.map(I=>`k !== ${fe(I)}`).join(" && ")||"true";e.write(`for (const k in ${o}) {`),e.indented(I=>{I.write(`if (${U}) return INVALID;`)}),e.write("}")}else(T==="unknown"||T==="any")&&!h._zod.def.checks?.length?_="passthrough":_="schema"}let k=N(r),P=c.some(T=>Gf(p[T])||Lu(p[T]));if(!t){if(_==="schema"){let T=s.length>0?E(r,new Set(s)):null;e.write(`for (const k in ${o}) {`),e.indented(U=>{U.write('if (k === "__proto__") continue;'),T&&U.write(`if (${T}.has(k)) continue;`);let I=N(r);U.write(`const ${I} = ${o}[k];`),ce(U,r,h,I,!1)}),e.write("}")}return null}if(P){e.write(`const ${k} = {};`);for(let T of c){let U=d(T),I=f.get(T);Lu(p[T])?e.write(`if (${U} in ${o}) ${k}[${U}] = ${I};`):Gf(p[T])?e.write(`if (${I} !== undefined || ${U} in ${o}) ${k}[${U}] = ${I};`):e.write(`${k}[${U}] = ${I};`)}}else{let T=c.map(U=>`${m(U)}: ${f.get(U)}`).join(", ");e.write(`const ${k} = { ${T} };`)}if(_!=="none"){let T=s.length>0?E(r,new Set(s)):null;e.write(`for (const k in ${o}) {`),e.indented(U=>{if(U.write('if (k === "__proto__") continue;'),T&&U.write(`if (${T}.has(k)) continue;`),_==="passthrough")U.write(`${k}[k] = ${o}[k];`);else{let I=N(r);U.write(`const ${I} = ${o}[k];`);let A=ce(U,r,h,I);U.write(`${k}[k] = ${A};`)}}),e.write("}")}return k}function oy(e,r,i,o,t=!0){let n=i._zod.def;if(ay(i))return q(e,r,n.innerType,o,t);if(n.innerType._zod.optin==="defaulted"){let s=N(r),u=N(r);return e.write(`let ${s};`),e.write(`if (${o} === undefined) {`),e.indented(c=>{c.write(`const ${u} = (() => {`),c.indented(d=>{let m=q(d,r,n.innerType,o);d.write(`return ${m};`)}),c.write("})();"),c.write(`if (${u} !== INVALID) ${s} = ${u};`)}),e.write("} else {"),e.indented(c=>{let d=q(c,r,n.innerType,o);c.write(`${s} = ${d};`)}),e.write("}"),s}let a=t?N(r):null;return a&&e.write(`let ${a};`),e.write(`if (${o} !== undefined) {`),e.indented(s=>{let u=q(s,r,n.innerType,o,t);a&&u!==null&&s.write(`${a} = ${u};`)}),e.write("}"),a}function ay(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function sy(e){return e._zod.optin===void 0&&yt(e)}function yt(e){if(e._zod.def.coerce)return!0;let r=e._zod.def;switch(r.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return r.innerType?yt(r.innerType):!1;case"literal":return!!r.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return r.innerType?yt(r.innerType):!0;case"catch":return!0;case"union":return r.options?r.options.some(yt):!0;case"intersection":return!r.left||!r.right?!0:yt(r.left)&&yt(r.right);case"pipe":return r.in?yt(r.in):!0;default:return!0}}function Lu(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function Gf(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&Wt(e)}function Wt(e){let r=e._zod.def;switch(r.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!r.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return r.innerType?Wt(r.innerType):!0;case"union":return r.options?r.options.some(Wt):!0;case"intersection":return!r.left||!r.right||Wt(r.left)||Wt(r.right);case"pipe":return r.out?Wt(r.out):!0;default:return!0}}function uy(e,r,i,o,t=!0){let n=i._zod.def,a=t?N(r):null;return a&&e.write(`let ${a} = null;`),e.write(`if (${o} !== null) {`),e.indented(s=>{let u=q(s,r,n.innerType,o,t);a&&u!==null&&s.write(`${a} = ${u};`)}),e.write("}"),a}function cy(e,r,i,o,t=!0){let n=i._zod.def;e.write(`if (!Array.isArray(${o})) return INVALID;`);let a=t?N(r):null,s=N(r),u=N(r);return a&&e.write(`const ${a} = new Array(${o}.length);`),e.write(`for (let ${s} = 0; ${s} < ${o}.length; ${s}++) {`),e.indented(c=>{c.write(`const ${u} = ${o}[${s}];`);let d=ce(c,r,n.element,u,t);a&&d!==null&&c.write(`${a}[${s}] = ${d};`)}),e.write("}"),a}function ly(e,r,i,o){let n=i._zod.def.values;if(n.length!==1){let s=E(r,new Set(n));return e.write(`if (!${s}.has(${o})) return INVALID;`),o}let a=n[0];if(typeof a=="number"&&Number.isNaN(a)){let s=E(r,new Set(n));return e.write(`if (!${s}.has(${o})) return INVALID;`),o}if(typeof a=="string")e.write(`if (${o} !== ${fe(a)}) return INVALID;`);else if(typeof a=="number"||typeof a=="boolean")e.write(`if (${o} !== ${a}) return INVALID;`);else if(a===null)e.write(`if (${o} !== null) return INVALID;`);else if(a===void 0)e.write(`if (${o} !== undefined) return INVALID;`);else if(typeof a=="bigint")e.write(`if (${o} !== ${a}n) return INVALID;`);else throw new L(`literal type ${typeof a}`);return o}function dy(e,r,i,o){let t=i._zod.values;if(!t)throw new L("enum schema without enumerated values");let n=E(r,t);return e.write(`if (!${n}.has(${o})) return INVALID;`),o}function Bf(e,r,i,o){let t=i._zod.def;return q(e,r,t.innerType,o)}function my(e,r,i,o){let t=i._zod.def,a=Object.getOwnPropertyDescriptor(i._zod.def,"defaultValue")?()=>i._zod.def.defaultValue:void 0;if(i._zod.def.type==="prefault"){if(!a)return q(e,r,t.innerType,o);let u=E(r,a),c=N(r);return e.write(`let ${c} = ${o};`),e.write(`if (${o} === undefined) ${c} = ${u}();`),q(e,r,t.innerType,c)}let s=N(r);if(a){let u=E(r,a),c=E(r,Ir);e.write(`let ${s};`),e.write(`if (${o} === undefined) {`),e.indented(d=>{d.write(`${s} = ${c}(${u}());`)}),e.write("} else {"),e.indented(d=>{let m=q(d,r,t.innerType,o);d.write(`${s} = ${m} === undefined ? ${c}(${u}()) : ${m};`)}),e.write("}")}else e.write(`let ${s};`),e.write(`if (${o} !== undefined) {`),e.indented(u=>{let c=q(u,r,t.innerType,o);u.write(`${s} = ${c};`)}),e.write("}");return s}function fy(e,r,i,o){let t=i._zod.def,n=q(e,r,t.innerType,o),a=N(r);return e.write(`const ${a} = ${n};`),e.write(`if (${a} === undefined) return INVALID;`),a}function py(e,r,i,o){let t=i._zod.def,n=t.items,a=t.rest;e.write(`if (!Array.isArray(${o})) return INVALID;`);let s=Jf(n,"optin"),u=Jf(n,"optout");a?e.write(`if (${o}.length < ${s}) return INVALID;`):e.write(`if (${o}.length < ${s} || ${o}.length > ${n.length}) return INVALID;`);let c=N(r);e.write(`const ${c} = [];`);for(let d=0;d<n.length;d++){let m=n[d];if(d>=u)e.write(`if (${c}.length === ${d}) {`),e.indented(p=>{p.write(`if (${d} < ${o}.length) {`),p.indented(f=>{let h=N(r);f.write(`const ${h} = ${o}[${d}];`);let _=ce(f,r,m,h);f.write(`${c}[${d}] = ${_};`)}),p.write("} else {"),p.indented(f=>{if(Lu(m)){f.write(`${c}.length = ${d};`);return}let h=N(r),_=N(r);f.write(`const ${h} = undefined;`),f.write(`const ${_} = (() => {`),f.indented(k=>{let P=ce(k,r,m,h);k.write(`return ${P};`)}),f.write("})();"),f.write(`if (${_} === INVALID || ${_} === undefined) ${c}.length = ${d};`),f.write(`else ${c}[${d}] = ${_};`)}),p.write("}")}),e.write("}");else{let p=N(r);e.write(`const ${p} = ${o}[${d}];`);let f=ce(e,r,m,p);e.write(`${c}[${d}] = ${f};`)}}if(a){let d=N(r),m=N(r);e.write(`for (let ${d} = ${n.length}; ${d} < ${o}.length; ${d}++) {`),e.indented(p=>{p.write(`const ${m} = ${o}[${d}];`);let f=ce(p,r,a,m);p.write(`${c}[${d}] = ${f};`)}),e.write("}")}return c}function Jf(e,r){for(let i=e.length-1;i>=0;i--)if(!(r==="optin"?e[i]._zod.optin!==void 0:e[i]._zod.optout==="optional"))return i+1;return 0}function gy(e,r,i,o){let t=i._zod.def,n=t.options;if(t.discriminator)return hy(e,r,t,o);if(t.inclusive===!1)throw new L("exclusive unions (z.xor)");if(n.length===0)return e.write("return INVALID;"),o;if(n.length===1)return q(e,r,n[0],o);if(n.every(u=>u._zod.def.type==="literal"&&!u._zod.def.checks?.length)){let u=new Set(n.flatMap(d=>d._zod.def.values)),c=E(r,u);return e.write(`if (!${c}.has(${o})) return INVALID;`),o}let s=N(r);e.write(`let ${s};`);for(let u=0;u<n.length;u++){let c=n[u];u===0?e.write(`${s} = (() => {`):e.write(`if (${s} === INVALID) ${s} = (() => {`),e.indented(d=>{let m=q(d,r,c,o);d.write(`return ${m};`)}),e.write("})();")}return e.write(`if (${s} === INVALID) return INVALID;`),s}function hy(e,r,i,o){if(i.unionFallback)throw new L("discriminated union with unionFallback");if(i.options.length===0)return e.write("return INVALID;"),o;let t=N(r),n=N(r);e.write(`const ${t} = ${o}?.[${fe(i.discriminator)}];`),e.write(`let ${n};`);let a=!0,s=new Set;for(let u of i.options){let c=u._zod.propValues?.[i.discriminator];if(!c||c.size===0)throw new L("discriminated union option without static discriminator values");for(let p of c){if(s.has(p))throw new L(`duplicate discriminator value ${String(p)}`);s.add(p)}let d=Array.from(c,p=>vy(r,t,p)),m=a?"if":"else if";e.write(`${m} (${d.join(" || ")}) {`),e.indented(p=>{let f=q(p,r,u,o);p.write(`${n} = ${f};`)}),e.write("}"),a=!1}return e.write("else { return INVALID; }"),n}function vy(e,r,i){if(typeof i=="string")return`${r} === ${fe(i)}`;if(typeof i=="number")return Number.isNaN(i)?`Number.isNaN(${r})`:`${r} === ${i}`;if(typeof i=="boolean")return`${r} === ${i}`;if(i===null)return`${r} === null`;if(i===void 0)return`${r} === undefined`;if(typeof i=="bigint")return`${r} === ${i}n`;if(typeof i=="symbol"){let o=E(e,i);return`${r} === ${o}`}throw new L(`literal discriminator value ${String(i)}`)}function by(e,r,i,o){let t=i._zod.def;r.definite=!1;let n=ce(e,r,t.left,o),a=ce(e,r,t.right,o),s=E(r,Gt),u=N(r);return e.write(`const ${u} = ${s}(${n}, ${a});`),e.write(`if (!${u}.valid) return INVALID;`),`${u}.data`}function $y(e,r,i,o){let t=i._zod.def,n=E(r,ze);e.write(`if (!${n}(${o})) return INVALID;`);let a=N(r),s=N(r),u=N(r);e.write(`const ${a} = {};`);let c=t,d=c.partial?void 0:t.keyType._zod.values;if(d){let f=[];for(let _ of d){if(!(typeof _=="string"||typeof _=="number"||typeof _=="symbol"))throw new L(`record key value ${String(_)}`);let k=typeof _=="number"?_.toString():_;if(k==="__proto__")throw new L('record key "__proto__"');f.push(k);let P=E(r,_),T=q(e,r,t.keyType,P),U=N(r);e.write(`const ${U} = ${o}[${yy(r,k)}];`);let I=ce(e,r,t.valueType,U);e.write(`${a}[${T}] = ${I};`)}let h=E(r,new Set(f));return e.write(`for (const ${s} in ${o}) {`),e.indented(_=>{_.write(`if (${h}.has(${s})) continue;`),c.mode==="loose"?_.write(`if (${s} !== "__proto__") ${a}[${s}] = ${o}[${s}];`):_.write("return INVALID;")}),e.write("}"),a}let m=t.keyType._zod.def;if(!(m.type==="string"&&m.format===void 0&&!m.coerce&&(m.checks?.length??0)===0)){let f=t.mode==="loose",h=Ni(t.keyType);h.definite===!1&&(r.definite=!1);let _=E(r,h),k=E(r,He),P=N(r);return Wf(e,r,o,s,T=>{T.write(`let ${P} = ${_}(${s});`),T.write(`if (${P} === INVALID && typeof ${s} === "string" && ${k}.test(${s})) ${P} = ${_}(Number(${s}));`),f?T.write(`if (${P} === INVALID) { ${a}[${s}] = ${o}[${s}]; continue; }`):T.write(`if (${P} === INVALID) return INVALID;`),T.write(`if (${P} === "__proto__") continue;`);let U=N(r);T.write(`const ${U} = ${o}[${s}];`);let I=ce(T,r,t.valueType,U);T.write(`${a}[${P}] = ${I};`)}),a}return Wf(e,r,o,s,f=>{f.write(`const ${u} = ${o}[${s}];`);let h=ce(f,r,t.valueType,u);f.write(`${a}[${s}] = ${h};`)},"return INVALID;"),a}function Wf(e,r,i,o,t,n){let a=E(r,Object.prototype.propertyIsEnumerable),s=N(r),u=N(r),c=N(r);e.write(`const ${s} = Object.getOwnPropertySymbols(${i});`),e.write(`const ${u} = Object.getOwnPropertyNames(${i});`),e.write(`for (let ${c} = 0; ${c} < ${u}.length; ${c}++) {`),e.indented(d=>{d.write(`const ${o} = ${u}[${c}];`),d.write(`if (${o} === "__proto__" || !${a}.call(${i}, ${o})) continue;`),t(d)}),e.write("}"),e.write(`for (let ${c} = 0; ${c} < ${s}.length; ${c}++) {`),e.indented(d=>{d.write(`const ${o} = ${s}[${c}];`),d.write(`if (!${a}.call(${i}, ${o})) continue;`),n?d.write(n):t(d)}),e.write("}")}function yy(e,r){return typeof r=="string"?fe(r):E(e,r)}function _y(e,r,i,o){let t=i._zod.def;e.write(`if (!(${o} instanceof Map)) return INVALID;`);let n=N(r),a=N(r),s=N(r);return e.write(`const ${n} = new Map();`),e.write(`for (const [${a}, ${s}] of ${o}) {`),e.indented(u=>{let c=q(u,r,t.keyType,a),d=q(u,r,t.valueType,s);u.write(`${n}.set(${c}, ${d});`)}),e.write("}"),n}function wy(e,r,i,o){let t=i._zod.def;e.write(`if (!(${o} instanceof Set)) return INVALID;`);let n=N(r),a=N(r);return e.write(`const ${n} = new Set();`),e.write(`for (const ${a} of ${o}) {`),e.indented(s=>{let u=q(s,r,t.valueType,a);s.write(`${n}.add(${u});`)}),e.write("}"),n}function xy(e,r){return e.write(`if (!(${r} instanceof File)) return INVALID;`),r}function ky(e,r,i,o){e.write(`if (typeof ${o} !== "string") return INVALID;`);let t=i._zod.pattern;if(t){let n=E(r,t);e.write(`${n}.lastIndex = 0;`),e.write(`if (!${n}.test(${o})) return INVALID;`)}return o}function Iy(e,r,i,o){let t=i._zod.def,n=_t(r,t.getter),a=E(r,{parser:null});e.write(`if (!${a}.parser) {`),e.indented(u=>{u.write(`const inner = ${n}();`),u.write(`${a}.parser = function(input) {`),u.indented(c=>{c.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),c.write("return result.issues.length === 0 ? result.value : INVALID;")}),u.write("};")}),e.write("}");let s=N(r);return e.write(`const ${s} = ${a}.parser(${o});`),e.write(`if (${s} === INVALID) return INVALID;`),s}function Sy(e,r,i,o){let t=i._zod.def,n=q(e,r,t.in,o);if(t.transform){if(wt(t.transform))throw new Ue("z.compile: async transforms in pipes are not supported");let a=t.transform,u=_t(r,d=>{let m={value:d,issues:[],addIssue:Vu},p=a(d,m);return p instanceof Promise?ge:m.issues.length===0?p:ge}),c=N(r);return e.write(`const ${c} = ${u}(${n});`),e.write(`if (${c} === INVALID) return INVALID;`),q(e,r,t.out,c)}else return q(e,r,t.out,n)}function wt(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function zy(e,r,i,o){let t=i._zod.def;if(t.fn){if(wt(t.fn))throw new Ue("z.compile: async custom predicates are not supported");let n=_t(r,t.fn),a=E(r,Ru),s=N(r);e.write(`const ${s} = ${n}(${o});`),e.write(`if (${s} instanceof Promise) ${a}();`),e.write(`if (!${s}) return INVALID;`)}else throw new L("custom schema without a predicate function");return o}function Ay(e,r,i){let o=e._zod.run({value:i,issues:[]},{});if(o&&typeof o.then=="function")return ge;let t=o;return t.issues.length===0?t.value:r()}function Ty(e,r,i,o){let t=i._zod.def;if(!t.catchValue[Rn])throw new L("catch with a callback (only a constant catch value compiles)",!1);let n=N(r);e.write(`let ${n} = (() => {`),e.indented(c=>{let d=ce(c,r,t.innerType,o);c.write(`return ${d};`)}),e.write("})();");let a=E(r,t.innerType),s=_t(r,t.catchValue),u=E(r,Ay);return e.write(`if (${n} === INVALID) {`),e.indented(c=>{c.write(`${n} = ${u}(${a}, ${s}, ${o});`),c.write(`if (${n} === INVALID) return INVALID;`)}),e.write("}"),n}function Py(e,r,i,o){let t=i._zod.def;if(t.transform){if(wt(t.transform))throw new Ue("z.compile: async transforms are not supported");let n=t.transform,s=_t(r,c=>{let d={value:c,issues:[],addIssue:Vu},m=n(c,d);return m instanceof Promise?ge:d.issues.length===0?m:ge}),u=N(r);return e.write(`const ${u} = ${s}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}return o}function Ui(e){return e.checks&&(e.checks=[...e.checks]),e}function Fu(e,r){return new e(Ui({type:"string",...z(r)}))}function Gu(e,r){return new e(Ui({type:"string",coerce:!0,...z(r)}))}function Ei(e,r){return new e({type:"string",format:"email",check:"string_format",abort:!1,...z(r)})}function Ci(e,r){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...z(r)})}function Zi(e,r){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...z(r)})}function Ri(e,r){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...z(r)})}function Li(e,r){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...z(r)})}function Mi(e,r){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...z(r)})}function en(e,r){return new e({type:"string",format:"url",check:"string_format",abort:!1,...z(r)})}function Vi(e,r){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...z(r)})}function Fi(e,r){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...z(r)})}function Gi(e,r){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...z(r)})}function Bi(e,r){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...z(r)})}function Ji(e,r){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...z(r)})}function Wi(e,r){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...z(r)})}function Ki(e,r){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...z(r)})}function Hi(e,r){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...z(r)})}function Xi(e,r){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...z(r)})}function Bu(e,r){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...z(r)})}function qi(e,r){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...z(r)})}function Yi(e,r){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...z(r)})}function Qi(e,r){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...z(r)})}function eo(e,r){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...z(r)})}function to(e,r){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...z(r)})}function Ju(e,r){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...z(r)})}function Wu(e,r){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...z(r)})}function ro(e,r){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...z(r)})}var Ku={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function tn(e,r){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...z(r)})}function rn(e,r){return new e({type:"string",format:"date",check:"string_format",...z(r)})}function nn(e,r){return new e({type:"string",format:"time",check:"string_format",precision:null,...z(r)})}function on(e,r){return new e({type:"string",format:"duration",check:"string_format",...z(r)})}function Hu(e,r){return new e(Ui({type:"number",checks:[],...z(r)}))}function Xu(e,r){return new e(Ui({type:"number",coerce:!0,checks:[],...z(r)}))}function qu(e,r){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...z(r)})}function Yu(e,r){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...z(r)})}function Qu(e,r){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...z(r)})}function ec(e,r){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...z(r)})}function tc(e,r){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...z(r)})}function rc(e,r){return new e({type:"boolean",...z(r)})}function nc(e,r){return new e({type:"boolean",coerce:!0,...z(r)})}function ic(e,r){return new e({type:"bigint",...z(r)})}function oc(e,r){return new e({type:"bigint",coerce:!0,...z(r)})}function ac(e,r){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...z(r)})}function sc(e,r){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...z(r)})}function uc(e,r){return new e({type:"symbol",...z(r)})}function cc(e,r){return new e({type:"undefined",...z(r)})}function lc(e,r){return new e({type:"null",...z(r)})}function dc(e){return new e({type:"any"})}function mc(e){return new e({type:"unknown"})}function fc(e,r){return new e({type:"never",...z(r)})}function pc(e,r){return new e({type:"void",...z(r)})}function gc(e,r){return new e({type:"date",...z(r)})}function hc(e,r){return new e({type:"date",coerce:!0,...z(r)})}function vc(e,r){return new e({type:"nan",...z(r)})}function Ze(e,r){return new ti({check:"less_than",...z(r),value:e,inclusive:!1})}function Ie(e,r){return new ti({check:"less_than",...z(r),value:e,inclusive:!0})}function Re(e,r){return new ri({check:"greater_than",...z(r),value:e,inclusive:!1})}function Se(e,r){return new ri({check:"greater_than",...z(r),value:e,inclusive:!0})}function no(e){return Re(0,e)}function io(e){return Ze(0,e)}function oo(e){return Ie(0,e)}function ao(e){return Se(0,e)}function tt(e,r){return new ts({check:"multiple_of",...z(r),value:e})}function rt(e,r){return new is({check:"max_size",...z(r),maximum:e})}function Le(e,r){return new os({check:"min_size",...z(r),minimum:e})}function xt(e,r){return new as({check:"size_equals",...z(r),size:e})}function kt(e,r){return new ss({check:"max_length",...z(r),maximum:e})}function Xe(e,r){return new us({check:"min_length",...z(r),minimum:e})}function It(e,r){return new cs({check:"length_equals",...z(r),length:e})}function Kt(e,r){return new ls({check:"string_format",format:"regex",...z(r),pattern:e})}function Ht(e){return new ds({check:"string_format",format:"lowercase",...z(e)})}function Xt(e){return new ms({check:"string_format",format:"uppercase",...z(e)})}function qt(e,r){return new fs({check:"string_format",format:"includes",...z(r),includes:e})}function Yt(e,r){return new ps({check:"string_format",format:"starts_with",...z(r),prefix:e})}function Qt(e,r){return new gs({check:"string_format",format:"ends_with",...z(r),suffix:e})}function so(e,r,i){return new hs({check:"property",property:e,schema:r,...z(i)})}function er(e,r){return new vs({check:"properties",shape:e,...z(r)})}function tr(e,r){return new bs({check:"mime_type",mime:e,...z(r)})}function Ee(e){return new $s({check:"overwrite",tx:e})}function rr(e){return Ee(r=>r.normalize(e))}function nr(){return Ee(e=>e.trim())}function ir(){return Ee(e=>e.toLowerCase())}function or(){return Ee(e=>e.toUpperCase())}function ar(){return Ee(e=>na(e))}function bc(e,r,i){return new e({type:"array",element:r,...z(i)})}function Oy(e,r,i){return new e({type:"union",options:r,...z(i)})}function Dy(e,r,i){return new e({type:"union",options:r,inclusive:!1,...z(i)})}function jy(e,r,i,o){return new e({type:"union",options:i,discriminator:r,...z(o)})}function Ny(e,r,i){return new e({type:"intersection",left:r,right:i})}function Uy(e,r,i,o){let t=i instanceof C,n=t?o:i,a=t?i:null;return new e({type:"tuple",items:r,rest:a,...z(n)})}function Ey(e,r,i,o){return new e({type:"record",keyType:r,valueType:i,...z(o)})}function Cy(e,r,i,o){return new e({type:"map",keyType:r,valueType:i,...z(o)})}function Zy(e,r,i){return new e({type:"set",valueType:r,...z(i)})}function Ry(e,r,i){let o=Array.isArray(r)?Object.fromEntries(r.map(t=>[t,t])):r;return new e({type:"enum",entries:o,...z(i)})}function Ly(e,r,i){return new e({type:"enum",entries:r,...z(i)})}function My(e,r,i){return new e({type:"literal",values:Array.isArray(r)?r:[r],...z(i)})}function $c(e,r){return new e({type:"file",...z(r)})}function Vy(e,r){return new e({type:"transform",transform:r})}function Fy(e,r){return new e({type:"optional",innerType:r})}function Gy(e,r){return new e({type:"nullable",innerType:r})}function By(e,r,i){return new e({type:"default",innerType:r,get defaultValue(){return typeof i=="function"?i():Ir(i)}})}function Jy(e,r,i){return new e({type:"nonoptional",innerType:r,...z(i)})}function Wy(e,r){return new e({type:"success",innerType:r})}function Ky(e,r,i){return new e({type:"catch",innerType:r,catchValue:typeof i=="function"?i:ca(i)})}function Hy(e,r,i){return new e({type:"pipe",in:r,out:i})}function Xy(e,r){return new e({type:"readonly",innerType:r})}function qy(e,r,i){return new e({type:"template_literal",parts:r,...z(i)})}function Yy(e,r){return new e({type:"lazy",getter:r})}function Qy(e,r){return new e({type:"promise",innerType:r})}function yc(e,r,i){let o=z(i);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:r,...o})}function _c(e,r,i){return new e({type:"custom",check:"custom",fn:r,...z(i)})}function wc(e,r){let i=qf(o=>(o.addIssue=t=>{if(typeof t=="string")o.issues.push(Zt(t,o.value,i._zod.def));else{let n=t;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),"input"in n||(n.input=o.value),n.inst??(n.inst=i),n.continue??(n.continue=!i._zod.def.abort),o.issues.push(Zt(n))}},e(o.value,o)),r);return i}function qf(e,r){let i=new K({check:"custom",...z(r)});return i._zod.check=e,i}function xc(e){let r=new K({check:"describe"});return r._zod.onattach=[i=>{let o=se.get(i)??{};se.add(i,{...o,description:e})}],r._zod.check=()=>{},r}function kc(e){let r=new K({check:"meta"});return r._zod.onattach=[i=>{let o=se.get(i)??{};se.add(i,{...o,...e})}],r._zod.check=()=>{},r}function Ic(e,r){let i=z(r),o=i.truthy??["true","1","yes","on","y","enabled"],t=i.falsy??["false","0","no","off","n","disabled"];i.case!=="sensitive"&&(o=o.map(f=>typeof f=="string"?f.toLowerCase():f),t=t.map(f=>typeof f=="string"?f.toLowerCase():f));let n=new Set(o),a=new Set(t),s=e.Codec??Wr,u=e.Boolean??Br,c=e.String??bt,d=new c({type:"string",error:i.error}),m=new u({type:"boolean",error:i.error}),p=new s({type:"pipe",in:d,out:m,transform:((f,h)=>{let _=f;return i.case!=="sensitive"&&(_=_.toLowerCase()),n.has(_)?!0:a.has(_)?!1:(h.issues.push({code:"invalid_value",expected:"stringbool",values:[...n,...a],input:h.value,inst:p,continue:!1}),{})}),reverseTransform:((f,h)=>f===!0?o[0]||"true":t[0]||"false"),error:i.error});return p._zod.bag.truthy=o,p._zod.bag.falsy=t,p._zod.bag.case=i.case??"insensitive",p}function St(e,r,i,o={}){let t=z(o),n={check:"string_format",type:"string",format:r,fn:typeof i=="function"?i:s=>i.test(s),...t};return i instanceof RegExp&&(n.pattern=i),new e(n)}function an(e,...r){for(let i of r)for(let o of Reflect.ownKeys(i))Object.prototype.propertyIsEnumerable.call(i,o)&&ae(e,o,i[o]);return e}function nt(e){let r=e?.target??"draft-2020-12";return r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??se,target:r,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function te(e,r,i,o,t){let n=typeof r.unrepresentable=="function"?r.unrepresentable({zodSchema:e,path:o.path,message:t}):r.unrepresentable;if(n==="any")return!1;if(n===void 0||n==="throw")throw new Error(t);return Object.assign(i,n),!0}function G(e,r,i={path:[],schemaPath:[]}){var o;let t=e._zod.def,n=r.seen.get(e);if(n)return n.count++,i.schemaPath.includes(e)&&(n.cycle=i.path),n.schema;let a={schema:{},count:1,cycle:void 0,path:i.path};r.seen.set(e,a),r.sharedDefsExtractedFor=void 0,r.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{let d={...i,schemaPath:[...i.schemaPath,e],path:i.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(r,a.schema,d);else{let p=a.schema,f=r.processors[t.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${t.type}`);f(e,r,p,d)}let m=e._zod.parent;m&&(a.ref||(a.ref=m),G(m,r,d),r.seen.get(m).isParent=!0)}let u=r.metadataRegistry.get(e);return u&&an(a.schema,u),r.io==="input"&&he(e)&&(delete a.schema.examples,delete a.schema.default),r.io==="input"&&"_prefault"in a.schema&&((o=a.schema).default??(o.default=a.schema._prefault)),delete a.schema._prefault,r.seen.get(e).schema}function Yf(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function it(e,r){let i=e.seen.get(r);if(!i)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let o=new Map;for(let a of e.seen.entries()){let s=e.metadataRegistry.get(a[0])?.id;if(s){let u=o.get(s);if(u&&u!==a[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(s,a[0])}}let t=a=>{let s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(a[0])?.id,p=e.external.uri??(h=>h);if(m)return{ref:p(m)};let f=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=f,{defId:f,ref:`${p("__shared")}#/${s}/${Yf(f)}`}}let u="#",c=`${u}/${s}/`;if(a[1]===i&&!a[1].schema.id)return{ref:u};let d=a[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:c+Yf(d)}},n=a=>{if(a[1].schema.$ref)return;let s=a[1],{ref:u,defId:c}=t(a);s.def={...s.schema},c&&(s.defId=c);let d=s.schema;for(let m in d)delete d[m];d.$ref=u};if(e.cycles==="throw")for(let a of e.seen.entries()){let s=a[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/<root>
61
61
 
62
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let s=a[1];if(r===a[0]){n(a);continue}if(e.external){let c=e.external.registry.get(a[0])?.id;if(r!==a[0]&&c){n(a);continue}}if(e.metadataRegistry.get(a[0])?.id){n(a);continue}if(s.cycle){n(a);continue}s.count>1&&e.reused==="ref"&&n(a)}e.external&&(e.sharedDefsExtractedFor=e.external)}function tp(e){let r=e.anyOf;if(!Array.isArray(r)||r.length===0||e.type!==void 0)return;let i=[];for(let o of r){if(!o||typeof o!="object")return;tp(o);let t=Object.keys(o);if(t.length!==1||t[0]!=="type")return;let n=o.type;for(let a of Array.isArray(n)?n:[n]){if(typeof a!="string")return;i.includes(a)||i.push(a)}}delete e.anyOf,e.type=i.length===1?i[0]:i}var rp=new Set(["type","properties","required","additionalProperties"]),Qf=["oneOf","anyOf"];function ep(e){let r=e.additionalProperties;return r===void 0||r===!1||typeof r!="object"||r===null?null:Object.keys(r).length?r:null}function Sc(e){let r=[];for(let n of e){if(typeof n!="object"||n.type!=="object")return null;for(let a in n)if(!rp.has(a))return null;r.push(n)}let i={},o=new Set;for(let n of r){for(let a in n.properties){if(Object.prototype.hasOwnProperty.call(i,a))continue;let s=[];for(let c of r){let d=c.properties?.[a]??ep(c);d!=null&&(s.some(m=>JSON.stringify(m)===JSON.stringify(d))||s.push(d))}let u=s.length===1?s[0]:Sc(s)??{allOf:s};ae(i,a,u)}for(let a of n.required??[])o.add(a)}let t={type:"object",properties:i};if(o.size&&(t.required=[...o]),r.every(n=>n.additionalProperties===!1))t.additionalProperties=!1;else{let n=[];for(let a of r){let s=ep(a);s&&!n.some(u=>JSON.stringify(u)===JSON.stringify(s))&&n.push(s)}n.length===1?t.additionalProperties=n[0]:n.length>1&&(t.additionalProperties={allOf:n})}return t}function e_(e){let r=e.allOf;if(!Array.isArray(r)||r.length<2)return;for(let t of rp)if(t in e)return;let i=r.filter(t=>Qf.some(n=>Array.isArray(t[n]))),o=null;if(!i.length)o=Sc(r);else{let t=i[0],n=Qf.find(u=>Array.isArray(t[u]));if(Object.keys(t).length!==1)return;let a=r.filter(u=>u!==t),s=t[n].map(u=>Sc([...a,u]));if(s.some(u=>!u))return;o={[n]:s}}o&&(delete e.allOf,an(e,o))}function ot(e,r){let i=e.seen.get(r);if(!i)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=s=>{let u=e.seen.get(s);if(u.ref===null)return;let c=u.def??u.schema,d={...c},m=u.ref;if(u.ref=null,m){o(m);let f=e.seen.get(m),h=f.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(h)):an(c,h),an(c,d),s._zod.parent===m)for(let k in c)k==="$ref"||k==="allOf"||k in d||delete c[k];if(h.$ref&&f.def)for(let k in c)k==="$ref"||k==="allOf"||k in f.def&&JSON.stringify(c[k])===JSON.stringify(f.def[k])&&delete c[k]}let p=s._zod.parent;if(p&&p!==m){o(p);let f=e.seen.get(p);if(f?.schema.$ref&&(c.$ref=f.schema.$ref,f.def))for(let h in c)h==="$ref"||h==="allOf"||h in f.def&&JSON.stringify(c[h])===JSON.stringify(f.def[h])&&delete c[h]}e.override({zodSchema:s,jsonSchema:c,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let s of[...e.seen.entries()].reverse())o(s[0]);if(e.target!=="openapi-3.0")for(let s of e.seen.entries())tp(s[1].def??s[1].schema);for(let s of e.deferred)s();if(e.intersections.length){let s=new Map;for(let u of e.seen.values())for(let c of[u.schema,u.def]){let d=c?.allOf;if(!Array.isArray(d))continue;let m=s.get(d);m?m.push(c):s.set(d,[c])}for(let u of e.intersections)for(let c of s.get(u)??[])e_(c)}}let t={};if(e.target==="draft-2020-12"?t.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?t.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?t.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let s=e.external.registry.get(r)?.id;if(!s)throw new Error("Schema is missing an `id` property");t.$id=e.external.uri(s)}an(t,i.defId?i.schema:i.def??i.schema);let n=e.metadataRegistry.get(r)?.id;n!==void 0&&t.id===n&&delete t.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let s of e.seen.entries()){let u=s[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,ae(a,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?t.$defs=a:t.definitions=a);try{let s=JSON.parse(JSON.stringify(t));return Object.defineProperty(s,"~standard",{value:{...r["~standard"],jsonSchema:{input:sr(r,"input",e.processors),output:sr(r,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function he(e,r){let i=r??{seen:new Set};if(i.seen.has(e))return!1;i.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return he(o.element,i);if(o.type==="set")return he(o.valueType,i);if(o.type==="lazy")return he(o.getter(),i);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return he(o.innerType,i);if(o.type==="intersection")return he(o.left,i)||he(o.right,i);if(o.type==="record"||o.type==="map")return he(o.keyType,i)||he(o.valueType,i);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:he(o.in,i)||he(o.out,i);if(o.type==="object"){for(let t in o.shape)if(he(o.shape[t],i))return!0;return!1}if(o.type==="union"){for(let t of o.options)if(he(t,i))return!0;return!1}if(o.type==="tuple"){for(let t of o.items)if(he(t,i))return!0;return!!(o.rest&&he(o.rest,i))}return!1}var zc=(e,r={})=>i=>{let o=nt({...i,processors:r});return G(e,o),it(o,e),ot(o,e)},sr=(e,r,i={})=>o=>{let{libraryOptions:t,target:n}=o??{},a=nt({...t??{},target:n,io:r,processors:i});return G(e,a),it(a,e),ot(a,e)};var ur=(e,r,i)=>{(e[r]===void 0||i>e[r])&&(e[r]=i)},cr=(e,r,i)=>{(e[r]===void 0||i<e[r])&&(e[r]=i)},np=(e,r)=>{ur(e,"minimum",r),cr(e,"maximum",r)},sp=(e,r)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(r)||e.multipleOf.push(r)},up=(e,r)=>{e.patterns??(e.patterns=new Set),e.patterns.add(r)},cp=(e,r)=>{e.mime=e.mime?e.mime.filter(i=>r.includes(i)):[...r]},lp=(e,r)=>{e.format=r,r.includes("int")&&(e.isInt=!0)},ip=(e,r)=>ur(e,"minimum",r.minimum),op=(e,r)=>cr(e,"maximum",r.maximum),ap=e=>(r,i)=>{lp(r,i.format);let[o,t]=e[i.format];ur(r,"minimum",o),cr(r,"maximum",t)},t_={greater_than:(e,r)=>ur(e,r.inclusive?"minimum":"exclusiveMinimum",r.value),less_than:(e,r)=>cr(e,r.inclusive?"maximum":"exclusiveMaximum",r.value),multiple_of:(e,r)=>sp(e,r.value),number_format:ap(zr),bigint_format:ap(Ar),min_length:ip,max_length:op,length_equals:(e,r)=>np(e,r.length),min_size:ip,max_size:op,size_equals:(e,r)=>np(e,r.size),string_format:(e,r)=>{lp(e,r.format),r.pattern&&up(e,r.pattern),(r.format==="base64"||r.format==="base64url")&&(e.contentEncoding=r.format),(r.local||r.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,r)=>cp(e,r.mime)};function re(e){let r={},i=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...i.checks??[]]:i.checks??[];for(let n of o)t_[n._zod.def.check]?.(r,n._zod.def);let t=e._zod.bag;t.minimum!==void 0&&ur(r,"minimum",t.minimum),t.exclusiveMinimum!==void 0&&ur(r,"exclusiveMinimum",t.exclusiveMinimum),t.maximum!==void 0&&cr(r,"maximum",t.maximum),t.exclusiveMaximum!==void 0&&cr(r,"exclusiveMaximum",t.exclusiveMaximum),t.multipleOf!==void 0&&sp(r,t.multipleOf),t.format!==void 0&&(r.format??(r.format=t.format),t.format.includes("int")&&(r.isInt=!0)),t.mime&&cp(r,t.mime);for(let n of t.patterns??[])up(r,n);return r}var r_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},n_=new Map([[mi,Ua],[Gr,Ea]]),dp=e=>n_.get(e)??e,Pc=(e,r,i,o)=>{let t=i;t.type="string";let{minimum:n,maximum:a,format:s,patterns:u,contentEncoding:c,laxFormat:d}=re(e);if(typeof n=="number"&&(t.minLength=n),typeof a=="number"&&(t.maxLength=a),s&&(t.format=r_[s]??s,t.format===""&&delete t.format,(s==="time"||d)&&delete t.format),c&&(t.contentEncoding=c),u&&u.size>0){let m=[...u].map(dp);m.length===1?t.pattern=m[0].source:m.length>1&&(t.allOf=[...m.map(p=>({...r.target==="draft-07"||r.target==="draft-04"||r.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},Oc=(e,r,i,o)=>{let t=i,{minimum:n,maximum:a,multipleOf:s,exclusiveMaximum:u,exclusiveMinimum:c,isInt:d}=re(e);t.type=d?"integer":"number";let m=typeof c=="number"&&c>=(n??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),f=r.target==="draft-04"||r.target==="openapi-3.0";if(m?f?(t.minimum=c,t.exclusiveMinimum=!0):t.exclusiveMinimum=c:typeof n=="number"&&(t.minimum=n),p?f?(t.maximum=u,t.exclusiveMaximum=!0):t.exclusiveMaximum=u:typeof a=="number"&&(t.maximum=a),s){let h=new Set;for(let P of s)Number.isFinite(P)&&P!==0?h.add(Math.abs(P)):te(e,r,t,o,`A multipleOf divisor of ${P} cannot be represented in JSON Schema`);let[_,...k]=h;_!==void 0&&(t.multipleOf=_),k.length&&(t.allOf=[...t.allOf??[],...k.map(P=>({multipleOf:P}))])}},Dc=(e,r,i,o)=>{i.type="boolean"},jc=(e,r,i,o)=>{te(e,r,i,o,"BigInt cannot be represented in JSON Schema")},Nc=(e,r,i,o)=>{te(e,r,i,o,"Symbols cannot be represented in JSON Schema")},Uc=(e,r,i,o)=>{r.target==="openapi-3.0"?(i.type="string",i.nullable=!0,i.enum=[null]):i.type="null"},Ec=(e,r,i,o)=>{te(e,r,i,o,"Undefined cannot be represented in JSON Schema")},Cc=(e,r,i,o)=>{te(e,r,i,o,"Void cannot be represented in JSON Schema")},Zc=(e,r,i,o)=>{i.not={}},Rc=(e,r,i,o)=>{},Lc=(e,r,i,o)=>{},Mc=(e,r,i,o)=>{te(e,r,i,o,"Date cannot be represented in JSON Schema")},Vc=(e,r,i,o)=>{let t=e._zod.def,n=Nt(t.entries);if(n.length===0){i.not={};return}n.every(a=>typeof a=="number")&&(i.type="number"),n.every(a=>typeof a=="string")&&(i.type="string"),i.enum=n},Fc=(e,r,i,o)=>{let t=e._zod.def;if(t.values.length===0){i.not={};return}let n=[];for(let a of t.values)if(a===void 0){if(te(e,r,i,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a=="bigint"){if(te(e,r,i,o,"BigInt literals cannot be represented in JSON Schema"))return;n.push(Number(a))}else n.push(a);if(n.length!==0)if(n.length===1){let a=n[0];i.type=a===null?"null":typeof a,r.target==="draft-04"||r.target==="openapi-3.0"?i.enum=[a]:i.const=a}else n.every(a=>typeof a=="number")&&(i.type="number"),n.every(a=>typeof a=="string")&&(i.type="string"),n.every(a=>typeof a=="boolean")&&(i.type="boolean"),n.every(a=>a===null)&&(i.type="null"),i.enum=n},Gc=(e,r,i,o)=>{te(e,r,i,o,"NaN cannot be represented in JSON Schema")},Bc=(e,r,i,o)=>{let t=i,n=e._zod.pattern;if(!n)throw new Error("Pattern not found in template literal");t.type="string",t.pattern=n.source},Jc=(e,r,i,o)=>{let t=i;t.type="string",t.format="binary",t.contentEncoding="binary";let{minimum:n,maximum:a,mime:s}=re(e);n!==void 0&&(t.minLength=n),a!==void 0&&(t.maxLength=a),s&&(s.length===0?t.not={}:s.length===1?t.contentMediaType=s[0]:t.anyOf=s.map(u=>({contentMediaType:u})))},Wc=(e,r,i,o)=>{i.type="boolean"},Kc=(e,r,i,o)=>{te(e,r,i,o,"Custom types cannot be represented in JSON Schema")},Hc=(e,r,i,o)=>{te(e,r,i,o,"Function types cannot be represented in JSON Schema")},Xc=(e,r,i,o)=>{te(e,r,i,o,"Transforms cannot be represented in JSON Schema")},qc=(e,r,i,o)=>{te(e,r,i,o,"Map cannot be represented in JSON Schema")},Yc=(e,r,i,o)=>{te(e,r,i,o,"Set cannot be represented in JSON Schema")},Qc=(e,r,i,o)=>{let t=i,n=e._zod.def,{minimum:a,maximum:s}=re(e);typeof a=="number"&&(t.minItems=a),typeof s=="number"&&(t.maxItems=s),t.type="array",t.items=G(n.element,r,{...o,path:[...o.path,"items"]})};function sn(e){let r=e._zod.def;return r.type==="pipe"&&r.in._zod.traits.has("$ZodTransform")?sn(r.out):r.type==="catch"?sn(r.innerType):e._zod.optin}var el=(e,r,i,o)=>{let t=i,n=e._zod.def,a=n.shape;if(Object.getOwnPropertySymbols(a).length&&te(e,r,t,o,"Symbol keys cannot be represented in JSON Schema"))return;t.type="object",t.properties={};for(let c in a)ae(t.properties,c,G(a[c],r,{...o,path:[...o.path,"properties",c]}));let u=[];for(let c of Object.keys(a)){let d=n.shape[c];(r.io==="input"?sn(d)===void 0:d._zod.optout===void 0)&&u.push(c)}u.length>0&&(t.required=u),n.catchall?._zod.def.type==="never"?t.additionalProperties=!1:n.catchall?n.catchall&&(t.additionalProperties=G(n.catchall,r,{...o,path:[...o.path,"additionalProperties"]})):r.io==="output"&&(t.additionalProperties=!1)},co=(e,r,i,o)=>{let t=e._zod.def,n=t.inclusive===!1,a=t.options.map((s,u)=>G(s,r,{...o,path:[...o.path,n?"oneOf":"anyOf",u]}));n?i.oneOf=a:i.anyOf=a},tl=(e,r,i,o)=>{let t=e._zod.def,n=G(t.left,r,{...o,path:[...o.path,"allOf",0]}),a=G(t.right,r,{...o,path:[...o.path,"allOf",1]}),s=c=>"allOf"in c&&Object.keys(c).length===1,u=[...s(n)?n.allOf:[n],...s(a)?a.allOf:[a]];i.allOf=u,r.intersections.push(u)},rl=(e,r,i,o)=>{let t=i,n=e._zod.def;t.type="array";let a=r.target==="draft-2020-12"?"prefixItems":"items",s=r.target==="draft-2020-12"||r.target==="openapi-3.0"?"items":"additionalItems",u=n.items.map((_,k)=>G(_,r,{...o,path:[...o.path,a,k]})),c=n.rest?G(n.rest,r,{...o,path:[...o.path,s,...r.target==="openapi-3.0"?[n.items.length]:[]]}):null,d=n.items.length;for(;d>0;){let _=n.items[d-1];if(!(r.io==="input"?sn(_)!==void 0:_._zod.optout==="optional"))break;d--}let m=n.items.length,p=!n.rest;r.target==="draft-2020-12"?(t.prefixItems=u,p?t.items=!1:c&&(t.items=c),d>0&&(t.minItems=d),p&&(t.maxItems=m)):r.target==="openapi-3.0"?(t.items={anyOf:u},c&&t.items.anyOf.push(c),d>0&&(t.minItems=d),p&&(t.maxItems=m)):(t.items=u,p?t.additionalItems=!1:c&&(t.additionalItems=c),d>0&&(t.minItems=d),p&&(t.maxItems=m));let{minimum:f,maximum:h}=re(e);typeof f=="number"&&(t.minItems=f),typeof h=="number"&&(t.maxItems=h)};function Ac(e,r,i){if(r.$ref){if(i.has(r))return r;i.add(r);let h=e.get(r)?.def;if(!h)return r;let _=Ac(e,h,i);return _===h?r:_}for(let h of["anyOf","oneOf"]){let _=r[h];if(!Array.isArray(_))continue;let k=_.map(P=>Ac(e,P,i));k.some((P,T)=>P!==_[T])&&(r={...r,[h]:k})}let o=Array.isArray(r.type)?r.type:[r.type],t=!o.includes("string")&&o.some(h=>h==="number"||h==="integer"),n=r.enum??(r.const!==void 0?[r.const]:void 0);if(!t&&!n?.some(h=>typeof h=="number"))return r;let{minimum:a,maximum:s,exclusiveMinimum:u,exclusiveMaximum:c,multipleOf:d,format:m,id:p,...f}=r;return f.enum?f.enum=f.enum.map(h=>typeof h=="number"?String(h):h):typeof f.const=="number"&&(f.const=String(f.const)),t&&(f.type="string",n||(f.pattern=(o.includes("number")?He:Cr).source)),f}var Tc=new WeakMap;function i_(e){let r=new Map;for(let o of e.seen.values())o.def&&!r.has(o.schema)&&r.set(o.schema,o);let i=new Map;for(let o of Tc.get(e)??[]){let t=e.seen.get(o),n=(t?.def??t?.schema)?.propertyNames;if(!n||n===!0||i.has(n))continue;let a=Ac(r,n,new Set);a!==n&&i.set(n,a)}if(i.size)for(let o of e.seen.values())for(let t of[o.schema,o.def]){let n=t&&i.get(t.propertyNames);n&&(t.propertyNames=n)}}var nl=(e,r,i,o)=>{let t=i,n=e._zod.def;t.type="object";let a=n.keyType,s=re(a).patterns;if(n.mode==="loose"&&s&&s.size>0){let d=G(n.valueType,r,{...o,path:[...o.path,"patternProperties","*"]});t.patternProperties={};for(let m of s)ae(t.patternProperties,dp(m).source,d)}else{if(r.target==="draft-07"||r.target==="draft-2020-12"){t.propertyNames=G(n.keyType,r,{...o,path:[...o.path,"propertyNames"]});let d=Tc.get(r);d||(d=[],Tc.set(r,d),r.deferred.push(()=>i_(r))),d.push(e)}t.additionalProperties=G(n.valueType,r,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,c=r.io==="input"&&sn(n.valueType)!==void 0;if(u&&!n.partial&&!c){let d=[...u].filter(m=>typeof m=="string"||typeof m=="number");d.length>0&&(t.required=d.map(String))}},il=(e,r,i,o)=>{let t=e._zod.def,n=G(t.innerType,r,o),a=r.seen.get(e);r.target==="openapi-3.0"?(a.ref=t.innerType,i.nullable=!0):i.anyOf=[n,{type:"null"}]},ol=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);n.ref=t.innerType},al=Symbol();function mp(e,r,i,o,t){let n=!1,a=JSON.stringify(e,(s,u)=>typeof u!="bigint"?u:(n=!0,null));return n?(te(r,i,o,t,"BigInt defaults cannot be represented in JSON Schema"),al):JSON.parse(a)}var sl=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);n.ref=t.innerType;let a=mp(t.defaultValue,e,r,i,o);a!==al&&(i.default=a)},ul=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);if(n.ref=t.innerType,r.io!=="input")return;let a=mp(t.defaultValue,e,r,i,o);a!==al&&(i._prefault=a)},cl=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);n.ref=t.innerType;let a;try{a=t.catchValue(void 0)}catch{te(e,r,i,o,"Dynamic catch values are not supported in JSON Schema");return}i.default=a},ll=(e,r,i,o)=>{let t=e._zod.def,n=t.in._zod.traits.has("$ZodTransform"),a=r.io==="input"?n?t.out:t.in:t.out;G(a,r,o);let s=r.seen.get(e);s.ref=a},dl=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);n.ref=t.innerType,i.readOnly=!0},ml=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);n.ref=t.innerType},lo=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);n.ref=t.innerType},fl=(e,r,i,o)=>{let t=e._zod.innerType;G(t,r,o);let n=r.seen.get(e);n.ref=t},uo={string:Pc,number:Oc,boolean:Dc,bigint:jc,symbol:Nc,null:Uc,undefined:Ec,void:Cc,never:Zc,any:Rc,unknown:Lc,date:Mc,enum:Vc,literal:Fc,nan:Gc,template_literal:Bc,file:Jc,success:Wc,custom:Kc,function:Hc,transform:Xc,map:qc,set:Yc,array:Qc,object:el,union:co,intersection:tl,tuple:rl,record:nl,nullable:il,nonoptional:ol,default:sl,prefault:ul,catch:cl,pipe:ll,readonly:dl,promise:ml,optional:lo,lazy:fl};function mo(e,r){if("_idmap"in e){let o=e,t=nt({...r,processors:uo}),n={};for(let u of o._idmap.entries()){let[c,d]=u;G(d,t)}let a={},s={registry:o,uri:r?.uri,defs:n};t.external=s;for(let u of o._idmap.entries()){let[c,d]=u;it(t,d),ae(a,c,ot(t,d))}if(Object.keys(n).length>0){let u=t.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[u]:n}}return{schemas:a}}let i=nt({...r,processors:uo});return G(e,i),it(i,e),ot(i,e)}var fo=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(r){this.ctx.counter=r}get seen(){return this.ctx.seen}constructor(r){let i=r?.target??"draft-2020-12";i==="draft-4"&&(i="draft-04"),i==="draft-7"&&(i="draft-07"),this.ctx=nt({processors:uo,target:i,...r?.metadata&&{metadata:r.metadata},...r?.unrepresentable&&{unrepresentable:r.unrepresentable},...r?.override&&{override:r.override},...r?.io&&{io:r.io}})}process(r,i={path:[],schemaPath:[]}){return G(r,this.ctx,i)}emit(r,i){i&&(i.cycles&&(this.ctx.cycles=i.cycles),i.reused&&(this.ctx.reused=i.reused),i.external&&(this.ctx.external=i.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,it(this.ctx,r);let o=ot(this.ctx,r),{"~standard":t,...n}=o;return n}};var fp={};var vr={};Je(vr,{ZodAny:()=>Ul,ZodArray:()=>Rl,ZodBase64:()=>Do,ZodBase64URL:()=>jo,ZodBigInt:()=>gr,ZodBigIntFormat:()=>Eo,ZodBoolean:()=>pr,ZodCIDRv4:()=>Po,ZodCIDRv6:()=>Oo,ZodCUID:()=>xo,ZodCUID2:()=>ko,ZodCatch:()=>ad,ZodCodec:()=>vn,ZodCreditCard:()=>zl,ZodCustom:()=>bn,ZodCustomStringFormat:()=>Pt,ZodDate:()=>dn,ZodDefault:()=>ed,ZodDiscriminatedUnion:()=>Ml,ZodE164:()=>No,ZodEmail:()=>$o,ZodEmoji:()=>_o,ZodEnum:()=>dr,ZodExactOptional:()=>Lo,ZodFile:()=>Xl,ZodFunction:()=>hd,ZodGUID:()=>yo,ZodIBAN:()=>Al,ZodIPv4:()=>Ao,ZodIPv6:()=>To,ZodISODate:()=>st,ZodISODateTime:()=>at,ZodISODuration:()=>ct,ZodISOTime:()=>ut,ZodInstanceOf:()=>$d,ZodIntersection:()=>Vl,ZodJWT:()=>Uo,ZodKSUID:()=>zo,ZodLazy:()=>fd,ZodLiteral:()=>Hl,ZodMAC:()=>Sl,ZodMap:()=>Wl,ZodNaN:()=>ud,ZodNanoID:()=>wo,ZodNever:()=>Cl,ZodNonOptional:()=>Mo,ZodNull:()=>jl,ZodNullable:()=>Ql,ZodNumber:()=>fr,ZodNumberFormat:()=>Ot,ZodObject:()=>fn,ZodOptional:()=>gn,ZodPipe:()=>hn,ZodPrefault:()=>rd,ZodPreprocess:()=>cd,ZodPromise:()=>gd,ZodReadonly:()=>ld,ZodRecord:()=>lr,ZodSet:()=>Kl,ZodString:()=>mr,ZodStringFormat:()=>B,ZodSuccess:()=>od,ZodSymbol:()=>Ol,ZodTemplateLiteral:()=>md,ZodTransform:()=>ql,ZodTuple:()=>Gl,ZodType:()=>Z,ZodULID:()=>Io,ZodURL:()=>ln,ZodUUID:()=>Me,ZodUndefined:()=>Dl,ZodUnion:()=>pn,ZodUnknown:()=>El,ZodVoid:()=>Zl,ZodXID:()=>So,ZodXor:()=>Ll,_ZodString:()=>bo,_default:()=>td,_function:()=>Ig,any:()=>rg,array:()=>mn,base64:()=>Ep,base64url:()=>Cp,bigint:()=>qp,boolean:()=>Pl,catch:()=>sd,check:()=>Sg,cidrv4:()=>Np,cidrv6:()=>Up,codec:()=>_g,creditCard:()=>Rp,cuid:()=>Sp,cuid2:()=>zp,currencyCode:()=>Bp,custom:()=>zg,date:()=>ig,describe:()=>Ag,discriminatedUnion:()=>lg,e164:()=>Zp,email:()=>hp,emoji:()=>kp,enum:()=>Zo,exactOptional:()=>Yl,file:()=>vg,float32:()=>Wp,float64:()=>Kp,function:()=>Ig,guid:()=>vp,hash:()=>Jp,hex:()=>Gp,hostname:()=>Fp,httpUrl:()=>xp,iban:()=>Lp,instanceof:()=>Pg,int:()=>ho,int32:()=>Hp,int64:()=>Yp,intersection:()=>Fl,invertCodec:()=>wg,ipv4:()=>Op,ipv6:()=>jp,json:()=>Dg,jwt:()=>Mp,keyof:()=>og,ksuid:()=>Pp,lazy:()=>pd,literal:()=>hg,looseObject:()=>ug,looseRecord:()=>mg,mac:()=>Dp,map:()=>fg,meta:()=>Tg,nan:()=>yg,nanoid:()=>Ip,nativeEnum:()=>gg,never:()=>Co,nonoptional:()=>id,null:()=>Nl,nullable:()=>cn,nullish:()=>bg,number:()=>Tl,object:()=>ag,optional:()=>At,partialRecord:()=>dg,pipe:()=>vo,prefault:()=>nd,preprocess:()=>jg,promise:()=>kg,readonly:()=>dd,record:()=>Jl,refine:()=>vd,set:()=>pg,strictObject:()=>sg,string:()=>un,stringFormat:()=>Vp,stringbool:()=>Og,success:()=>$g,superRefine:()=>bd,symbol:()=>eg,templateLiteral:()=>xg,transform:()=>Ro,tuple:()=>Bl,uint32:()=>Xp,uint64:()=>Qp,ulid:()=>Ap,undefined:()=>tg,union:()=>hr,unknown:()=>zt,url:()=>wp,uuid:()=>bp,uuidv4:()=>$p,uuidv6:()=>yp,uuidv7:()=>_p,void:()=>ng,xid:()=>Tp,xor:()=>cg});var po={};Je(po,{endsWith:()=>Qt,gt:()=>Re,gte:()=>Se,includes:()=>qt,length:()=>It,lowercase:()=>Ht,lt:()=>Ze,lte:()=>Ie,maxLength:()=>kt,maxSize:()=>rt,mime:()=>tr,minLength:()=>Xe,minSize:()=>Le,multipleOf:()=>tt,negative:()=>io,nonnegative:()=>ao,nonpositive:()=>oo,normalize:()=>rr,overwrite:()=>Ee,positive:()=>no,properties:()=>er,property:()=>so,regex:()=>Kt,size:()=>xt,slugify:()=>ar,startsWith:()=>Yt,toLowerCase:()=>ir,toUpperCase:()=>or,trim:()=>nr,uppercase:()=>Xt});var pp=new WeakSet([Object.prototype,Error.prototype]);function go(e,r,i){Object.defineProperty(e,r,{configurable:!0,enumerable:!1,get(){let o=i(this);return Object.defineProperty(this,r,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,r,{value:o,configurable:!0,writable:!0})}})}var gp=(e,r)=>{ga.init(e,r),e.name="ZodError";let i=Object.getPrototypeOf(e);pp.has(i)||(pp.add(i),go(i,"format",o=>t=>jr(o,t)),go(i,"flatten",o=>t=>Dr(o,t)),go(i,"addIssue",o=>t=>{o.issues.push(t),o.message=JSON.stringify(o.issues,Ut,2)}),go(i,"addIssues",o=>t=>{o.issues.push(...t),o.message=JSON.stringify(o.issues,Ut,2)}),Object.defineProperty(i,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},a_=g("ZodError",gp),ke=g("ZodError",gp,void 0,{Parent:Error});var pl=Rt(ke),gl=Lt(ke),hl=Mt(ke),vl=Vt(ke),bl=Fn(ke),$l=Gn(ke),yl=Bn(ke),_l=Jn(ke),wl=Wn(ke),xl=Kn(ke),kl=Hn(ke),Il=Xn(ke);function u_(){ie.localeError||Y(Ai())}function Tt(){ie.memoizer||Y({memoizer:qr()})}var Z=g("ZodType",(e,r)=>(u_(),C.init(e,r),e.def=r,e.type=r.type,e),{check(...e){let r=this.def;return this.clone($.mergeDefs(r,{checks:[...r.checks??[],...e.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,r){return V(this,e,r)},brand(){return this},register(e,r){return e.add(this,r),this},refine(e,r){return this.check(vd(e,r))},superRefine(e,r){return this.check(bd(e,r))},overwrite(e){return this.check(Ee(e))},optional(){return At(this)},exactOptional(){return Yl(this)},nullable(){return cn(this)},nullish(){return At(cn(this))},nonoptional(e){return id(this,e)},array(){return mn(this)},or(e){return hr([this,e])},and(e){return Fl(this,e)},transform(e){return vo(this,Ro(e))},default(e){return td(this,e)},prefault(e){return nd(this,e)},catch(e){return sd(this,e)},pipe(e){return vo(this,e)},readonly(){return dd(this)},describe(e){let r=this.clone();return se.add(r,{description:e}),r},meta(...e){if(e.length===0)return se.get(this);let r=this.clone();return se.add(r,e[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...r){return r.length===0?e(this):e(this,...r)},get"~standard"(){return $.hide(this,"~standard",{...si(this),jsonSchema:{input:sr(this,"input"),output:sr(this,"output")}})},set"~standard"(e){$.own(this,"~standard",e)},parse:function e(r,i){return pl(this,r,i,{callee:e})},parseAsync:async function e(r,i){return await gl(this,r,i,{callee:e})},safeParse(e,r){return hl(this,e,r)},async safeParseAsync(e,r){return vl(this,e,r)},get spa(){return this?.safeParseAsync},set spa(e){$.own(this,"spa",e)},validate(e,r){return Nr(this,e,r)},validateAsync(e,r){return Ur(this,e,r)},encode:function e(r,i){return bl(this,r,i,{callee:e})},decode:function e(r,i){return $l(this,r,i,{callee:e})},encodeAsync:async function e(r,i){return await yl(this,r,i,{callee:e})},decodeAsync:async function e(r,i){return await _l(this,r,i,{callee:e})},safeEncode(e,r){return wl(this,e,r)},safeDecode(e,r){return xl(this,e,r)},async safeEncodeAsync(e,r){return kl(this,e,r)},async safeDecodeAsync(e,r){return Il(this,e,r)},toJSONSchema(e){return zc(this,{})(e)},get description(){return se.get(this)?.description},get _def(){return this._zod.def}}),bo=g("_ZodString",(e,r)=>{bt.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Pc(e,i,o,t)},$.derived({format:e=>re(e).format??null,minLength:e=>re(e).minimum??null,maxLength:e=>re(e).maximum??null},{regex(...e){return this.check(Kt(...e))},includes(...e){return this.check(qt(...e))},startsWith(...e){return this.check(Yt(...e))},endsWith(...e){return this.check(Qt(...e))},min(...e){return this.check(Xe(...e))},max(...e){return this.check(kt(...e))},length(...e){return this.check(It(...e))},nonempty(...e){return this.check(Xe(1,...e))},lowercase(e){return this.check(Ht(e))},uppercase(e){return this.check(Xt(e))},trim(){return this.check(nr())},normalize(...e){return this.check(rr(...e))},toLowerCase(){return this.check(ir())},toUpperCase(){return this.check(or())},slugify(){return this.check(ar())}})),mr=g("ZodString",(e,r)=>{bt.init(e,r),bo.init(e,r)},{email(e){return this.check(Ei($o,e))},url(e){return this.check(en(ln,e))},jwt(e){return this.check(ro(Uo,e))},emoji(e){return this.check(Vi(_o,e))},guid(e){return this.check(Ci(yo,e))},uuid(e){return this.check(Zi(Me,e))},uuidv4(e){return this.check(Ri(Me,e))},uuidv6(e){return this.check(Li(Me,e))},uuidv7(e){return this.check(Mi(Me,e))},nanoid(e){return this.check(Fi(wo,e))},cuid(e){return this.check(Gi(xo,e))},cuid2(e){return this.check(Bi(ko,e))},ulid(e){return this.check(Ji(Io,e))},base64(e){return this.check(Qi(Do,e))},base64url(e){return this.check(eo(jo,e))},xid(e){return this.check(Wi(So,e))},ksuid(e){return this.check(Ki(zo,e))},ipv4(e){return this.check(Hi(Ao,e))},ipv6(e){return this.check(Xi(To,e))},cidrv4(e){return this.check(qi(Po,e))},cidrv6(e){return this.check(Yi(Oo,e))},e164(e){return this.check(to(No,e))},datetime(e){return this.check(tn(at,e))},date(e){return this.check(rn(st,e))},time(e){return this.check(nn(ut,e))},duration(e){return this.check(on(ct,e))}});function un(e){return Fu(mr,e)}var B=g("ZodStringFormat",(e,r)=>{F.init(e,r),bo.init(e,r)}),at=g("ZodISODateTime",(e,r)=>{Us.init(e,r),B.init(e,r)}),st=g("ZodISODate",(e,r)=>{Es.init(e,r),B.init(e,r)}),ut=g("ZodISOTime",(e,r)=>{Cs.init(e,r),B.init(e,r)}),ct=g("ZodISODuration",(e,r)=>{Zs.init(e,r),B.init(e,r)}),$o=g("ZodEmail",(e,r)=>{ks.init(e,r),B.init(e,r)});function hp(e){return Ei($o,e)}var yo=g("ZodGUID",(e,r)=>{ws.init(e,r),B.init(e,r)});function vp(e){return Ci(yo,e)}var Me=g("ZodUUID",(e,r)=>{xs.init(e,r),B.init(e,r)});function bp(e){return Zi(Me,e)}function $p(e){return Ri(Me,e)}function yp(e){return Li(Me,e)}function _p(e){return Mi(Me,e)}var ln=g("ZodURL",(e,r)=>{zs.init(e,r),B.init(e,r)});function wp(e){return en(ln,e)}function xp(e){return en(ln,{protocol:Er,hostname:Za,...$.normalizeParams(e)})}var _o=g("ZodEmoji",(e,r)=>{As.init(e,r),B.init(e,r)});function kp(e){return Vi(_o,e)}var wo=g("ZodNanoID",(e,r)=>{Ts.init(e,r),B.init(e,r)});function Ip(e){return Fi(wo,e)}var xo=g("ZodCUID",(e,r)=>{Ps.init(e,r),B.init(e,r)});function Sp(e){return Gi(xo,e)}var ko=g("ZodCUID2",(e,r)=>{Os.init(e,r),B.init(e,r)});function zp(e){return Bi(ko,e)}var Io=g("ZodULID",(e,r)=>{Ds.init(e,r),B.init(e,r)});function Ap(e){return Ji(Io,e)}var So=g("ZodXID",(e,r)=>{js.init(e,r),B.init(e,r)});function Tp(e){return Wi(So,e)}var zo=g("ZodKSUID",(e,r)=>{Ns.init(e,r),B.init(e,r)});function Pp(e){return Ki(zo,e)}var Ao=g("ZodIPv4",(e,r)=>{Rs.init(e,r),B.init(e,r)});function Op(e){return Hi(Ao,e)}var Sl=g("ZodMAC",(e,r)=>{Ms.init(e,r),B.init(e,r)});function Dp(e){return Bu(Sl,e)}var To=g("ZodIPv6",(e,r)=>{Ls.init(e,r),B.init(e,r)});function jp(e){return Xi(To,e)}var Po=g("ZodCIDRv4",(e,r)=>{Vs.init(e,r),B.init(e,r)});function Np(e){return qi(Po,e)}var Oo=g("ZodCIDRv6",(e,r)=>{Fs.init(e,r),B.init(e,r)});function Up(e){return Yi(Oo,e)}var Do=g("ZodBase64",(e,r)=>{Gs.init(e,r),B.init(e,r)});function Ep(e){return Qi(Do,e)}var jo=g("ZodBase64URL",(e,r)=>{Bs.init(e,r),B.init(e,r)});function Cp(e){return eo(jo,e)}var No=g("ZodE164",(e,r)=>{Js.init(e,r),B.init(e,r)});function Zp(e){return to(No,e)}var zl=g("ZodCreditCard",(e,r)=>{Ws.init(e,r),B.init(e,r)});function Rp(e){return Ju(zl,e)}var Al=g("ZodIBAN",(e,r)=>{Ks.init(e,r),B.init(e,r)});function Lp(e){return Wu(Al,e)}var Uo=g("ZodJWT",(e,r)=>{Hs.init(e,r),B.init(e,r)});function Mp(e){return ro(Uo,e)}var Pt=g("ZodCustomStringFormat",(e,r)=>{Xs.init(e,r),B.init(e,r)});function Vp(e,r,i={}){return St(Pt,e,r,i)}function Fp(e){return St(Pt,"hostname",Ca,e)}function Gp(e){return St(Pt,"hex",Ya,e)}function Bp(e){return St(Pt,"currency_code",La,e)}function Jp(e,r){let i=r?.enc??"hex",o=`${e}_${i}`,t=Te[o];if(!t)throw new Error(`Unrecognized hash format: ${o}`);return St(Pt,o,t,r)}var fr=g("ZodNumber",(e,r)=>{vi.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Oc(e,i,o,t),e.isFinite=!0},$.derived({minValue:e=>{let{minimum:r,exclusiveMinimum:i}=re(e);return Math.max(r??Number.NEGATIVE_INFINITY,i??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:r,exclusiveMaximum:i}=re(e);return Math.min(r??Number.POSITIVE_INFINITY,i??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:r,multipleOf:i}=re(e);return!!r||!!i?.some(Number.isSafeInteger)},format:e=>re(e).format??null},{gt(e,r){return this.check(Re(e,r))},gte(e,r){return this.check(Se(e,r))},min(e,r){return this.check(Se(e,r))},lt(e,r){return this.check(Ze(e,r))},lte(e,r){return this.check(Ie(e,r))},max(e,r){return this.check(Ie(e,r))},int(e){return this.check(ho(e))},safe(e){return this.check(ho(e))},positive(e){return this.check(Re(0,e))},nonnegative(e){return this.check(Se(0,e))},negative(e){return this.check(Ze(0,e))},nonpositive(e){return this.check(Ie(0,e))},multipleOf(e,r){return this.check(tt(e,r))},step(e,r){return this.check(tt(e,r))},finite(){return this}}));function Tl(e){return Hu(fr,e)}var Ot=g("ZodNumberFormat",(e,r)=>{qs.init(e,r),fr.init(e,r)});function ho(e){return qu(Ot,e)}function Wp(e){return Yu(Ot,e)}function Kp(e){return Qu(Ot,e)}function Hp(e){return ec(Ot,e)}function Xp(e){return tc(Ot,e)}var pr=g("ZodBoolean",(e,r)=>{Br.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Dc(e,i,o,t)});function Pl(e){return rc(pr,e)}var gr=g("ZodBigInt",(e,r)=>{bi.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>jc(e,i,o,t)},$.derived({minValue:e=>re(e).minimum??null,maxValue:e=>re(e).maximum??null,format:e=>re(e).format??null},{gte(e,r){return this.check(Se(e,r))},min(e,r){return this.check(Se(e,r))},gt(e,r){return this.check(Re(e,r))},lt(e,r){return this.check(Ze(e,r))},lte(e,r){return this.check(Ie(e,r))},max(e,r){return this.check(Ie(e,r))},positive(e){return this.check(Re(BigInt(0),e))},negative(e){return this.check(Ze(BigInt(0),e))},nonpositive(e){return this.check(Ie(BigInt(0),e))},nonnegative(e){return this.check(Se(BigInt(0),e))},multipleOf(e,r){return this.check(tt(e,r))}}));function qp(e){return ic(gr,e)}var Eo=g("ZodBigIntFormat",(e,r)=>{Ys.init(e,r),gr.init(e,r)});function Yp(e){return ac(Eo,e)}function Qp(e){return sc(Eo,e)}var Ol=g("ZodSymbol",(e,r)=>{Qs.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Nc(e,i,o,t)});function eg(e){return uc(Ol,e)}var Dl=g("ZodUndefined",(e,r)=>{eu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Ec(e,i,o,t)});function tg(e){return cc(Dl,e)}var jl=g("ZodNull",(e,r)=>{tu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Uc(e,i,o,t)});function Nl(e){return lc(jl,e)}var Ul=g("ZodAny",(e,r)=>{ru.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Rc(e,i,o,t)});function rg(){return dc(Ul)}var El=g("ZodUnknown",(e,r)=>{nu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Lc(e,i,o,t)});function zt(){return mc(El)}var Cl=g("ZodNever",(e,r)=>{iu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Zc(e,i,o,t)});function Co(e){return fc(Cl,e)}var Zl=g("ZodVoid",(e,r)=>{ou.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Cc(e,i,o,t)});function ng(e){return pc(Zl,e)}var dn=g("ZodDate",(e,r)=>{au.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Mc(e,i,o,t),e.min=(i,o)=>e.check(Se(i,o)),e.max=(i,o)=>e.check(Ie(i,o))},$.derived({minDate:e=>{let{minimum:r}=re(e);return r?new Date(r):null},maxDate:e=>{let{maximum:r}=re(e);return r?new Date(r):null}},{}));function ig(e){return gc(dn,e)}var Rl=g("ZodArray",(e,r)=>{Tt(),su.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Qc(e,i,o,t),e.element=r.element},{min(e,r){return this.check(Xe(e,r))},nonempty(e){return this.check(Xe(1,e))},max(e,r){return this.check(kt(e,r))},length(e,r){return this.check(It(e,r))},unwrap(){return this.element}});function mn(e,r){return bc(Rl,e,r)}function og(e){let r=e._zod.def.shape;return Zo(Object.keys(r))}var fn=g("ZodObject",(e,r)=>{Tt(),uu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>el(e,i,o,t),$.installLazyProp(e,"shape",i=>i._zod.def.shape,!1)},{keyof(){return Zo(Object.keys(this._zod.def.shape))},catchall(e){return this.clone($.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone($.mergeDefs(this._zod.def,{catchall:zt()}))},loose(){return this.clone($.mergeDefs(this._zod.def,{catchall:zt()}))},strict(){return this.clone($.mergeDefs(this._zod.def,{catchall:Co()}))},strip(){return this.clone($.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return $.extend(this,e)},safeExtend(e){return $.safeExtend(this,e)},merge(e){return $.merge(this,e)},pick(e){return $.pick(this,e)},omit(e){return $.omit(this,e)},partial(...e){return $.partial(gn,this,e[0])},exactPartial(...e){return $.partial(Lo,this,e[0],"exactPartial")},required(...e){return $.required(Mo,this,e[0])}});function ag(e,r){let i={type:"object",shape:e??{},...$.normalizeParams(r)};return new fn(i)}function sg(e,r){return new fn({type:"object",shape:e,catchall:Co(),...$.normalizeParams(r)})}function ug(e,r){return new fn({type:"object",shape:e,catchall:zt(),...$.normalizeParams(r)})}var pn=g("ZodUnion",(e,r)=>{Jr.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>co(e,i,o,t),e.options=r.options});function hr(e,r){return new pn({type:"union",options:e,...$.normalizeParams(r)})}var Ll=g("ZodXor",(e,r)=>{pn.init(e,r),cu.init(e,r),e._zod.processJSONSchema=(i,o,t)=>co(e,i,o,t),e.options=r.options});function cg(e,r){return new Ll({type:"union",options:e,inclusive:!1,...$.normalizeParams(r)})}var Ml=g("ZodDiscriminatedUnion",(e,r)=>{pn.init(e,r),du.init(e,r)});function lg(e,r,i){return new Ml({type:"union",options:r,discriminator:e,...$.normalizeParams(i)})}var Vl=g("ZodIntersection",(e,r)=>{mu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>tl(e,i,o,t)});function Fl(e,r){return new Vl({type:"intersection",left:e,right:r})}var Gl=g("ZodTuple",(e,r)=>{Tt(),$i.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>rl(e,i,o,t)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(r=>new gn({type:"optional",innerType:r}))})}});function Bl(e,r,i){let o=r instanceof C,t=o?i:r,n=o?r:null;return new Gl({type:"tuple",items:e,rest:n,...$.normalizeParams(t)})}var lr=g("ZodRecord",(e,r)=>{Tt(),fu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>nl(e,i,o,t),e.keyType=r.keyType,e.valueType=r.valueType});function Jl(e,r,i){return!r||!r._zod?new lr({type:"record",keyType:un(),valueType:e,...$.normalizeParams(r)}):new lr({type:"record",keyType:e,valueType:r,...$.normalizeParams(i)})}function dg(e,r,i){return new lr({type:"record",keyType:e,valueType:r,...$.normalizeParams(i),partial:!0})}function mg(e,r,i){return new lr({type:"record",keyType:e,valueType:r,mode:"loose",...$.normalizeParams(i)})}var Wl=g("ZodMap",(e,r)=>{Tt(),pu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>qc(e,i,o,t),e.keyType=r.keyType,e.valueType=r.valueType,e.min=(...i)=>e.check(Le(...i)),e.nonempty=i=>e.check(Le(1,i)),e.max=(...i)=>e.check(rt(...i)),e.size=(...i)=>e.check(xt(...i))});function fg(e,r,i){return new Wl({type:"map",keyType:e,valueType:r,...$.normalizeParams(i)})}var Kl=g("ZodSet",(e,r)=>{Tt(),gu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Yc(e,i,o,t),e.min=(...i)=>e.check(Le(...i)),e.nonempty=i=>e.check(Le(1,i)),e.max=(...i)=>e.check(rt(...i)),e.size=(...i)=>e.check(xt(...i))});function pg(e,r){return new Kl({type:"set",valueType:e,...$.normalizeParams(r)})}var dr=g("ZodEnum",(e,r)=>{hu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(o,t,n)=>Vc(e,o,t,n),e.enum=r.entries,e.options=[...e._zod.values];let i=new Set(Object.keys(r.entries));e.extract=(o,t)=>{let n={};for(let a of o)if(i.has(a))n[a]=r.entries[a];else throw new Error(`Key ${a} not found in enum`);return new dr({...r,checks:[],...$.normalizeParams(t),entries:n})},e.exclude=(o,t)=>{let n={...r.entries};for(let a of o)if(i.has(a))delete n[a];else throw new Error(`Key ${a} not found in enum`);return new dr({...r,checks:[],...$.normalizeParams(t),entries:n})}});function Zo(e,r){let i=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new dr({type:"enum",entries:i,...$.normalizeParams(r)})}function gg(e,r){return new dr({type:"enum",entries:e,...$.normalizeParams(r)})}var Hl=g("ZodLiteral",(e,r)=>{vu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Fc(e,i,o,t),e.values=new Set(r.values),Object.defineProperty(e,"value",{get(){if(r.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});function hg(e,r){return new Hl({type:"literal",values:Array.isArray(e)?e:[e],...$.normalizeParams(r)})}var Xl=g("ZodFile",(e,r)=>{bu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Jc(e,i,o,t),e.min=(i,o)=>e.check(Le(i,o)),e.max=(i,o)=>e.check(rt(i,o)),e.mime=(i,o)=>e.check(tr(Array.isArray(i)?i:[i],o))});function vg(e){return $c(Xl,e)}var ql=g("ZodTransform",(e,r)=>{Tt(),$u.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Xc(e,i,o,t),e._zod.parse=(i,o)=>{if(o.direction==="backward")throw new et(e.constructor.name);i.addIssue=n=>{if(typeof n=="string")i.issues.push($.issue(n,i.value,r));else{let a=n;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),"input"in a||(a.input=i.value),a.inst??(a.inst=e),i.issues.push($.issue(a))}};let t=r.transform(i.value,i);return t instanceof Promise?t.then(n=>(i.value=n,i)):(i.value=t,i)}});function Ro(e){return new ql({type:"transform",transform:e})}var gn=g("ZodOptional",(e,r)=>{yi.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>lo(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function At(e){return new gn({type:"optional",innerType:e})}var Lo=g("ZodExactOptional",(e,r)=>{yu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>lo(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function Yl(e){return new Lo({type:"optional",innerType:e})}var Ql=g("ZodNullable",(e,r)=>{_u.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>il(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function cn(e){return new Ql({type:"nullable",innerType:e})}function bg(e){return At(cn(e))}var ed=g("ZodDefault",(e,r)=>{wu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>sl(e,i,o,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function td(e,r){return new ed({type:"default",innerType:e,get defaultValue(){return typeof r=="function"?r():$.shallowClone(r)}})}var rd=g("ZodPrefault",(e,r)=>{xu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>ul(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function nd(e,r){return new rd({type:"prefault",innerType:e,get defaultValue(){return typeof r=="function"?r():$.shallowClone(r)}})}var Mo=g("ZodNonOptional",(e,r)=>{ku.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>ol(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function id(e,r){return new Mo({type:"nonoptional",innerType:e,...$.normalizeParams(r)})}var od=g("ZodSuccess",(e,r)=>{Iu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Wc(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function $g(e){return new od({type:"success",innerType:e})}var ad=g("ZodCatch",(e,r)=>{Su.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>cl(e,i,o,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function sd(e,r){return new ad({type:"catch",innerType:e,catchValue:typeof r=="function"?r:$.constantCatch(r)})}var ud=g("ZodNaN",(e,r)=>{zu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Gc(e,i,o,t)});function yg(e){return vc(ud,e)}var hn=g("ZodPipe",(e,r)=>{_i.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>ll(e,i,o,t),e.in=r.in,e.out=r.out});function vo(e,r){return new hn({type:"pipe",in:e,out:r})}var vn=g("ZodCodec",(e,r)=>{hn.init(e,r),Wr.init(e,r)});function _g(e,r,i){return new vn({type:"pipe",in:e,out:r,transform:i.decode,reverseTransform:i.encode})}function wg(e){let r=e._zod.def;return new vn({type:"pipe",in:r.out,out:r.in,transform:r.reverseTransform,reverseTransform:r.transform})}var cd=g("ZodPreprocess",(e,r)=>{hn.init(e,r),Au.init(e,r)}),ld=g("ZodReadonly",(e,r)=>{Tu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>dl(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function dd(e){return new ld({type:"readonly",innerType:e})}var md=g("ZodTemplateLiteral",(e,r)=>{Pu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Bc(e,i,o,t)});function xg(e,r){return new md({type:"template_literal",parts:e,...$.normalizeParams(r)})}var fd=g("ZodLazy",(e,r)=>{Kr.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>fl(e,i,o,t),e.unwrap=()=>e._zod.def.getter()});function pd(e){return new fd({type:"lazy",getter:e})}var gd=g("ZodPromise",(e,r)=>{Du.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>ml(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function kg(e){return new gd({type:"promise",innerType:e})}var hd=g("ZodFunction",(e,r)=>{Ou.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Hc(e,i,o,t)});function Ig(e){return new hd({type:"function",input:Array.isArray(e?.input)?Bl(e?.input):e?.input??mn(zt()),output:e?.output??zt()})}var bn=g("ZodCustom",(e,r)=>{ju.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Kc(e,i,o,t)});function Sg(e){let r=new K({check:"custom"});return r._zod.check=e,r}function zg(e,r){return yc(bn,e??(()=>!0),r)}function vd(e,r={}){return _c(bn,e,r)}function bd(e,r){return wc(e,r)}var Ag=xc,Tg=kc,$d=g("ZodInstanceOf",(e,r)=>{bn.init(e,r)},{properties(e,r){return this.check(er(e,r))}});function Pg(e,r={}){let i=new $d({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...$.normalizeParams(r)});return i._zod.bag.Class=e,i._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:i,path:[...i._zod.def.path??[]]})},i}var Og=(...e)=>Ic({Codec:vn,Boolean:pr,String:mr},...e);function Dg(e){let r=pd(()=>hr([un(e),Tl(),Pl(),Nl(),mn(r),Jl(un(),r)]));return r}function jg(e,r){return new cd({type:"pipe",in:Ro(e),out:r})}var c_={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function l_(e){Y({customError:e})}function d_(){return Y().customError}var yd;yd||(yd={});var $n={};Je($n,{ZodISODate:()=>st,ZodISODateTime:()=>at,ZodISODuration:()=>ct,ZodISOTime:()=>ut,date:()=>f_,datetime:()=>m_,duration:()=>g_,time:()=>p_});function m_(e){return tn(at,e)}function f_(e){return rn(st,e)}function p_(e){return nn(ut,e)}function g_(e){return on(ct,e)}var O={...vr,...po,iso:$n},h_=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function v_(e,r){let i=e.$schema;return i==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":i==="http://json-schema.org/draft-07/schema#"?"draft-7":i==="http://json-schema.org/draft-04/schema#"?"draft-4":r??"draft-2020-12"}function Ng(e,r){return e.map((i,o)=>o<r?i:i.optional())}function b_(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function $_(e,r){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let i=e.slice(1).split("/").filter(Boolean);if(i.length===0)return r.rootSchema;let o=r.version==="draft-2020-12"?"$defs":"definitions";if(i[0]===o){let t=i[1]===void 0?void 0:b_(i[1]);if(!t||!r.defs[t])throw new Error(`Reference not found: ${e}`);return r.defs[t]}throw new Error(`Reference not found: ${e}`)}function y_(e,r){return O.transform(o=>o).check(o=>{let t=o.value;if(typeof t!="object"||t===null||Array.isArray(t))return;let n=Object.getOwnPropertyNames(t);if(r.minProperties!==void 0&&n.length<r.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:r.minProperties,inclusive:!0,message:`Too small: expected object to have >=${r.minProperties} properties`,input:t,inst:e,continue:!0}),r.maxProperties!==void 0&&n.length>r.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:r.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${r.maxProperties} properties`,input:t,inst:e,continue:!0}),r.keySchema)for(let a of n){let s=r.keySchema.safeParse(a);s.success||o.issues.push({code:"invalid_key",origin:"record",issues:s.error.issues,input:a,path:[a],continue:!0})}}).pipe(e)}function _d(e,r){if(e===null)return"z";let i=typeof e;if(i!=="object"){if(i==="number"&&Number.isNaN(e))return null;let o=String(e);return`${i[0]}${o.length}:${o}`}if(r.has(e))return null;r.add(e);try{if(Array.isArray(e)){let n=[];for(let a of e){let s=_d(a,r);if(s===null)return null;n.push(s)}return`a${n.length}:[${n.join(",")}]`}let o=Object.keys(e).sort(),t=[];for(let n of o){let a=_d(e[n],r);if(a===null)return null;t.push(`${n.length}:${n}=${a}`)}return`o${t.length}:{${t.join(",")}}`}finally{r.delete(e)}}var __=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),w_=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function yn(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(yn):typeof e.$ref=="string"?!0:Object.entries(e).some(([r,i])=>__.has(r)?yn(i):!w_.has(r)||typeof i!="object"||i===null?!1:Object.values(i).some(yn))}function Ug(e){return e===1?"element":"elements"}function x_(e,r){return O.transform(o=>o).check(o=>{let t=o.value;if(Array.isArray(t)){if(r.uniqueItems===!0){let n=new Map;for(let a=0;a<t.length;a++){let s=_d(t[a],new Set);if(s===null)continue;let u=n.get(s);if(u===void 0){n.set(s,a);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${a} duplicates the one at index ${u}`,input:t,path:[a],continue:!0})}}if(r.containsSchema){let n=r.minContains??1,a=r.maxContains!==void 0?r.maxContains+1:Number.POSITIVE_INFINITY,s=0;for(let u of t)if(r.containsSchema.safeParse(u).success&&++s>=a)break;s<n&&o.issues.push({code:"custom",message:`Array must contain at least ${n} matching ${Ug(n)}; found ${s}`,input:t,continue:!0}),r.maxContains!==void 0&&s>r.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${r.maxContains} matching ${Ug(r.maxContains)}`,input:t,continue:!0})}}}).pipe(e)}function Eg(e,r){if(e!==!1)return e===void 0||e===!0?O.any():ve(e,r)}var k_=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function Cg(e,r){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return O.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let t=e.$ref;if(r.refs.has(t))return r.refs.get(t);if(r.processing.has(t))return O.lazy(()=>{if(!r.refs.has(t))throw new Error(`Circular reference not resolved: ${t}`);return r.refs.get(t)});r.processing.add(t);let n=$_(t,r),a=ve(n,r);return r.refs.set(t,a),r.processing.delete(t),a}if(e.enum!==void 0){let t=e.enum;if(r.version==="openapi-3.0"&&e.nullable===!0&&t.length===1&&t[0]===null)return O.null();if(t.length===0)return O.never();if(t.length===1)return O.literal(t[0]);if(t.every(a=>typeof a=="string"))return O.enum(t);let n=t.map(a=>O.literal(a));return n.length<2?n[0]:O.union([n[0],n[1],...n.slice(2)])}if(e.const!==void 0)return O.literal(e.const);let i=e.type;if(Array.isArray(i)){let t=i.map(n=>{let a={...e,type:n};return Cg(a,r)});return t.length===0?O.never():t.length===1?t[0]:O.union(t)}if(!i)return O.any();let o;switch(i){case"string":{let t=O.string();if(e.format){let n=e.format;n==="email"?t=t.check(O.email()):n==="uri"||n==="uri-reference"?t=t.check(O.url()):n==="uuid"||n==="guid"?t=t.check(O.uuid()):n==="date-time"?t=t.check(O.iso.datetime({offset:!0})):n==="date"?t=t.check(O.iso.date()):n==="time"?t=t.check(O.regex(k_)):n==="duration"?t=t.check(O.iso.duration()):n==="hostname"?t=t.check(O.hostname()):n==="ipv4"?t=t.check(O.ipv4()):n==="ipv6"?t=t.check(O.ipv6()):n==="mac"?t=t.check(O.mac()):n==="cidr"?t=t.check(O.cidrv4()):n==="cidr-v6"?t=t.check(O.cidrv6()):n==="base64"?t=t.check(O.base64()):n==="base64url"?t=t.check(O.base64url()):n==="e164"?t=t.check(O.e164()):n==="credit_card"?t=t.check(O.creditCard()):n==="iban"?t=t.check(O.iban()):n==="jwt"?t=t.check(O.jwt()):n==="emoji"?t=t.check(O.emoji()):n==="nanoid"?t=t.check(O.nanoid()):n==="cuid"?t=t.check(O.cuid()):n==="cuid2"?t=t.check(O.cuid2()):n==="ulid"?t=t.check(O.ulid()):n==="xid"?t=t.check(O.xid()):n==="ksuid"&&(t=t.check(O.ksuid()))}typeof e.minLength=="number"&&(t=t.min(e.minLength)),typeof e.maxLength=="number"&&(t=t.max(e.maxLength)),e.pattern&&(t=t.regex(new RegExp(e.pattern))),o=t;break}case"number":case"integer":{let t=i==="integer"?O.number().int():O.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(t=t.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(t=t.max(e.maximum)),typeof e.exclusiveMinimum=="number"?t=t.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(t=t.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?t=t.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(t=t.lt(e.maximum)),typeof e.multipleOf=="number"&&(t=t.multipleOf(e.multipleOf)),o=t;break}case"boolean":{o=O.boolean();break}case"null":{o=O.null();break}case"object":{let t={},n=e.properties||{},a=new Set(e.required||[]),s=typeof e.additionalProperties=="object"?ve(e.additionalProperties,r):void 0;for(let[m,p]of Object.entries(n)){let f=ve(p,r);ae(t,m,a.has(m)?f:f.optional())}if(e.patternProperties){let m=e.patternProperties,p=Object.keys(m),f=[];for(let _ of p){let k=ve(m[_],r),P=O.string().regex(new RegExp(_));f.push(O.looseRecord(P,k))}let h=[];if(Object.keys(t).length>0&&h.push(O.object(t).passthrough()),h.push(...f),h.length===0)o=O.object({}).passthrough();else if(h.length===1)o=h[0];else{let _=O.intersection(h[0],h[1]);for(let k=2;k<h.length;k++)_=O.intersection(_,h[k]);o=_}if(e.additionalProperties===!1){let _=Object.keys(t),k=p.map(T=>new RegExp(T)),P=o;o=o.check(T=>{if(!ze(T.value))return;let U=[];for(let I of Object.keys(T.value))_.includes(I)||k.some(A=>A.test(I))||U.push(I);U.length&&T.issues.push({code:"unrecognized_keys",keys:U,input:T.value,inst:P})})}}else{let m=O.object(t);e.additionalProperties===!1?o=m.strict():s?o=m.catchall(s):o=m.passthrough()}let u=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties=="number"?e.minProperties:void 0,d=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(u||c!==void 0||d!==void 0){let m;if(u){let p=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;m=ve(p,r)}o=y_(o,{keySchema:m,minProperties:c,maxProperties:d})}break}case"array":{let t=e.prefixItems,n=e.items;if(t&&Array.isArray(t)){let a=typeof e.minItems=="number"?e.minItems:0,s=t.map(m=>ve(m,r)),u=Ng(s,a),c=Array.isArray(n)?void 0:Eg(n,r),d=O.tuple(u);o=c?d.rest(c):d,typeof e.minItems=="number"&&(o=o.check(O.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(O.maxLength(e.maxItems)))}else if(Array.isArray(n)){let a=typeof e.minItems=="number"?e.minItems:0,s=n.map(m=>ve(m,r)),u=Ng(s,a),c=Eg(e.additionalItems,r),d=O.tuple(u);o=c?d.rest(c):d,typeof e.minItems=="number"&&(o=o.check(O.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(O.maxLength(e.maxItems)))}else if(n!==void 0){let a=ve(n,r),s=O.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),o=s}else o=O.array(O.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=x_(o,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?ve(e.contains,r):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${i}`)}return o}function ve(e,r){if(typeof e=="boolean")return e?O.any():O.never();let i=Cg(e,r),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let s=e.anyOf.map(c=>ve(c,r)),u=O.union(s);i=o?O.intersection(i,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map(c=>ve(c,r)),u=O.xor(s);i=o?O.intersection(i,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)i=o?i:O.any();else{let s=o?i:ve(e.allOf[0],r),u=o?0:1;for(let c=u;c<e.allOf.length;c++)s=O.intersection(s,ve(e.allOf[c],r));i=s}e.nullable===!0&&r.version==="openapi-3.0"&&(i=O.nullable(i)),e.readOnly===!0&&(i=O.readonly(i)),e.default!==void 0&&(i=i.default(e.default));let t={},n=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of n)s in e&&(t[s]=e[s]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let s of a)s in e&&(t[s]=e[s]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!yn(e.propertyNames)&&(t.propertyNames=e.propertyNames);for(let s of["minProperties","maxProperties"])e[s]!==void 0&&(t[s]=e[s])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!yn(e.contains)&&(t.contains=e.contains);for(let s of["uniqueItems","minContains","maxContains"])e[s]!==void 0&&(t[s]=e[s])}for(let s of Object.keys(e))h_.has(s)||ae(t,s,e[s]);return Object.keys(t).length>0&&r.registry.add(i,t),e.description&&(i=i.describe(e.description)),i}function Zg(e,r){if(typeof e=="boolean")return e?O.any():O.never();let i;try{i=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=v_(i,r?.defaultTarget),t=i.$defs||i.definitions||{},n={version:o,defs:t,refs:new Map,processing:new Set,rootSchema:i,registry:r?.registry??se};return ve(i,n)}var Rg=Symbol("z.visit/resolving");function _n(e,r){let i=typeof r=="function"?r:(a,s)=>{let u=r[a._zod.def.type];return u?u(a,s):a},o=new Map;function t(a){let s=o.get(a);if(s===Rg)return new Kr({type:"lazy",getter:()=>o.get(a)});if(s!==void 0)return s;o.set(a,Rg);let u=n(a),c=i(u,u!==a);return o.set(a,c),c}function n(a){let s=a._zod.def,u=s.type;switch(u){case"object":{let c=s.shape,d=Object.keys(c),m=!1,p={};for(let h of d){let _=t(c[h]);_!==c[h]&&(m=!0),p[h]=_}let f=s.catchall;return s.catchall&&(f=t(s.catchall),f!==s.catchall&&(m=!0)),m?V(a,{...s,shape:p,catchall:f}):a}case"array":{let c=t(s.element);return c===s.element?a:V(a,{...s,element:c})}case"tuple":{let c=s.items,d=!1,m=[];for(let f of c){let h=t(f);h!==f&&(d=!0),m.push(h)}let p=s.rest;return s.rest&&(p=t(s.rest),p!==s.rest&&(d=!0)),d?V(a,{...s,items:m,rest:p}):a}case"record":case"map":{let c=t(s.keyType),d=t(s.valueType);return c===s.keyType&&d===s.valueType?a:V(a,{...s,keyType:c,valueType:d})}case"set":{let c=t(s.valueType);return c===s.valueType?a:V(a,{...s,valueType:c})}case"union":{let c=s.options,d=!1,m=[];for(let p of c){let f=t(p);f!==p&&(d=!0),m.push(f)}return d?V(a,{...s,options:m}):a}case"intersection":{let c=t(s.left),d=t(s.right);return c===s.left&&d===s.right?a:V(a,{...s,left:c,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let c=t(s.innerType);return c===s.innerType?a:V(a,{...s,innerType:c})}case"pipe":{let c=t(s.in),d=t(s.out);return c===s.in&&d===s.out?a:V(a,{...s,in:c,out:d})}case"function":{let c=t(s.input),d=t(s.output);return c===s.input&&d===s.output?a:V(a,{...s,input:c,output:d})}case"lazy":{let c=s.getter,{_cachedInner:d,...m}=s;return V(a,{...m,getter:()=>t(c())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return a;default:return a}}return t(e)}function Lg(e){return _n(e,{object:r=>r.partial(),union:r=>{let i=r._zod.def;return i.discriminator===void 0?r:hr(i.options)}})}function I_(e,r){if(!r?.length)return e;let i=e._zod.def;return V(e,Ne(i,{checks:[...i.checks??[],...r]}),{parent:!0})}function Mg(e){return I_(e.out,e.checks)}function S_(e){return e.in._zod.traits.has("$ZodTransform")?Mg(e):e.in}function Vg(e){return _n(e,{pipe:r=>S_(r._zod.def),default:(r,i)=>i?At(r._zod.def.innerType):r,catch:(r,i)=>i?r._zod.def.innerType:r})}function Fg(e){return _n(e,{pipe:r=>Mg(r._zod.def),prefault:(r,i)=>i?r._zod.def.innerType:r})}var wd={};Je(wd,{bigint:()=>P_,boolean:()=>T_,date:()=>O_,number:()=>A_,string:()=>z_});function z_(e){return Gu(mr,e)}function A_(e){return Xu(fr,e)}function T_(e){return nc(pr,e)}function P_(e){return oc(gr,e)}function O_(e){return hc(dn,e)}var be=l.strictObject({tabId:l.number().int().nonnegative().optional()}),xd=l.strictObject({stable:l.boolean(),stabilityWaitMs:l.number().finite().nonnegative(),lastMutationAgoMs:l.number().finite().nonnegative(),fontsReady:l.boolean(),pendingImages:l.number().int().nonnegative().max(1e6),timeoutReached:l.boolean()}),Gg=be.extend({maxEntries:l.number().int().min(1).max(100).default(50),reset:l.boolean().default(!0)}),D_=be.extend({selector:l.string().min(1).max(2048),durationMs:l.number().int().min(500).max(3e4).default(3e3)}),mS=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url(),highlighted:l.boolean()}),xn=l.strictObject({level:l.enum(["warn","error"]),message:l.string().max(512),timestamp:l.number().finite().nonnegative()}),kd=l.strictObject({url:l.url().max(1024),method:l.string().max(16),resourceType:l.string().max(32),status:l.number().int().min(100).max(599).optional(),error:l.string().max(128).optional(),timestamp:l.number().finite().nonnegative()}),fS=l.strictObject({tabId:l.number().int().nonnegative(),entries:l.array(xn).max(100),dropped:l.number().int().nonnegative(),forwardingDropped:l.number().int().nonnegative()}),pS=l.strictObject({tabId:l.number().int().nonnegative(),entries:l.array(kd).max(100),dropped:l.number().int().nonnegative()}),Id=l.strictObject({url:l.url(),title:l.string().max(160),readyState:l.enum(["loading","interactive","complete"]),viewport:l.strictObject({width:l.number().int().positive(),height:l.number().int().positive(),devicePixelRatio:l.number().finite().positive()}),scroll:l.strictObject({x:l.number().finite(),y:l.number().finite()}),stabilityPending:l.boolean(),consoleInstrumentationActive:l.boolean(),consoleForwardingDropped:l.number().int().nonnegative()}),gS=Id.extend({tabId:l.number().int().nonnegative(),targetState:l.enum(["authorized","reauthorization_required","none"]),runtimeErrorCount:l.number().int().nonnegative(),consoleEntryCount:l.number().int().nonnegative(),networkFailureCount:l.number().int().nonnegative()}),kn=l.enum(["click","type","press_key","hover","scroll","select","focus"]),wn=be.extend({selector:l.string().min(1).max(2048)}),j_=wn.extend({text:l.string().max(4096),clear:l.boolean().default(!0)}),N_=be.extend({selector:l.string().min(1).max(2048).optional(),key:l.string().max(12).refine(e=>e.length===1||["Enter","Escape","Tab","Backspace","Delete","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"].includes(e)),shift:l.boolean().default(!1)}),U_=be.extend({selector:l.string().min(1).max(2048).optional(),x:l.number().finite().min(-1e6).max(1e6).default(0),y:l.number().finite().min(-1e6).max(1e6).default(0),mode:l.enum(["by","to"]).default("by")}),E_=wn.extend({value:l.string().max(4096)}),hS=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url(),action:kn,inputSource:l.literal("dom"),completed:l.literal(!0),scroll:l.strictObject({x:l.number().finite(),y:l.number().finite()}).optional()}),Ve=be.extend({url:l.url().optional(),format:l.enum(["png","jpeg"]).default("jpeg"),quality:l.number().int().min(0).max(100).default(85),waitForStable:l.boolean().default(!1),includeOverlay:l.boolean().optional(),stableWindowMs:l.number().int().min(20).max(1e3).default(100),maxWaitMs:l.number().int().min(50).max(5e3).default(2e3)}),C_=be.extend({bypassCache:l.boolean().default(!1)}),Z_=Ve.extend({x:l.number().finite().nonnegative(),y:l.number().finite().nonnegative(),width:l.number().finite().positive().max(32768),height:l.number().finite().positive().max(32768)}),R_=Ve.extend({selector:l.string().min(1).max(2048),padding:l.number().finite().min(0).max(1e3).default(0)}),L_=Ve.extend({maxPixels:l.number().int().min(1).max(32e6).default(16e6),maxSegments:l.number().int().min(1).max(64).default(32),timeoutMs:l.number().int().min(500).max(8e3).default(7e3)}),M_=be.extend({url:l.url()}),vS=l.strictObject({baseline:l.uuid().optional().describe("A prior PNG imageReference from this session. Omit and use referenceImagePath instead to diff against an external design reference."),referenceImagePath:l.string().min(1).max(4096).optional().describe("Path (relative to the MCP server's working directory, or absolute) to a local PNG design reference to diff the live capture against. Exactly one of baseline/referenceImagePath is required."),current:l.uuid().optional(),tabId:l.number().int().nonnegative().optional().describe("Only used with referenceImagePath when current is omitted, to select which tab to capture. Ignored otherwise (baseline's own tab is used)."),threshold:l.number().finite().min(0).max(1).default(.1),checkpoint:l.string().min(1).max(200).regex(/^[A-Za-z0-9_-]+$/).optional().describe("Visual Convergence best-so-far tracking id (e.g. 'hero-desktop'). Only meaningful together with referenceImagePath: persists the best-known result locally and objectively reports isBest/regressed on every call, independent of the agent's own assessment.")}),Bg=l.enum(["mobile-small","mobile","tablet","desktop","desktop-wide"]),V_=be.extend({profile:Bg.optional(),width:l.number().int().min(200).max(8192).optional(),height:l.number().int().min(200).max(8192).optional(),dedicatedPreview:l.boolean().default(!0),close:l.boolean().optional().describe("Close the current dedicated preview window instead of creating or resizing one. Width/height/profile are ignored when true. Idempotent: has no effect if no preview is open.")}),bS=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url(),windowId:l.number().int().nonnegative(),width:l.number().int().positive(),height:l.number().int().positive(),devicePixelRatio:l.number().finite().positive(),zoom:l.number().finite().positive(),outerWidth:l.number().int().positive(),outerHeight:l.number().int().positive(),dedicatedPreview:l.boolean(),sourceTabId:l.number().int().nonnegative().optional(),requested:l.strictObject({width:l.number().int().positive(),height:l.number().int().positive(),profile:Bg.optional()}).optional(),exact:l.boolean().optional(),attempts:l.number().int().min(0).max(3).optional(),requiresTargetSelection:l.boolean().optional(),sourceWindowUnchanged:l.boolean().optional(),previewClosed:l.boolean().optional().describe("Present when close:true was requested. True if a dedicated preview window was actually open and closed; false if there was none to close.")}),Jg=be.extend({selector:l.string().min(1).max(2048).optional(),depth:l.number().int().min(0).max(8).default(3),maxNodes:l.number().int().min(1).max(300).default(100),textLength:l.number().int().min(0).max(300).default(160),maxBytes:l.number().int().min(2048).max(65536).default(32768)}),F_=Jg.extend({selector:l.string().min(1).max(2048)}),G_=be.extend({maxRegions:l.number().int().min(1).max(100).default(50),reset:l.boolean().default(!0)}),B_=l.enum(["highlight","clear_highlight","capture_region","capture_element","capture_full_page","get_dom","get_element","get_changed_regions","get_viewport","set_viewport",...kn.options,"get_console","get_network_failures","get_page_status"]),Wg=l.strictObject({x:l.number().finite(),y:l.number().finite(),width:l.number().finite().nonnegative(),height:l.number().finite().nonnegative()}),J_=l.strictObject({index:l.number().int().nonnegative(),parent:l.number().int().nonnegative().optional(),depth:l.number().int().min(0).max(8),tag:l.string().max(80),id:l.string().max(160).optional(),classes:l.array(l.string().max(80)).max(6).optional(),role:l.string().max(80).optional(),text:l.string().max(300).optional(),ariaLabel:l.string().max(300).optional(),name:l.string().max(160).optional(),type:l.string().max(80).optional(),href:l.string().max(1024).optional(),bounds:Wg,visible:l.boolean(),redacted:l.boolean().optional(),disabled:l.boolean().optional(),checked:l.boolean().optional(),selected:l.boolean().optional()}),$S=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url(),nodes:l.array(J_).max(300),truncated:l.boolean(),payloadBytes:l.number().int().max(65536)}),yS=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url(),regions:l.array(Wg.extend({reason:l.enum(["mutation","resize","attribute","text"]),selector:l.string().max(240).optional()})).max(100),trackingStarted:l.boolean(),dropped:l.number().int().nonnegative(),coverage:l.literal("potential-dom-and-layout-changes")}),Sd=l.strictObject({type:l.enum(["error","unhandledrejection","console-error"]),message:l.string().max(4096),source:l.string().max(2048).optional(),line:l.number().int().nonnegative().optional(),column:l.number().int().nonnegative().optional(),timestamp:l.number().nonnegative()}),Kg=l.strictObject({extensionVersion:l.string().max(80).optional(),extensionId:l.string().min(1).max(256).optional(),capabilities:l.array(B_).max(20).optional(),selectedTab:l.number().int().nonnegative().nullable(),url:l.string().max(2048).nullable(),targetState:l.enum(["none","authorized","reauthorization_required"]).optional(),browser:l.strictObject({name:l.enum(["firefox","chrome"]),version:l.string().max(80)}).optional(),backgroundCapture:l.strictObject({enabled:l.boolean(),permissionGranted:l.boolean()}).optional()}),Hg=l.discriminatedUnion("type",[l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("highlight"),payload:D_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("clear_highlight"),payload:be}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_console"),payload:Gg}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_network_failures"),payload:Gg}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_page_status"),payload:be}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("click"),payload:wn}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("type"),payload:j_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("press_key"),payload:N_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("hover"),payload:wn}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("scroll"),payload:U_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("select"),payload:E_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("focus"),payload:wn}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_viewport"),payload:be}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("set_viewport"),payload:V_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_dom"),payload:Jg}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_element"),payload:F_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_changed_regions"),payload:G_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("capture_region"),payload:Z_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("capture_element"),payload:R_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("capture_full_page"),payload:L_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("capture"),payload:Ve}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("reload"),payload:C_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("navigate"),payload:M_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_errors"),payload:be})]),_S=l.discriminatedUnion("ok",[l.strictObject({id:l.uuid(),version:l.literal(1),ok:l.literal(!0),result:l.unknown()}),l.strictObject({id:l.uuid(),version:l.literal(1),ok:l.literal(!1),error:l.strictObject({code:l.string().max(80),message:l.string().max(4096),stability:xd.optional()})})]),wS=l.strictObject({version:l.literal(1),type:l.literal("hello"),token:l.string().regex(/^[a-f0-9]{64}$/),state:Kg}),xS=l.strictObject({version:l.literal(1),type:l.literal("state"),state:Kg}),Xg=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url(),width:l.number().int().positive(),height:l.number().int().positive(),format:l.enum(["png","jpeg"]),captureMs:l.number().nonnegative(),processingMs:l.number().nonnegative().optional(),totalMs:l.number().nonnegative().optional(),segments:l.number().int().positive().max(64).optional(),scrollRestored:l.boolean().optional(),stabilityWaitMs:l.number().nonnegative().optional(),extensionTotalMs:l.number().nonnegative().optional(),renderAppearsStable:l.boolean().optional(),stable:l.boolean().optional(),lastMutationAgoMs:l.number().finite().nonnegative().optional(),fontsReady:l.boolean().optional(),pendingImages:l.number().int().nonnegative().optional(),timeoutReached:l.boolean().optional(),dataUrl:l.string().max(16*1024*1024)}),kS=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url()}),IS=l.strictObject({tabId:l.number().int().nonnegative(),errors:l.array(Sd).max(200)}),x=class extends Error{constructor(i,o,t){super(o);this.code=i;this.stability=t}};function Fe(e,r=[]){let i=new URL(e);if(!["http:","https:"].includes(i.protocol)||i.username||i.password||!["localhost","127.0.0.1","[::1]"].includes(i.hostname)&&!r.includes(i.origin))throw new x("GS_URL_NOT_ALLOWED","Use a localhost URL or explicitly authorize this origin in both server and extension settings.")}var W_="background-capture-offscreen.html",K_=6e3;function eh(e,r){if(e!==r)throw new x("GS_PREVIEW_BACKGROUND_INELIGIBLE","This responsive preview is not eligible for Background Capture while inactive (a Chrome platform limitation, not a GazeSight restriction). Activate the preview window to capture it, or capture the authorized primary target instead.")}async function H_(){return(await chrome.runtime.getContexts({contextTypes:[chrome.runtime.ContextType.OFFSCREEN_DOCUMENT]})).length>0}async function qg(){await H_()&&await chrome.offscreen.closeDocument().catch(()=>{})}var Yg=Promise.resolve();function zd(e,r,i){return new Promise((o,t)=>{let n=setTimeout(()=>t(new x("GS_TIMEOUT",i)),r);e.then(a=>{clearTimeout(n),o(a)},a=>{clearTimeout(n),t(a)})})}async function Qg(e,r,i){let o;try{o=await chrome.tabCapture.getMediaStreamId({targetTabId:e})}catch(t){throw new x("GS_CAPTURE_FAILED",`Background capture stream unavailable: ${String(t?.message??t)}`)}await qg(),await chrome.offscreen.createDocument({url:chrome.runtime.getURL(W_),reasons:[chrome.offscreen.Reason.USER_MEDIA],justification:"Decode a tabCapture MediaStream frame into a still image for GazeSight's Background Capture."});try{let t=await zd(chrome.runtime.sendMessage({type:"gazesight-background-capture-offscreen",streamId:o,format:r,quality:i}),K_,"Background capture timed out waiting for the offscreen document.");if(!t?.ok||typeof t.dataUrl!="string")throw new x("GS_CAPTURE_FAILED",typeof t?.error=="string"?t.error:"Background capture failed.");return t.dataUrl}finally{await qg()}}function th(e,r,i){let o=Yg.then(()=>Qg(e,r,i),()=>Qg(e,r,i));return Yg=o.catch(()=>{}),o}function Ad(e){let r=typeof e=="object"&&e!==null&&"message"in e?e.message:e;return String(r).slice(0,512)}function rh(e,r){return e instanceof x?e:new x(r==="capture"?"GS_CAPTURE_FAILED":"GS_OPERATION_FAILED",`Firefox ${r}: ${Ad(e)}`)}var Vo=class{constructor(r,i,o,t,n,a){this.port=r;this.token=i;this.state=o;this.handler=t;this.status=n;this.keepaliveMs=a}socket;timer;keepalive;delay=250;stopped=!1;paired=!1;start(){this.stopped=!1,this.connect()}stop(){this.stopped=!0,clearTimeout(this.timer),clearInterval(this.keepalive),this.socket?.close(),this.status(!1)}async publish(){this.paired&&this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify({version:1,type:"state",state:await this.state()}))}async connect(){if(this.stopped)return;let r=new WebSocket(`ws://127.0.0.1:${this.port}`);this.socket=r,this.paired=!1;let i=setTimeout(()=>r.close(),4e3);r.onopen=()=>{this.state().then(t=>{r.readyState===WebSocket.OPEN&&r.send(JSON.stringify({version:1,type:"hello",token:this.token,state:t}))})};let o=Promise.resolve();r.onmessage=t=>{o=o.then(async()=>{try{if(typeof t.data!="string"||t.data.length>32768)throw new Error("Invalid message");let n=JSON.parse(t.data);if(!this.paired){if(JSON.stringify(n)!==JSON.stringify({version:1,type:"paired"}))throw new Error("Pairing failed");this.paired=!0,clearTimeout(i),this.delay=250,this.status(!0),this.keepaliveMs&&(this.keepalive=setInterval(()=>{this.publish().catch(()=>{})},this.keepaliveMs));return}let a=Hg.parse(n),s;try{s={id:a.id,version:1,ok:!0,result:await this.handler(a)}}catch(u){let c=rh(u,a.type);s={id:a.id,version:1,ok:!1,error:{code:c.code,message:c.message,...c.stability?{stability:c.stability}:{}}}}r.readyState===WebSocket.OPEN&&r.send(JSON.stringify(s))}catch{r.close(1008,"Invalid message")}})},r.onerror=()=>r.close(),r.onclose=()=>{clearTimeout(i),clearInterval(this.keepalive),this.paired=!1,this.stopped||this.status(!1),this.stopped||(this.timer=setTimeout(()=>void this.connect(),this.delay),this.delay=Math.min(this.delay*2,5e3))}}};var Fo=class{selectedTab=null;selectedOrigin=null;state="none";generation=0;choose(r,i){this.selectedTab=r,this.selectedOrigin=i?new URL(i).origin:null,this.state="authorized",this.generation++}reauthorize(r){r===this.selectedTab&&(this.state="reauthorization_required",this.generation++)}refresh(r){r===this.selectedTab&&this.generation++}resume(r){r===this.selectedTab&&this.state==="reauthorization_required"&&(this.state="authorized")}assertAuthorized(r){if(r!==this.selectedTab)throw new x("GS_TARGET_MISMATCH","The requested tab is not the target explicitly selected in GazeSight.");if(this.state!=="authorized")throw new x("GS_REAUTHORIZE_TARGET","Click the GazeSight extension icon or use the configured selection shortcut (default Ctrl+Shift+Y) in the target tab to grant Firefox permission for this document.")}assertAuthorizedUrl(r,i){if(this.assertAuthorized(r),this.selectedOrigin!==null&&new URL(i).origin!==this.selectedOrigin)throw new x("GS_REAUTHORIZE_TARGET","The target moved to a different origin. Select it again before GazeSight accesses it.")}isSelectedOrigin(r){try{return this.selectedOrigin!==null&&new URL(r).origin===this.selectedOrigin}catch{return!1}}remove(r){this.selectedTab===r&&(this.selectedTab=null,this.selectedOrigin=null,this.state="none",this.generation++)}resolve(r){let i=r??this.selectedTab;if(i===null)throw new x("GS_NO_TARGET_TAB","Open your preview page in Firefox and click the GazeSight icon.");return i}};async function nh(e){try{return await e()}catch(r){throw X_(r)}}function X_(e){let r=Ad(e),i=/activeTab|<all_urls>|permission/i.test(r);return new x(i?"GS_PERMISSION_DENIED":"GS_CAPTURE_FAILED",`Firefox captureVisibleTab: ${r}${i?" Click the GazeSight icon or use the configured selection shortcut (default Ctrl+Shift+Y) in the selected tab to grant activeTab again.":""}`)}var In=class{constructor(r,i,o){this.nativeCapture=r;this.contentOperation=i;this.services=o}capture(r){return this.nativeCapture(r)}executeContentOperation(r){return this.contentOperation(r)}getTarget(r){return browser.tabs.get(r)}async reload(r,i){await browser.tabs.reload(r,{bypassCache:i})}async navigate(r,i){await browser.tabs.update(r,{url:i})}getViewport(r){return this.services.getViewport(r)}resizePreview(...r){return this.services.resizePreview(...r)}getDiagnostics(r){return this.services.getDiagnostics(r)}};var ih=l.discriminatedUnion("op",[l.strictObject({op:l.literal("metrics")}),l.strictObject({op:l.literal("begin")}),l.strictObject({op:l.literal("restore"),lease:l.uuid()}),l.strictObject({op:l.literal("scroll"),lease:l.uuid(),x:l.number().finite().nonnegative(),y:l.number().finite().nonnegative()}),l.strictObject({op:l.literal("element"),lease:l.uuid(),selector:l.string().min(1).max(2048),padding:l.number().min(0).max(1e3)})]);async function Td(e,r,i,o,t,n,a=()=>performance.now()){e.assertAuthorized(r);let s=a()+5e3;e.reauthorize(r);let u=e.generation,c=()=>{if(a()>=s)throw new x("GS_TIMEOUT","Navigation preparation exceeded its bounded deadline; no navigation was issued.");if(e.selectedTab!==r||e.generation!==u||e.state!=="reauthorization_required")throw new x("GS_TARGET_CHANGED","The target changed before navigation; no navigation was issued.")};await o(),c();let d=await t();if(c(),d!==i)throw new x("GS_TARGET_CHANGED","The document changed before navigation; no navigation was issued.");await n()}function Pd(e,r,i){if(![e.x,e.y,e.width,e.height,r.width,r.height,i.width,i.height].every(Number.isFinite)||r.width<=0||r.height<=0||e.width<=0||e.height<=0||e.x<0||e.y<0||e.x+e.width>r.width+.5||e.y+e.height>r.height+.5)throw new x("GS_REGION_OUT_OF_VIEWPORT","The complete region must fit inside the current CSS viewport.");let o=i.width/r.width,t=i.height/r.height,n=Math.floor(e.x*o),a=Math.floor(e.y*t);return{x:n,y:a,width:Math.min(i.width,Math.ceil((e.x+e.width)*o))-n,height:Math.min(i.height,Math.ceil((e.y+e.height)*t))-a}}function oh(e,r,i,o,t,n=0){if(![e,r,i,o].every(s=>Number.isFinite(s)&&s>0)||e>32768||r>32768)throw new x("GS_CAPTURE_LIMIT","Page dimensions exceed the capture limits.");if(i=e>i?Math.max(1,i-n*2):i,o=r>o?Math.max(1,o-n*2):o,Math.ceil(e/i)*Math.ceil(r/o)>t)throw new x("GS_CAPTURE_LIMIT","Page requires too many capture segments.");let a=[];for(let s=0;s<r;s+=o)for(let u=0;u<e;u+=i)a.push({x:u,y:s,width:Math.min(i,e-u),height:Math.min(o,r-s)});return a}var br=l.object({width:l.number().finite().positive(),height:l.number().finite().positive(),pageWidth:l.number().finite().positive(),pageHeight:l.number().finite().positive(),x:l.number().finite(),y:l.number().finite(),devicePixelRatio:l.number().finite().positive()}),ah=br.extend({lease:l.uuid()}),sh=br.extend({rect:l.object({x:l.number(),y:l.number(),width:l.number().positive(),height:l.number().positive()})});async function uh(e,r,i){let o=performance.now(),t=r.payload,n=o+(r.type==="capture_full_page"?r.payload.timeoutMs:7e3);async function a(I){let A=n-performance.now();if(A<=0)throw new x("GS_TIMEOUT","Capture suite deadline reached.");let S;try{return await Promise.race([I(),new Promise((j,M)=>{S=setTimeout(()=>M(new x("GS_TIMEOUT","Capture suite deadline reached.")),A)})])}finally{clearTimeout(S)}}let s=I=>a(()=>e.executeContentOperation(I)),u=Ve.parse({tabId:t.tabId,url:t.url,format:t.format,quality:t.quality,waitForStable:t.waitForStable,stableWindowMs:t.stableWindowMs,maxWaitMs:t.maxWaitMs,includeOverlay:t.includeOverlay}),c=0,d=0,m=0,p=0,f,h=!0,_,k,P;async function T(){let I=Xg.parse(await a(()=>e.capture(u)));if(c+=I.captureMs,p+=I.stabilityWaitMs??0,m++,_??=I,!new RegExp(`^data:image/${I.format};base64,[A-Za-z0-9+/]+={0,2}$`).test(I.dataUrl))throw new x("GS_CAPTURE_FAILED","Native capture returned an invalid image data URL.");let A=performance.now(),S=await a(async()=>{let j=await createImageBitmap(await(await fetch(I.dataUrl)).blob());if(performance.now()>n)throw j.close(),new x("GS_TIMEOUT","Image decoding exceeded the capture deadline.");return j});return d+=performance.now()-A,S}function U(I,A,S=16e6){if(!Number.isFinite(I*A)||I<1||A<1||I>32768||A>32768||I*A>S)throw new x("GS_CAPTURE_LIMIT","Output image exceeds the pixel/memory limit.");return k=i.createSurface(I,A),k}try{if(r.type==="capture_full_page"){let S=ah.parse(await s({op:"begin"}));f=S.lease;let j=oh(S.pageWidth,S.pageHeight,S.width,S.height,r.payload.maxSegments,1),M,H=0,X=0;for(let D of j){let J=br.parse(await s({op:"scroll",lease:f,x:Math.max(0,D.x-1),y:Math.max(0,D.y-1)}));if(J.pageWidth!==S.pageWidth||J.pageHeight!==S.pageHeight||J.width!==S.width||J.height!==S.height)throw new x("GS_PAGE_CHANGED","Page dimensions changed during capture; infinite or dynamic pages are not stitched.");let W=await T();try{let mt=performance.now();if(M||(H=W.width/J.width,X=W.height/J.height,M=U(Math.ceil(S.pageWidth*H),Math.ceil(S.pageHeight*X),r.payload.maxPixels)),Math.abs(W.width/J.width-H)>.001||Math.abs(W.height/J.height-X)>.001)throw new x("GS_TARGET_CHANGED","Capture scale changed during stitching.");let me=Pd({x:D.x-J.x,y:D.y-J.y,width:D.width,height:D.height},J,W),Dt=Math.floor(D.x*H),Md=Math.floor(D.y*X),Uh=Math.ceil((D.x+D.width)*H)-Dt,Eh=Math.ceil((D.y+D.height)*X)-Md;M.drawImage(W,me.x,me.y,me.width,me.height,Dt,Md,Uh,Eh),d+=performance.now()-mt}finally{W.close()}let je=br.parse(await s({op:"metrics"}));if(je.pageWidth!==S.pageWidth||je.pageHeight!==S.pageHeight||Math.abs(je.x-J.x)>.5||Math.abs(je.y-J.y)>.5)throw new x("GS_PAGE_CHANGED","Page size or scroll changed during native capture.")}}else{let S,j;if(r.type==="capture_element"){f=ah.parse(await s({op:"begin"})).lease;let D=sh.parse(await s({op:"element",lease:f,selector:r.payload.selector,padding:r.payload.padding}));S=D,j=D.rect}else S=br.parse(await s({op:"metrics"})),j=r.payload;let M=await T();try{let X=performance.now(),D=Pd(j,S,M);U(D.width,D.height).drawImage(M,D.x,D.y,D.width,D.height,0,0,D.width,D.height),d+=performance.now()-X}finally{M.close()}let H=br.parse(await s({op:"metrics"}));if(S.width!==H.width||S.height!==H.height||S.x!==H.x||S.y!==H.y)throw new x("GS_TARGET_CHANGED","Viewport or scroll changed during capture.");if(r.type==="capture_element"){let X=sh.parse(await s({op:"element",lease:f,selector:r.payload.selector,padding:r.payload.padding}));if(JSON.stringify(X.rect)!==JSON.stringify(j))throw new x("GS_PAGE_CHANGED","Element geometry changed during capture.")}}if(!k||!_)throw new x("GS_CAPTURE_FAILED","No capture segments produced.");let I=performance.now(),A=await k.encode(t.format,t.quality);if(d+=performance.now()-I,A.length>16*1024*1024)throw new x("GS_CAPTURE_LIMIT","Encoded image exceeds the bridge payload limit.");if(performance.now()>n)throw new x("GS_TIMEOUT","Local image processing exceeded the capture deadline.");return P={..._,width:k.width,height:k.height,dataUrl:A,segments:m,captureMs:c,processingMs:d,stabilityWaitMs:p,extensionTotalMs:performance.now()-o,totalMs:performance.now()-o,scrollRestored:h},P}finally{if(f){let I;try{if(h=l.object({scrollRestored:l.boolean()}).parse(await Promise.race([e.executeContentOperation({op:"restore",lease:f}),new Promise((S,j)=>{I=setTimeout(()=>j(new x("GS_SCROLL_RESTORE_FAILED","Scroll restoration timed out; content watchdog remains active.")),500)})])).scrollRestored,!h)throw new x("GS_SCROLL_RESTORE_FAILED","The original scroll position could not be restored.")}finally{clearTimeout(I)}}k&&k.dispose(),P&&Object.assign(P,{scrollRestored:h,totalMs:performance.now()-o,extensionTotalMs:performance.now()-o})}}function q_(e){return new Promise((r,i)=>{let o=new FileReader;o.onload=()=>r(o.result),o.onerror=()=>i(o.error),o.readAsDataURL(e)})}var Go=class{createSurface(r,i){let o=new OffscreenCanvas(r,i),t=o.getContext("2d");if(!t)throw new x("GS_CAPTURE_FAILED","Unable to allocate local image processing surface.");return{width:r,height:i,drawImage:(n,a,s,u,c,d,m,p,f)=>t.drawImage(n,a,s,u,c,d,m,p,f),encode:async(n,a)=>{let s=await o.convertToBlob({type:`image/${n}`,quality:a/100});return q_(s)},dispose:()=>{o.width=0,o.height=0}}}};var Y_="fullpage-stitch-offscreen.html",Q_=8e3;async function ew(){return(await chrome.runtime.getContexts({contextTypes:[chrome.runtime.ContextType.OFFSCREEN_DOCUMENT]})).length>0}async function ch(){await ew()&&await chrome.offscreen.closeDocument().catch(()=>{})}var lh=Promise.resolve();async function dh(e,r,i,o,t){await ch(),await chrome.offscreen.createDocument({url:chrome.runtime.getURL(Y_),reasons:[chrome.offscreen.Reason.BLOBS],justification:"Decode and draw already-cropped capture tiles onto a DOM canvas for GazeSight's Chrome full-page composition."});try{let n=await zd(chrome.runtime.sendMessage({type:"gazesight-fullpage-stitch-offscreen",tiles:e,width:r,height:i,format:o,quality:t}),Q_,"Offscreen full-page stitch timed out.");if(!n?.ok||typeof n.dataUrl!="string")throw new x("GS_CAPTURE_FAILED",typeof n?.error=="string"?n.error:"Offscreen full-page stitch failed.");return n.dataUrl}finally{await ch()}}function mh(e,r,i,o,t){let n=lh.then(()=>dh(e,r,i,o,t),()=>dh(e,r,i,o,t));return lh=n.catch(()=>{}),n}function tw(e){let r=new Uint8Array(e),i="",o=32768;for(let t=0;t<r.length;t+=o)i+=String.fromCharCode(...r.subarray(t,t+o));return btoa(i)}function rw(e,r,i,o,t){let n=new OffscreenCanvas(o,t),a=n.getContext("2d");if(!a)throw new x("GS_CAPTURE_FAILED","Unable to allocate local image processing surface.");return a.drawImage(e,r,i,o,t,0,0,o,t),n.convertToBlob({type:"image/png"}).then(s=>s.arrayBuffer()).then(s=>`data:image/png;base64,${tw(s)}`)}var Bo=class{createSurface(r,i){let o=[];return{width:r,height:i,drawImage:(t,n,a,s,u,c,d,m,p)=>{o.push(rw(t,n,a,s,u).then(f=>({dataUrl:f,sw:s,sh:u,dx:c,dy:d,dw:m,dh:p})))},encode:async(t,n)=>{let a=await Promise.all(o);return mh(a.map(s=>({dataUrl:s.dataUrl,sx:0,sy:0,sw:s.sw,sh:s.sh,dx:s.dx,dy:s.dy,dw:s.dw,dh:s.dh})),r,i,t,n)},dispose:()=>{}}}};var nw={"mobile-small":{width:320,height:568},mobile:{width:390,height:844},tablet:{width:768,height:1024},desktop:{width:1440,height:900},"desktop-wide":{width:1920,height:1080}},pz=l.strictObject({op:l.literal("measure")}),fh=l.strictObject({width:l.number().int().positive(),height:l.number().int().positive(),devicePixelRatio:l.number().finite().positive()});function ph(e){let r=e.profile?nw[e.profile]:void 0,i=e.width??r?.width,o=e.height??r?.height;if(!i||!o)throw new x("GS_INVALID_VIEWPORT","Provide a profile or both width and height in CSS pixels.");return{width:i,height:o,...e.profile?{profile:e.profile}:{}}}function gh(e,r,i,o){if(!i.width||!i.height||!Number.isFinite(o)||o<=0)throw new x("GS_VIEWPORT_FAILED","Window dimensions or zoom are unavailable.");return{width:Math.max(200,Math.min(8192,Math.round(i.width+(e.width-r.width)*o))),height:Math.max(200,Math.min(8192,Math.round(i.height+(e.height-r.height)*o)))}}function hh(e,r){return["width","height","left","top","state"].every(i=>e[i]===r[i])}function Jo(e,r){if(e.tabs?.length!==1||e.tabs[0].id!==r)throw new x("GS_PREVIEW_IN_USE","The preview now contains other tabs; GazeSight will not resize it.")}function iw(e){return{incognito:!!e.incognito}}var Wo=class{preview;async get(r){let i=Od(r),o=await browser.tabs.sendMessage(r.id,{type:"gazesight-viewport-content",operation:{op:"measure"}},{frameId:0});if(!o?.ok)throw new x("GS_VIEWPORT_FAILED","Viewport measurement unavailable; select the target again.");let t=fh.parse(o.value),n=await browser.windows.get(i),a=await browser.tabs.getZoom(r.id);return{tabId:r.id,url:r.url,windowId:i,...t,zoom:a,outerWidth:n.width,outerHeight:n.height,dedicatedPreview:!!(this.preview&&this.preview.tabId===r.id),...this.preview&&this.preview.tabId===r.id?{sourceTabId:this.preview.sourceTabId}:{}}}async set(r,i,o){let t=ph(i),n=Od(r),a=i.dedicatedPreview&&this.preview&&this.preview.tabId===r.id?this.preview.sourceWindowId:n,s=await browser.windows.get(a).catch(()=>{}),u=r,c=!1,d=!1;if(i.dedicatedPreview){if(this.preview){let k=await browser.windows.get(this.preview.windowId,{populate:!0}).catch(()=>{});if(!k)this.preview=void 0;else{if(Jo(k,this.preview.tabId),r.id!==this.preview.tabId&&(r.id!==this.preview.sourceTabId||r.url!==this.preview.url||!!r.incognito!==this.preview.incognito))throw new x("GS_PREVIEW_IN_USE","An existing preview belongs to another source. Close that preview before creating a different one.");if(u=await browser.tabs.get(this.preview.tabId),t.width<500&&r.id===this.preview.tabId&&k.type!=="popup"){await o();let P={...this.preview},T=await browser.windows.create({tabId:P.tabId,type:"popup",focused:!0,width:Math.min(8192,t.width+32),height:Math.min(8192,t.height+120)});if(T.id===void 0)throw new x("GS_VIEWPORT_FAILED","Chrome did not return the compact preview window.");this.preview={...P,windowId:T.id},u=await browser.tabs.get(P.tabId),c=!0}}}if(!this.preview){let k=iw(r);await o();let P=await browser.windows.create({url:r.url,type:t.width<500?"popup":"normal",focused:!0,width:Math.min(8192,t.width+32),height:Math.min(8192,t.height+120),incognito:k.incognito}),T=P.tabs?.[0];if(P.id===void 0||T?.id===void 0)throw new x("GS_VIEWPORT_FAILED","Chrome did not return a preview tab.");this.preview={windowId:P.id,tabId:T.id,sourceTabId:r.id,sourceWindowId:n,incognito:k.incognito,url:r.url},u=T,d=!0}}let m,p,f;for(let k=0;k<20;k++){await o();let P=await browser.tabs.get(u.id);if(P.status==="complete"&&P.url!==r.url)throw new x("GS_TARGET_CHANGED","The preview navigated away from its source URL.");if(u=P,u.status==="complete"){if(d){try{await ow(u.id)}catch(T){p=T}d=!1}try{m=await this.get(u);break}catch(T){f=T}}await new Promise(T=>setTimeout(T,100))}if(!m){let k=p??f;throw new x("GS_VIEWPORT_FAILED","Preview created but its measured viewport is unavailable."+(k?` ${p?"Injection":"Measurement"} error: ${String(k?.message??k)}`:""))}let h=0;for(;h<3&&(m.width!==t.width||m.height!==t.height);h++){await o();let k=Od(u),P=await browser.windows.get(k,{populate:!0});i.dedicatedPreview&&Jo(P,u.id);let T=gh(t,m,P,m.zoom);await browser.windows.update(k,{state:"normal"}),await o(),await browser.windows.update(k,T),await new Promise(I=>setTimeout(I,150)),await o();let U=await browser.tabs.get(u.id);if(U.url!==r.url)throw new x("GS_TARGET_CHANGED","The preview navigated during resize.");m=await this.get(U)}let _=await browser.windows.get(a).catch(()=>{});return{...m,movedToCompact:c,requested:t,exact:m.width===t.width&&m.height===t.height,attempts:h,...s&&_?{sourceWindowUnchanged:hh(s,_)}:{}}}removeWindow(r){this.preview?.windowId===r&&(this.preview=void 0)}previewSourceTabId(r){return this.preview&&this.preview.tabId===r?this.preview.sourceTabId:void 0}currentPreviewTabId(){return this.preview?.tabId}clear(){this.preview=void 0}snapshot(){return this.preview?{...this.preview}:void 0}async hydrate(r,i){if(i.selectedTab!==r.sourceTabId||i.state!=="authorized")return!1;try{let o=await browser.windows.get(r.windowId,{populate:!0});return Jo(o,r.tabId),(await browser.tabs.get(r.tabId)).url!==r.url?!1:(this.preview={...r},!0)}catch{return!1}}};async function ow(e){await browser.scripting.executeScript({target:{tabId:e},files:["content.js"]})}function Od(e){if(e.id===void 0||e.windowId===void 0||!e.url)throw new x("GS_VIEWPORT_FAILED","Chrome tab identity or window is unavailable.");return e.windowId}var aw="gazesight-select-target";async function vh(e,r){if(e!==aw)return;let i=r??(await browser.tabs.query({active:!0,lastFocusedWindow:!0}))[0];if(!(i?.id===void 0||i.active!==!0))return i}function Ge(e,r){return e.slice(0,4096).replace(/https?:\/\/[^\s"'<>]+/gi,i=>{try{let o=new URL(i);return o.origin+o.pathname}catch{return"[redacted URL]"}}).replace(/(?:bearer\s+)[\w.+/=-]+/gi,"[redacted]").replace(/\beyJ[\w-]+\.[\w-]+(?:\.[\w-]+)?/g,"[redacted]").replace(/\b[a-zA-Z0-9_+/-]{24,}={0,2}\b/g,"[redacted]").replace(/((?:password|passwd|token|secret|credential|api[-_]?key|authorization)["']?\s*[:=]\s*["']?)[^\s,;"']+/gi,"$1[redacted]").replace(/\s+/g," ").trim().slice(0,r)}function Sn(e,r){try{let i=new URL(e,r);return["http:","https:"].includes(i.protocol)?(i.origin+i.pathname.split("/").map(o=>Ge(o,200)).join("/")).slice(0,1024):void 0}catch{return}}var Iz=l.strictObject({op:l.enum(["status","stop"])}),Sz=l.discriminatedUnion("type",[l.strictObject({namespace:l.literal("gazesight-console"),type:l.literal("entry"),entry:xn}),l.strictObject({namespace:l.literal("gazesight-console"),type:l.enum(["ready","stopped"])})]),zn=class{entries=[];dropped=0;get count(){return this.entries.length}push(r){this.entries.length===100&&(this.entries.shift(),this.dropped++),this.entries.push(r)}clear(){this.entries=[],this.dropped=0}read(r,i){let o=Math.max(1,Math.min(100,Math.floor(r))),t={entries:this.entries.slice(-o),dropped:this.dropped+Math.max(0,this.entries.length-o)};return i&&this.clear(),t}};function bh(e){if(!e.error&&!(e.statusCode!==void 0&&e.statusCode>=400&&e.statusCode<=599))return;let r=Sn(e.url,e.url);if(r)return kd.parse({url:r,method:Ge(e.method,16),resourceType:Ge(e.type,32),timestamp:e.timeStamp,...e.statusCode!==void 0?{status:e.statusCode}:{},...e.error?{error:/^NS_ERROR_[A-Z_]{1,96}$/.test(e.error)?e.error:Ge(e.error,128)}:{}})}var $h=l.strictObject({type:l.literal("gazesight-ui"),action:l.enum(["status","select","disconnect","fast","stable","diagnostics","background-enable","background-denied","background-disable","continuous-enable","continuous-denied","continuous-disable"])});function yh(e,r,i,o){return e?r==="none"?"WAIT":r==="reauthorization_required"?"AUTH":i?"WAIT":o?"ERR":"ON":"OFF"}function Dd(e,r,i,o=!1){if(e.id!==r||!o&&e.tab||!e.url)return!1;try{let t=new URL(e.url),n=new URL(i);return t.origin===n.origin&&t.pathname===n.pathname}catch{return!1}}var _h="0.5.2";async function wh(e){if(e.tabId!==e.targetTabId)throw new x("GS_TARGET_MISMATCH","The requested tab is not the target explicitly selected in GazeSight.");let r=e.backgroundMode==="enabled"&&e.permissionGranted,i=await e.currentTarget();if(i.id!==e.tabId||i.url!==e.url||e.currentGeneration()!==e.generation)throw new x("GS_TARGET_CHANGED","The target changed before capture.");if(!r&&!i.active)throw new x("GS_CAPTURE_FAILED","Bring the authorized target tab to the front.");let o=await(r?e.background():e.foreground()),t=await e.currentTarget();if(t.id!==e.tabId||t.url!==e.url||e.currentGeneration()!==e.generation)throw new x("GS_TARGET_CHANGED","The target changed during capture.");if(!r&&!t.active)throw new x("GS_CAPTURE_FAILED","The active tab changed during capture.");return o}function An(e){return String(e).padStart(2,"0")}function sw(e=new Date){return`GazeSight/gazesight-${e.getFullYear()}-${An(e.getMonth()+1)}-${An(e.getDate())}_${An(e.getHours())}-${An(e.getMinutes())}-${An(e.getSeconds())}.png`}var Ko=class{busy=!1;async run(r){if(this.busy)throw new x("GS_CAPTURE_BUSY","A manual screenshot is already in progress.");this.busy=!0;try{if(!await r.permissionGranted())throw new x("GS_PERMISSION_DENIED","Download permission required.");let i=await r.capture();if(i.format!=="png"||!/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(i.dataUrl))throw new x("GS_CAPTURE_FAILED","Capture failed to produce a PNG image.");let o=sw(r.now),t;try{if(t=await r.download({url:i.dataUrl,filename:o,saveAs:!1,conflictAction:"uniquify"}),!await r.waitForCompletion(t))throw new Error("interrupted")}catch{throw new x("GS_DOWNLOAD_FAILED","Download failed.")}return{filename:o,downloadId:t}}finally{this.busy=!1}}};function jd(e,r,i,o){if(!i.enabled||!i.hostPermissionGranted)return!1;let t=o(e);return t!==void 0&&t===r.selectedTab&&r.state==="authorized"}function xh(e,r,i,o,t){return jd(e,i,o,t)&&i.isSelectedOrigin(r)}function Nd(e,r){if(r===null)return!1;try{return new URL(e).origin===r}catch{return!1}}var b=new Fo,dt=new Wo,uw=new Go,cw=new Bo,Oe=new Map,yr=new zn,_r=new zn,Q,Be=[],De=!1,$r=null,Pn=!1,Ed=!1,On=!1,$e="disabled",le=!1,oe=!1,ue=!1,lw=new Ko;function Sh(e){return jd(e,b,{enabled:ue,hostPermissionGranted:le},r=>dt.previewSourceTabId(r))}function dw(e,r){return xh(e,r,b,{enabled:ue,hostPermissionGranted:le},i=>dt.previewSourceTabId(i))}function ne(e){Sh(e)||b.assertAuthorized(e)}function zh(e,r){dw(e,r)||b.assertAuthorizedUrl(e,r)}function mw(e){return e===b.selectedTab?b.state==="authorized":Sh(e)}async function Pe(){await browser.storage.session.set({sessionTargetTabId:b.selectedTab,sessionTargetOrigin:b.selectedOrigin,sessionTargetState:b.state,sessionPreview:dt.snapshot()??null})}async function Ho(){await browser.storage.session.remove(["sessionTargetTabId","sessionTargetOrigin","sessionTargetState","sessionPreview"])}async function fw(e){let r=Date.now()+15e3;for(;Date.now()<r;){let[i]=await browser.downloads.search({id:e});if(i?.state==="complete")return!0;if(i?.state==="interrupted")return!1;await new Promise(o=>setTimeout(o,100))}return!1}var Ah,Th;async function pw(e,r){for(let i=1;;i++)try{return await browser.tabs.captureVisibleTab(e,r)}catch(o){let t=o instanceof Error?o.message:String(o);if(i>=4||!/MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND/.test(t))throw o;await new Promise(n=>setTimeout(n,550))}}var Ph={getViewport:e=>dt.get(e),resizePreview:(...e)=>dt.set(...e),getDiagnostics:vw},ee=new In(async e=>{let r=b.resolve(e.tabId);ne(r);let i=b.generation,o=await ee.getTarget(r);if(zh(r,o.url??""),i!==b.generation)throw new x("GS_TARGET_CHANGED","The target changed before native capture.");Fe(o.url??"",Be);let t=o.windowId;if(t===void 0)throw new x("GS_CAPTURE_FAILED","The authorized target window is unavailable.");let n=()=>nh(()=>pw(t,{format:e.format,quality:e.quality}));return wh({tabId:r,targetTabId:r,generation:i,currentGeneration:()=>b.generation,url:o.url??"",currentTarget:()=>ee.getTarget(r),backgroundMode:$e,permissionGranted:oe,foreground:n,background:()=>o.active?n():(eh(r,b.selectedTab),th(r,e.format??"jpeg",e.quality??85))})},async e=>{let r=b.resolve();ne(r);let i=await browser.tabs.sendMessage(r,{type:"gazesight-capture-content",operation:ih.parse(e)},{frameId:0});if(!i?.ok)throw new x("GS_CAPTURE_FAILED","Fixed content operation failed.");return i.value},Ph);function gw(){return/Chrom(?:e|ium)\/([\d.]+)/.exec(globalThis.navigator?.userAgent??"")?.[1]??"unknown"}async function hw(){let e={extensionVersion:_h,extensionId:browser.runtime.id,capabilities:["highlight","clear_highlight","capture_region","capture_element","capture_full_page","get_dom","get_element","get_changed_regions","get_viewport","set_viewport",...kn.options,"get_console","get_network_failures","get_page_status"],targetState:b.state,browser:{name:"chrome",version:gw()},backgroundCapture:{enabled:$e==="enabled",permissionGranted:oe}};if(b.selectedTab===null)return{selectedTab:null,url:null,...e};try{let r=await ee.getTarget(b.selectedTab);return{selectedTab:b.selectedTab,url:r.url??null,...e}}catch{return b.remove(b.selectedTab),await Ho(),{selectedTab:null,url:null,...e,targetState:b.state}}}var Ud=Promise.resolve(),Tn;function de(){let e={text:yh(De,b.state,Ed,On),color:De&&b.state==="authorized"?"#15734b":"#8c5321",title:b.state==="reauthorization_required"?"GazeSight: click in the target tab to reauthorize this document":"GazeSight: use this tab"};return Ud=Ud.catch(()=>{}).then(async()=>{try{let r=await Promise.allSettled([Tn?.text!==e.text?Promise.resolve().then(()=>browser.action.setBadgeText({text:e.text})):void 0,Tn?.color!==e.color?Promise.resolve().then(()=>browser.action.setBadgeBackgroundColor({color:e.color})):void 0,Tn?.title!==e.title?Promise.resolve().then(()=>browser.action.setTitle({title:e.title})):void 0]);for(let i of r)if(i.status==="rejected")throw i.reason;Tn=e}catch(r){throw Tn=void 0,r}}),Ud}function kh(){return browser.scripting}async function Nn(e){await kh().executeScript({target:{tabId:e},files:["content.js"]}).catch(()=>{}),De&&b.selectedTab===e&&b.state==="authorized"&&(await kh().executeScript({target:{tabId:e,frameIds:[0]},files:["diagnostics-page.js"],world:"MAIN",injectImmediately:!0}).catch(()=>{}),!De||b.selectedTab!==e||b.state!=="authorized"?await Xo(e):await lt(e))}async function vw(e){let r=await browser.tabs.sendMessage(e,{type:"gazesight-diagnostics-content",operation:{op:"status"}},{frameId:0});if(!r?.ok)throw new x("GS_DIAGNOSTICS_UNAVAILABLE","Select the target again to initialize diagnostics.");return Id.parse(r.value)}async function Xo(e){await Dn(e,{op:"clear"}).catch(()=>{}),await wr(e,{op:"set",state:"none"}),$r===e&&($r=null),await browser.tabs.sendMessage(e,{type:"gazesight-diagnostics-content",operation:{op:"stop"}},{frameId:0}).catch(()=>{})}async function Dn(e,r){let i=await browser.tabs.sendMessage(e,{type:"gazesight-overlay-content",operation:r},{frameId:0});if(!i?.ok)throw new x(i?.code??"GS_HIGHLIGHT_UNAVAILABLE","The overlay operation was refused or unavailable.");return i.value===!0}function bw(e){return e?$e==="enabled"&&oe?"background":"authorized":"none"}async function wr(e,r){await browser.tabs.sendMessage(e,{type:"gazesight-target-indicator-content",operation:r}).catch(()=>{})}async function lt(e){await wr(e,{op:"set",state:bw(b.state==="authorized"&&b.selectedTab===e)})}function jn(){yr.clear(),_r.clear()}function Oh(e){if(!(!De||b.state!=="authorized"||e.tabId!==b.selectedTab||!b.isSelectedOrigin(e.url)))try{Fe(e.url,Be);let r=bh(e);r&&_r.push(r)}catch{}}browser.webRequest.onCompleted.addListener(Oh,{urls:["http://*/*","https://*/*"]});browser.webRequest.onErrorOccurred.addListener(Oh,{urls:["http://*/*","https://*/*"]});async function $w(e){let r=e.payload.tabId;if(r===void 0&&e.type.startsWith("capture")&&"url"in e.payload&&e.payload.url){let o=e.payload.url,t=(await browser.tabs.query({})).filter(n=>n.url===o);if(t.length!==1)throw new x("GS_TAB_NOT_FOUND","Provide a tabId or a URL matching exactly one open Chrome tab.");r=t[0].id}r=b.resolve(r),ne(r);let i;try{i=await ee.getTarget(r)}catch{throw new x("GS_TAB_NOT_FOUND","The Chrome tab was closed. Select a new target.")}return Fe(i.url??"",Be),zh(r,i.url??""),i}async function Dh(e){let r=await $w(e),i=r.id;if(e.type==="highlight"||e.type==="clear_highlight"){if(ne(i),Pn)throw new x("GS_CAPTURE_BUSY","Wait for the current capture before changing its overlay.");let o=b.generation,t=await Dn(i,e.type==="highlight"?{op:"show",options:e.payload}:{op:"clear"}),n=await ee.getTarget(i);if(o!==b.generation||n.url!==r.url)throw await Dn(i,{op:"clear"}).catch(()=>{}),new x("GS_TARGET_CHANGED","The target changed while highlighting.");return ne(i),$r=t?i:null,{tabId:i,url:n.url,highlighted:t}}if(e.type==="get_console"||e.type==="get_network_failures"||e.type==="get_page_status"){ne(i);let o=b.generation,t=e.type==="get_network_failures"?void 0:await ee.getDiagnostics(i),n=await ee.getTarget(i);if(o!==b.generation||n.url!==r.url)throw new x("GS_TARGET_CHANGED","The target document changed during diagnostics.");return ne(i),e.type==="get_console"?{tabId:i,...yr.read(e.payload.maxEntries,e.payload.reset),forwardingDropped:t.consoleForwardingDropped}:e.type==="get_network_failures"?{tabId:i,..._r.read(e.payload.maxEntries,e.payload.reset)}:{...t,tabId:i,targetState:b.state,runtimeErrorCount:Oe.get(i)?.length??0,consoleEntryCount:yr.count,networkFailureCount:_r.count}}if(kn.safeParse(e.type).success){ne(i);let o=b.generation,t=await browser.tabs.sendMessage(i,{type:"gazesight-interaction-content",operation:{type:e.type,options:e.payload}},{frameId:0}).catch(()=>{throw new x("GS_TARGET_CHANGED","Interaction content unavailable; select the target again.")}),n=await ee.getTarget(i);if(o!==b.generation||n.url!==r.url)throw new x("GS_TARGET_CHANGED","The document changed during interaction; the action may already have occurred. Inspect before retrying.");if(ne(i),!t?.ok)throw new x(typeof t?.code=="string"&&t.code.startsWith("GS_")?t.code:"GS_INTERACTION_FAILED","The DOM interaction was refused or failed.");return{tabId:i,url:n.url,action:e.type,inputSource:"dom",completed:!0,...t.value}}if(e.type==="get_viewport"||e.type==="set_viewport"){ne(i);let o=b.generation,t=async()=>{ne(i);let u=await ee.getTarget(i);if(b.generation!==o||u.url!==r.url)throw new x("GS_TARGET_CHANGED","The selected source changed during viewport operation.")},n=e.type==="get_viewport"?await ee.getViewport(r):await ee.resizePreview(r,e.payload,t);await t(),Fe(n.url,Be),e.type==="set_viewport"&&await Pe();let{movedToCompact:a,...s}={movedToCompact:!1,...n};return a&&(ue&&le?b.refresh(n.tabId):b.reauthorize(n.tabId),await Pe(),await de(),await Q?.publish()),{...s,requiresTargetSelection:!mw(n.tabId)}}if(e.type==="get_dom"||e.type==="get_element"||e.type==="get_changed_regions"){ne(i);let o=b.generation,t=await browser.tabs.sendMessage(i,{type:"gazesight-dom-content",operation:{type:e.type,options:{...e.payload,tabId:i}}},{frameId:0}).catch(()=>{throw new x("GS_TARGET_CHANGED","DOM content script unavailable; reauthorize the target.")});ne(i);let n=await ee.getTarget(i);if(b.generation!==o||n.url!==r.url)throw new x("GS_TARGET_CHANGED","The target changed during inspection.");if(!t?.ok)throw new x(typeof t?.code=="string"&&t.code.startsWith("GS_")?t.code:"GS_DOM_FAILED","The fixed DOM inspection operation failed.");return t.value}if(e.type==="capture_region"||e.type==="capture_element"||e.type==="capture_full_page"){ne(i);let o=b.generation;async function t(){ne(i);let a=await ee.getTarget(i);if(o!==b.generation||a.url!==r.url||($e!=="enabled"||!oe)&&!a.active)throw new x("GS_TARGET_CHANGED","The authorized active target changed during capture.")}let n=new In(async a=>(await t(),Dh({id:e.id,version:1,type:"capture",payload:Ve.parse({...a,tabId:i})})),async a=>{await t();let s=await browser.tabs.sendMessage(i,{type:"gazesight-capture-content",operation:a},{frameId:0}).catch(()=>{throw new x("GS_TARGET_CHANGED","Capture content script unavailable; reauthorize the target.")});if(await t(),!s?.ok)throw new x(typeof s?.code=="string"&&s.code.startsWith("GS_")?s.code:"GS_CAPTURE_FAILED","The fixed content capture operation failed.");return s.value},Ph);return uh(n,e,e.type==="capture_full_page"?cw:uw)}if(e.type==="capture"){ne(i);let o=performance.now(),t=b.generation;if(($e!=="enabled"||!oe)&&!r.active)throw new x("GS_CAPTURE_FAILED","Bring the selected GazeSight tab to the front in its Chrome window before capturing.");let n=0,a;if(e.payload.waitForStable){let h=await browser.tabs.sendMessage(i,{type:"gazesight-wait-stable",options:e.payload},{frameId:0}).catch(()=>{throw new x("GS_TARGET_CHANGED","The target document closed or navigated, or its content script is unavailable. Click the GazeSight icon in the target tab.")});if(!h?.ok)throw new x(h?.code==="GS_TARGET_CHANGED"?"GS_TARGET_CHANGED":"GS_RENDER_NOT_STABLE","The render did not appear stable before maxWaitMs. Retry after updates settle.",h?.stability?xd.parse(h.stability):void 0);n=h.stabilityWaitMs,a={lastMutationAgoMs:h.lastMutationAgoMs,fontsReady:h.fontsReady,pendingImages:h.pendingImages,timeoutReached:h.timeoutReached}}if(t!==b.generation)throw new x("GS_TARGET_CHANGED","The target document changed during capture preparation.");let s=performance.now(),u=await ee.capture(e.payload).then(h=>{if(typeof h!="string")throw new x("GS_CAPTURE_FAILED","Invalid native capture result.");return h}).catch(async h=>{throw h instanceof x&&h.code==="GS_PERMISSION_DENIED"?(b.reauthorize(i),await Pe(),await de(),await Q?.publish(),new x("GS_REAUTHORIZE_TARGET","Chrome requires permission again. Click the GazeSight extension icon in the target tab.")):h}),c=performance.now()-s,d=$e==="enabled"&&oe?[await ee.getTarget(i)]:await browser.tabs.query({active:!0,windowId:r.windowId});if(t!==b.generation)throw new x("GS_TARGET_CHANGED","The target document changed during native capture. Click the GazeSight icon in the target tab again.");if(d[0]?.id!==i||d[0]?.url!==r.url)throw new x("GS_CAPTURE_FAILED","The active tab changed during capture. Retry with the preview tab active.");let m=await createImageBitmap(await(await fetch(u)).blob()),p=m.width,f=m.height;return m.close(),{tabId:i,url:r.url,width:p,height:f,format:e.payload.format,captureMs:c,stabilityWaitMs:n,extensionTotalMs:performance.now()-o,renderAppearsStable:e.payload.waitForStable,stable:e.payload.waitForStable,...a,dataUrl:u}}if(e.type==="get_errors"){ne(i);let o=Oe.get(i)??[];return Oe.set(i,[]),{tabId:i,errors:o}}if(e.type==="reload")return await Td(b,i,r.url,async()=>{await Pe(),await de(),await Q?.publish()},async()=>(await ee.getTarget(i)).url??"",()=>ee.reload(i,e.payload.bypassCache)),await Ih(i),{tabId:i,url:r.url};if(e.type!=="navigate")throw new x("GS_INVALID_MESSAGE","Unsupported operation.");return Fe(e.payload.url,Be),await Td(b,i,r.url,async()=>{await Pe(),await de(),await Q?.publish()},async()=>(await ee.getTarget(i)).url??"",()=>ee.navigate(i,e.payload.url)),await Ih(i),{tabId:i,url:e.payload.url}}async function Ih(e){if(!(ue&&le))return;let r=Date.now()+5e3;for(;Date.now()<r;){if(b.selectedTab!==e||b.state==="none"||b.state==="authorized")return;let i=await browser.tabs.get(e).catch(()=>{});if(i?.status==="complete"&&b.isSelectedOrigin(i.url??"")){b.resume(e),await Pe(),await lt(e),await de(),await Q?.publish();return}await new Promise(o=>setTimeout(o,100))}}async function yw(){let e=await browser.storage.session.get(["sessionTargetTabId","sessionTargetOrigin","sessionTargetState","sessionPreview"]),r=typeof e.sessionTargetTabId=="number"?e.sessionTargetTabId:null,i=typeof e.sessionTargetOrigin=="string"?e.sessionTargetOrigin:null;if(r===null||i===null)return!1;try{let o=await browser.tabs.get(r);if(!o.url)throw new x("GS_TARGET_CHANGED","Stale session target.");return Fe(o.url,Be),b.choose(r,o.url),(e.sessionTargetState==="reauthorization_required"||!Nd(o.url,i))&&b.reauthorize(r),e.sessionPreview&&typeof e.sessionPreview=="object"&&await dt.hydrate(e.sessionPreview,b).catch(()=>!1),await Nn(r),await de(),!0}catch{return await Ho(),!1}}async function _w(){let e=await browser.storage.local.get(["continuousAuthPrimaryTabId","continuousAuthOrigin"]),r=typeof e.continuousAuthPrimaryTabId=="number"?e.continuousAuthPrimaryTabId:null,i=typeof e.continuousAuthOrigin=="string"?e.continuousAuthOrigin:null;if(!(r===null||i===null))try{let o=await browser.tabs.get(r);if(!o.url||!Nd(o.url,i))throw new x("GS_TARGET_CHANGED","Stale persisted target.");Fe(o.url,Be),b.choose(r,o.url),await Pe(),await Nn(r),await de()}catch{await browser.storage.local.remove(["continuousAuthPrimaryTabId","continuousAuthOrigin"])}}async function Zd(){Q?.stop();let e=await browser.storage.local.get(["port","token","allowedOrigins","backgroundCaptureEnabled","continuousAuthorizationEnabled"]);if(le=await browser.permissions.contains({origins:["<all_urls>"]}),oe=await chrome.permissions.contains({permissions:["tabCapture","offscreen"]}),$e=e.backgroundCaptureEnabled===!0&&oe?"enabled":"disabled",e.backgroundCaptureEnabled===!0&&!oe&&await browser.storage.local.set({backgroundCaptureEnabled:!1}),ue=e.continuousAuthorizationEnabled===!0&&le,e.continuousAuthorizationEnabled===!0&&!le&&await browser.storage.local.set({continuousAuthorizationEnabled:!1}),Be=Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],b.selectedTab===null&&!await yw()&&ue&&await _w(),typeof e.token!="string"||!/^[a-f0-9]{64}$/.test(e.token))return;let r=Number(e.port??32147);!Number.isInteger(r)||r<1024||r>65535||(Q=new Vo(r,e.token,hw,Cd,i=>{De=i,!i&&b.selectedTab!==null&&(Rd(b.selectedTab),Xo(b.selectedTab)),i&&b.state==="authorized"&&b.selectedTab!==null&&Nn(b.selectedTab),de()},2e4),Q.start())}async function Cd(e){let r=e.type==="capture"||e.type.startsWith("capture_"),i=!1,o=$r;if(r&&o!==null){if(Pn)throw new x("GS_CAPTURE_BUSY","Wait for the current overlay capture to complete.");ne(b.resolve(e.payload.tabId)),Pn=!0;try{(!("includeOverlay"in e.payload)||e.payload.includeOverlay!==!0)&&(i=await Dn(o,{op:"suspend"}),i||($r=null))}catch(a){throw Pn=!1,a}}let t=r&&b.state==="authorized"?b.selectedTab:null;t!==null&&await wr(t,{op:"suspend"});let n;r&&(Ed=!0,n=setTimeout(()=>{de().catch(()=>{})},120));try{let a=await Dh(e);if(On=!1,r){let s=a;Ah={mode:e.payload&&"waitForStable"in e.payload&&e.payload.waitForStable?"STABLE":"FAST",width:s.width,height:s.height,time:new Date().toISOString()}}return a}catch(a){throw On=!0,Th={code:a instanceof x?a.code:"GS_OPERATION_FAILED",message:Ge(a instanceof Error?a.message:"Operation failed",512),time:new Date().toISOString()},a}finally{t!==null&&await wr(t,{op:"resume"}),i&&o!==null&&(await Dn(o,{op:"resume"}).catch(()=>!1)||($r=null)),r&&o!==null&&(Pn=!1),n!==void 0&&clearTimeout(n),r&&(Ed=!1),de().catch(()=>{})}}async function Ce(){let e,r;if(b.selectedTab!==null){let i=await browser.tabs.get(b.selectedTab).catch(()=>{});e=i?.url?Sn(i.url,i.url):void 0,De&&b.state==="authorized"&&(r=(await ee.getDiagnostics(b.selectedTab).catch(()=>{}))?.viewport)}return{connected:De,paired:De,targetState:b.state,url:e,viewport:r,lastCapture:Ah,lastError:Th,backgroundMode:$e,backgroundCapture:{enabled:$e==="enabled",permissionGranted:oe},continuousAuthorization:{enabled:ue,permissionGranted:le,authorizedOrigin:ue&&b.state==="authorized"?b.selectedOrigin:null},consoleCount:yr.count,networkCount:_r.count,runtimeErrorCount:b.selectedTab===null?0:Oe.get(b.selectedTab)?.length??0}}async function ww(e){if(e==="status")return Ce();if(e==="background-enable")return $e="requesting",oe=await chrome.permissions.contains({permissions:["tabCapture","offscreen"]}),$e=oe?"enabled":"permission_denied",await browser.storage.local.set({backgroundCaptureEnabled:oe}),b.state==="authorized"&&b.selectedTab!==null&&await lt(b.selectedTab),await Q?.publish(),Ce();if(e==="background-denied")return $e="permission_denied",oe=!1,await browser.storage.local.set({backgroundCaptureEnabled:!1}),b.state==="authorized"&&b.selectedTab!==null&&await lt(b.selectedTab),await Q?.publish(),Ce();if(e==="background-disable")return $e="disabled",await browser.storage.local.set({backgroundCaptureEnabled:!1}),await chrome.permissions.remove({permissions:["tabCapture","offscreen"]}),oe=await chrome.permissions.contains({permissions:["tabCapture","offscreen"]}),b.state==="authorized"&&b.selectedTab!==null&&await lt(b.selectedTab),await Q?.publish(),Ce();if(e==="continuous-enable")return ue=!1,le=await browser.permissions.contains({origins:["<all_urls>"]}),ue=le,await browser.storage.local.set({continuousAuthorizationEnabled:le}),ue&&b.state==="authorized"&&b.selectedTab!==null&&b.selectedOrigin!==null&&await browser.storage.local.set({continuousAuthPrimaryTabId:b.selectedTab,continuousAuthOrigin:b.selectedOrigin}),await Q?.publish(),Ce();if(e==="continuous-denied")return ue=!1,await browser.storage.local.set({continuousAuthorizationEnabled:!1}),await Q?.publish(),Ce();if(e==="continuous-disable")return ue=!1,await browser.storage.local.set({continuousAuthorizationEnabled:!1}),await browser.storage.local.remove(["continuousAuthPrimaryTabId","continuousAuthOrigin"]),await browser.permissions.remove({origins:["<all_urls>"]}),le=await browser.permissions.contains({origins:["<all_urls>"]}),await Q?.publish(),Ce();if(e==="disconnect"){let i=b.selectedTab;return i!==null&&(await Rd(i),await Xo(i),b.remove(i)),jn(),Oe.clear(),On=!1,await Ho(),await browser.storage.local.remove(["continuousAuthPrimaryTabId","continuousAuthOrigin"]),dt.clear(),await de(),await Q?.publish(),Ce()}if(e==="select"){let[i]=await browser.tabs.query({active:!0,lastFocusedWindow:!0});if(!i?.id)throw new x("GS_NO_TARGET_TAB","Activate your preview page before using this tab.");if(Fe(i.url??"",Be),!await Ld(i))throw new x("GS_TARGET_SELECTION_FAILED","Selection failed. Check the allowed origin and settings.");return Ce()}if(!De)throw new x("GS_NOT_CONNECTED","Start the GazeSight MCP server and check pairing in settings.");let r=b.resolve();return ne(r),e==="diagnostics"?{status:await Ce(),console:yr.read(10,!1),network:_r.read(10,!1),runtimeErrors:(Oe.get(r)??[]).slice(-10)}:e==="fast"?lw.run({permissionGranted:()=>browser.permissions.contains({permissions:["downloads"]}),capture:async()=>await Cd({id:crypto.randomUUID(),version:1,type:"capture",payload:Ve.parse({tabId:r,format:"png",waitForStable:!1})}),download:async i=>{let o=await(await fetch(i.url)).blob(),t=URL.createObjectURL(o);try{return await browser.downloads.download({...i,url:t})}finally{setTimeout(()=>URL.revokeObjectURL(t),3e4)}},waitForCompletion:fw}):(await Cd({id:crypto.randomUUID(),version:1,type:"capture",payload:Ve.parse({tabId:r,waitForStable:!0})}),Ce())}async function Rd(e){await browser.tabs.sendMessage(e,{type:"gazesight-dom-content",operation:{type:"stop_tracking"}},{frameId:0}).catch(()=>{})}async function Ld(e){try{return Fe(e.url??"",Be),b.selectedTab!==null&&(await Rd(b.selectedTab),await Xo(b.selectedTab)),jn(),Oe.clear(),b.choose(e.id,e.url),On=!1,await Pe(),ue&&b.selectedOrigin!==null&&await browser.storage.local.set({continuousAuthPrimaryTabId:e.id,continuousAuthOrigin:b.selectedOrigin}),await Nn(e.id),await de(),await Q?.publish(),!0}catch{return await browser.runtime.openOptionsPage(),!1}}browser.action.onClicked.addListener(Ld);browser.commands.onCommand.addListener(async(e,r)=>{try{let i=await vh(e,r);i&&await Ld(i)}catch{await browser.runtime.openOptionsPage()}});browser.tabs.onRemoved.addListener(e=>{e===b.selectedTab&&(jn(),Ho(),browser.storage.local.remove(["continuousAuthPrimaryTabId","continuousAuthOrigin"])),b.remove(e),Oe.delete(e),de(),Q?.publish()});browser.windows.onRemoved.addListener(e=>{dt.removeWindow(e),Pe()});browser.tabs.onUpdated.addListener((e,r)=>{if(e===b.selectedTab){if(r.url&&!b.isSelectedOrigin(r.url)){jn(),Oe.delete(e),b.reauthorize(e),Pe(),wr(e,{op:"set",state:"none"}),de(),Q?.publish();return}r.status==="loading"&&(jn(),Oe.delete(e),$e==="enabled"&&oe||ue&&le?b.refresh(e):(b.reauthorize(e),wr(e,{op:"set",state:"none"})),Pe(),de()),r.status==="complete"&&(ue&&le&&browser.tabs.get(e).then(i=>{b.selectedTab===e&&b.state==="reauthorization_required"&&b.isSelectedOrigin(i.url??"")&&(b.resume(e),Pe(),lt(e),de(),Q?.publish())}).catch(()=>{}),Nn(e)),Q?.publish()}});browser.runtime.onMessage.addListener((e,r)=>{if(r.id===browser.runtime.id){if(e?.type==="gazesight-ui"){if(!Dd(r,browser.runtime.id,browser.runtime.getURL("popup.html"))&&!Dd(r,browser.runtime.id,browser.runtime.getURL("permission.html"),!0))return;let i=$h.safeParse(e);return i.success?ww(i.data.action).then(o=>({ok:!0,value:o}),o=>({ok:!1,error:Ge(o instanceof Error?o.message:"GS_OPERATION_FAILED",512)})):Promise.resolve({ok:!1,error:"GS_INVALID_MESSAGE"})}if(!(!De||b.state!=="authorized"||r.tab?.id!==b.selectedTab||!b.isSelectedOrigin(r.tab?.url??"")||r.frameId!==0)){if(e?.type==="console-diagnostic"){let i=xn.safeParse(e.entry);i.success&&yr.push({...i.data,message:Ge(i.data.message,512)});return}if(e?.type==="runtime-error"&&r.tab?.id!==void 0&&r.frameId===0){let i=Sd.safeParse(e.error);if(i.success&&r.tab.id===b.selectedTab){let o=Oe.get(r.tab.id)??[];o.push({...i.data,message:Ge(i.data.message,4096),source:i.data.source?Sn(i.data.source,r.tab.url??i.data.source):void 0}),Oe.set(r.tab.id,o.slice(-200))}}}}});browser.storage.onChanged.addListener((e,r)=>{r==="local"&&["port","token","allowedOrigins"].some(i=>i in e)&&Zd()});function jh(e,r){return e?.some(i=>r.includes(i))??!1}browser.permissions.onRemoved.addListener(e=>{e.origins?.includes("<all_urls>")&&(le=!1,ue=!1,browser.storage.local.set({continuousAuthorizationEnabled:!1}),browser.storage.local.remove(["continuousAuthPrimaryTabId","continuousAuthOrigin"]));let r=jh(e.permissions,["tabCapture","offscreen"]);r&&(oe=!1,$e="disabled",browser.storage.local.set({backgroundCaptureEnabled:!1})),(e.origins?.includes("<all_urls>")||r)&&b.state==="authorized"&&b.selectedTab!==null&&lt(b.selectedTab),Q?.publish()});browser.permissions.onAdded.addListener(e=>{e.origins?.includes("<all_urls>")&&(le=!0),jh(e.permissions,["tabCapture","offscreen"])&&(oe=!0),b.state==="authorized"&&b.selectedTab!==null&&lt(b.selectedTab),Q?.publish()});var Nh="gazesight-reconnect";browser.alarms.create(Nh,{periodInMinutes:1});browser.alarms.onAlarm.addListener(e=>{e.name===Nh&&!De&&Zd()});Zd();})();
62
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let s=a[1];if(r===a[0]){n(a);continue}if(e.external){let c=e.external.registry.get(a[0])?.id;if(r!==a[0]&&c){n(a);continue}}if(e.metadataRegistry.get(a[0])?.id){n(a);continue}if(s.cycle){n(a);continue}s.count>1&&e.reused==="ref"&&n(a)}e.external&&(e.sharedDefsExtractedFor=e.external)}function tp(e){let r=e.anyOf;if(!Array.isArray(r)||r.length===0||e.type!==void 0)return;let i=[];for(let o of r){if(!o||typeof o!="object")return;tp(o);let t=Object.keys(o);if(t.length!==1||t[0]!=="type")return;let n=o.type;for(let a of Array.isArray(n)?n:[n]){if(typeof a!="string")return;i.includes(a)||i.push(a)}}delete e.anyOf,e.type=i.length===1?i[0]:i}var rp=new Set(["type","properties","required","additionalProperties"]),Qf=["oneOf","anyOf"];function ep(e){let r=e.additionalProperties;return r===void 0||r===!1||typeof r!="object"||r===null?null:Object.keys(r).length?r:null}function Sc(e){let r=[];for(let n of e){if(typeof n!="object"||n.type!=="object")return null;for(let a in n)if(!rp.has(a))return null;r.push(n)}let i={},o=new Set;for(let n of r){for(let a in n.properties){if(Object.prototype.hasOwnProperty.call(i,a))continue;let s=[];for(let c of r){let d=c.properties?.[a]??ep(c);d!=null&&(s.some(m=>JSON.stringify(m)===JSON.stringify(d))||s.push(d))}let u=s.length===1?s[0]:Sc(s)??{allOf:s};ae(i,a,u)}for(let a of n.required??[])o.add(a)}let t={type:"object",properties:i};if(o.size&&(t.required=[...o]),r.every(n=>n.additionalProperties===!1))t.additionalProperties=!1;else{let n=[];for(let a of r){let s=ep(a);s&&!n.some(u=>JSON.stringify(u)===JSON.stringify(s))&&n.push(s)}n.length===1?t.additionalProperties=n[0]:n.length>1&&(t.additionalProperties={allOf:n})}return t}function e_(e){let r=e.allOf;if(!Array.isArray(r)||r.length<2)return;for(let t of rp)if(t in e)return;let i=r.filter(t=>Qf.some(n=>Array.isArray(t[n]))),o=null;if(!i.length)o=Sc(r);else{let t=i[0],n=Qf.find(u=>Array.isArray(t[u]));if(Object.keys(t).length!==1)return;let a=r.filter(u=>u!==t),s=t[n].map(u=>Sc([...a,u]));if(s.some(u=>!u))return;o={[n]:s}}o&&(delete e.allOf,an(e,o))}function ot(e,r){let i=e.seen.get(r);if(!i)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=s=>{let u=e.seen.get(s);if(u.ref===null)return;let c=u.def??u.schema,d={...c},m=u.ref;if(u.ref=null,m){o(m);let f=e.seen.get(m),h=f.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(h)):an(c,h),an(c,d),s._zod.parent===m)for(let k in c)k==="$ref"||k==="allOf"||k in d||delete c[k];if(h.$ref&&f.def)for(let k in c)k==="$ref"||k==="allOf"||k in f.def&&JSON.stringify(c[k])===JSON.stringify(f.def[k])&&delete c[k]}let p=s._zod.parent;if(p&&p!==m){o(p);let f=e.seen.get(p);if(f?.schema.$ref&&(c.$ref=f.schema.$ref,f.def))for(let h in c)h==="$ref"||h==="allOf"||h in f.def&&JSON.stringify(c[h])===JSON.stringify(f.def[h])&&delete c[h]}e.override({zodSchema:s,jsonSchema:c,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let s of[...e.seen.entries()].reverse())o(s[0]);if(e.target!=="openapi-3.0")for(let s of e.seen.entries())tp(s[1].def??s[1].schema);for(let s of e.deferred)s();if(e.intersections.length){let s=new Map;for(let u of e.seen.values())for(let c of[u.schema,u.def]){let d=c?.allOf;if(!Array.isArray(d))continue;let m=s.get(d);m?m.push(c):s.set(d,[c])}for(let u of e.intersections)for(let c of s.get(u)??[])e_(c)}}let t={};if(e.target==="draft-2020-12"?t.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?t.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?t.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let s=e.external.registry.get(r)?.id;if(!s)throw new Error("Schema is missing an `id` property");t.$id=e.external.uri(s)}an(t,i.defId?i.schema:i.def??i.schema);let n=e.metadataRegistry.get(r)?.id;n!==void 0&&t.id===n&&delete t.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let s of e.seen.entries()){let u=s[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,ae(a,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?t.$defs=a:t.definitions=a);try{let s=JSON.parse(JSON.stringify(t));return Object.defineProperty(s,"~standard",{value:{...r["~standard"],jsonSchema:{input:sr(r,"input",e.processors),output:sr(r,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function he(e,r){let i=r??{seen:new Set};if(i.seen.has(e))return!1;i.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return he(o.element,i);if(o.type==="set")return he(o.valueType,i);if(o.type==="lazy")return he(o.getter(),i);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return he(o.innerType,i);if(o.type==="intersection")return he(o.left,i)||he(o.right,i);if(o.type==="record"||o.type==="map")return he(o.keyType,i)||he(o.valueType,i);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:he(o.in,i)||he(o.out,i);if(o.type==="object"){for(let t in o.shape)if(he(o.shape[t],i))return!0;return!1}if(o.type==="union"){for(let t of o.options)if(he(t,i))return!0;return!1}if(o.type==="tuple"){for(let t of o.items)if(he(t,i))return!0;return!!(o.rest&&he(o.rest,i))}return!1}var zc=(e,r={})=>i=>{let o=nt({...i,processors:r});return G(e,o),it(o,e),ot(o,e)},sr=(e,r,i={})=>o=>{let{libraryOptions:t,target:n}=o??{},a=nt({...t??{},target:n,io:r,processors:i});return G(e,a),it(a,e),ot(a,e)};var ur=(e,r,i)=>{(e[r]===void 0||i>e[r])&&(e[r]=i)},cr=(e,r,i)=>{(e[r]===void 0||i<e[r])&&(e[r]=i)},np=(e,r)=>{ur(e,"minimum",r),cr(e,"maximum",r)},sp=(e,r)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(r)||e.multipleOf.push(r)},up=(e,r)=>{e.patterns??(e.patterns=new Set),e.patterns.add(r)},cp=(e,r)=>{e.mime=e.mime?e.mime.filter(i=>r.includes(i)):[...r]},lp=(e,r)=>{e.format=r,r.includes("int")&&(e.isInt=!0)},ip=(e,r)=>ur(e,"minimum",r.minimum),op=(e,r)=>cr(e,"maximum",r.maximum),ap=e=>(r,i)=>{lp(r,i.format);let[o,t]=e[i.format];ur(r,"minimum",o),cr(r,"maximum",t)},t_={greater_than:(e,r)=>ur(e,r.inclusive?"minimum":"exclusiveMinimum",r.value),less_than:(e,r)=>cr(e,r.inclusive?"maximum":"exclusiveMaximum",r.value),multiple_of:(e,r)=>sp(e,r.value),number_format:ap(zr),bigint_format:ap(Ar),min_length:ip,max_length:op,length_equals:(e,r)=>np(e,r.length),min_size:ip,max_size:op,size_equals:(e,r)=>np(e,r.size),string_format:(e,r)=>{lp(e,r.format),r.pattern&&up(e,r.pattern),(r.format==="base64"||r.format==="base64url")&&(e.contentEncoding=r.format),(r.local||r.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,r)=>cp(e,r.mime)};function re(e){let r={},i=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...i.checks??[]]:i.checks??[];for(let n of o)t_[n._zod.def.check]?.(r,n._zod.def);let t=e._zod.bag;t.minimum!==void 0&&ur(r,"minimum",t.minimum),t.exclusiveMinimum!==void 0&&ur(r,"exclusiveMinimum",t.exclusiveMinimum),t.maximum!==void 0&&cr(r,"maximum",t.maximum),t.exclusiveMaximum!==void 0&&cr(r,"exclusiveMaximum",t.exclusiveMaximum),t.multipleOf!==void 0&&sp(r,t.multipleOf),t.format!==void 0&&(r.format??(r.format=t.format),t.format.includes("int")&&(r.isInt=!0)),t.mime&&cp(r,t.mime);for(let n of t.patterns??[])up(r,n);return r}var r_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},n_=new Map([[mi,Ua],[Gr,Ea]]),dp=e=>n_.get(e)??e,Pc=(e,r,i,o)=>{let t=i;t.type="string";let{minimum:n,maximum:a,format:s,patterns:u,contentEncoding:c,laxFormat:d}=re(e);if(typeof n=="number"&&(t.minLength=n),typeof a=="number"&&(t.maxLength=a),s&&(t.format=r_[s]??s,t.format===""&&delete t.format,(s==="time"||d)&&delete t.format),c&&(t.contentEncoding=c),u&&u.size>0){let m=[...u].map(dp);m.length===1?t.pattern=m[0].source:m.length>1&&(t.allOf=[...m.map(p=>({...r.target==="draft-07"||r.target==="draft-04"||r.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},Oc=(e,r,i,o)=>{let t=i,{minimum:n,maximum:a,multipleOf:s,exclusiveMaximum:u,exclusiveMinimum:c,isInt:d}=re(e);t.type=d?"integer":"number";let m=typeof c=="number"&&c>=(n??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),f=r.target==="draft-04"||r.target==="openapi-3.0";if(m?f?(t.minimum=c,t.exclusiveMinimum=!0):t.exclusiveMinimum=c:typeof n=="number"&&(t.minimum=n),p?f?(t.maximum=u,t.exclusiveMaximum=!0):t.exclusiveMaximum=u:typeof a=="number"&&(t.maximum=a),s){let h=new Set;for(let P of s)Number.isFinite(P)&&P!==0?h.add(Math.abs(P)):te(e,r,t,o,`A multipleOf divisor of ${P} cannot be represented in JSON Schema`);let[_,...k]=h;_!==void 0&&(t.multipleOf=_),k.length&&(t.allOf=[...t.allOf??[],...k.map(P=>({multipleOf:P}))])}},Dc=(e,r,i,o)=>{i.type="boolean"},jc=(e,r,i,o)=>{te(e,r,i,o,"BigInt cannot be represented in JSON Schema")},Nc=(e,r,i,o)=>{te(e,r,i,o,"Symbols cannot be represented in JSON Schema")},Uc=(e,r,i,o)=>{r.target==="openapi-3.0"?(i.type="string",i.nullable=!0,i.enum=[null]):i.type="null"},Ec=(e,r,i,o)=>{te(e,r,i,o,"Undefined cannot be represented in JSON Schema")},Cc=(e,r,i,o)=>{te(e,r,i,o,"Void cannot be represented in JSON Schema")},Zc=(e,r,i,o)=>{i.not={}},Rc=(e,r,i,o)=>{},Lc=(e,r,i,o)=>{},Mc=(e,r,i,o)=>{te(e,r,i,o,"Date cannot be represented in JSON Schema")},Vc=(e,r,i,o)=>{let t=e._zod.def,n=Nt(t.entries);if(n.length===0){i.not={};return}n.every(a=>typeof a=="number")&&(i.type="number"),n.every(a=>typeof a=="string")&&(i.type="string"),i.enum=n},Fc=(e,r,i,o)=>{let t=e._zod.def;if(t.values.length===0){i.not={};return}let n=[];for(let a of t.values)if(a===void 0){if(te(e,r,i,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a=="bigint"){if(te(e,r,i,o,"BigInt literals cannot be represented in JSON Schema"))return;n.push(Number(a))}else n.push(a);if(n.length!==0)if(n.length===1){let a=n[0];i.type=a===null?"null":typeof a,r.target==="draft-04"||r.target==="openapi-3.0"?i.enum=[a]:i.const=a}else n.every(a=>typeof a=="number")&&(i.type="number"),n.every(a=>typeof a=="string")&&(i.type="string"),n.every(a=>typeof a=="boolean")&&(i.type="boolean"),n.every(a=>a===null)&&(i.type="null"),i.enum=n},Gc=(e,r,i,o)=>{te(e,r,i,o,"NaN cannot be represented in JSON Schema")},Bc=(e,r,i,o)=>{let t=i,n=e._zod.pattern;if(!n)throw new Error("Pattern not found in template literal");t.type="string",t.pattern=n.source},Jc=(e,r,i,o)=>{let t=i;t.type="string",t.format="binary",t.contentEncoding="binary";let{minimum:n,maximum:a,mime:s}=re(e);n!==void 0&&(t.minLength=n),a!==void 0&&(t.maxLength=a),s&&(s.length===0?t.not={}:s.length===1?t.contentMediaType=s[0]:t.anyOf=s.map(u=>({contentMediaType:u})))},Wc=(e,r,i,o)=>{i.type="boolean"},Kc=(e,r,i,o)=>{te(e,r,i,o,"Custom types cannot be represented in JSON Schema")},Hc=(e,r,i,o)=>{te(e,r,i,o,"Function types cannot be represented in JSON Schema")},Xc=(e,r,i,o)=>{te(e,r,i,o,"Transforms cannot be represented in JSON Schema")},qc=(e,r,i,o)=>{te(e,r,i,o,"Map cannot be represented in JSON Schema")},Yc=(e,r,i,o)=>{te(e,r,i,o,"Set cannot be represented in JSON Schema")},Qc=(e,r,i,o)=>{let t=i,n=e._zod.def,{minimum:a,maximum:s}=re(e);typeof a=="number"&&(t.minItems=a),typeof s=="number"&&(t.maxItems=s),t.type="array",t.items=G(n.element,r,{...o,path:[...o.path,"items"]})};function sn(e){let r=e._zod.def;return r.type==="pipe"&&r.in._zod.traits.has("$ZodTransform")?sn(r.out):r.type==="catch"?sn(r.innerType):e._zod.optin}var el=(e,r,i,o)=>{let t=i,n=e._zod.def,a=n.shape;if(Object.getOwnPropertySymbols(a).length&&te(e,r,t,o,"Symbol keys cannot be represented in JSON Schema"))return;t.type="object",t.properties={};for(let c in a)ae(t.properties,c,G(a[c],r,{...o,path:[...o.path,"properties",c]}));let u=[];for(let c of Object.keys(a)){let d=n.shape[c];(r.io==="input"?sn(d)===void 0:d._zod.optout===void 0)&&u.push(c)}u.length>0&&(t.required=u),n.catchall?._zod.def.type==="never"?t.additionalProperties=!1:n.catchall?n.catchall&&(t.additionalProperties=G(n.catchall,r,{...o,path:[...o.path,"additionalProperties"]})):r.io==="output"&&(t.additionalProperties=!1)},co=(e,r,i,o)=>{let t=e._zod.def,n=t.inclusive===!1,a=t.options.map((s,u)=>G(s,r,{...o,path:[...o.path,n?"oneOf":"anyOf",u]}));n?i.oneOf=a:i.anyOf=a},tl=(e,r,i,o)=>{let t=e._zod.def,n=G(t.left,r,{...o,path:[...o.path,"allOf",0]}),a=G(t.right,r,{...o,path:[...o.path,"allOf",1]}),s=c=>"allOf"in c&&Object.keys(c).length===1,u=[...s(n)?n.allOf:[n],...s(a)?a.allOf:[a]];i.allOf=u,r.intersections.push(u)},rl=(e,r,i,o)=>{let t=i,n=e._zod.def;t.type="array";let a=r.target==="draft-2020-12"?"prefixItems":"items",s=r.target==="draft-2020-12"||r.target==="openapi-3.0"?"items":"additionalItems",u=n.items.map((_,k)=>G(_,r,{...o,path:[...o.path,a,k]})),c=n.rest?G(n.rest,r,{...o,path:[...o.path,s,...r.target==="openapi-3.0"?[n.items.length]:[]]}):null,d=n.items.length;for(;d>0;){let _=n.items[d-1];if(!(r.io==="input"?sn(_)!==void 0:_._zod.optout==="optional"))break;d--}let m=n.items.length,p=!n.rest;r.target==="draft-2020-12"?(t.prefixItems=u,p?t.items=!1:c&&(t.items=c),d>0&&(t.minItems=d),p&&(t.maxItems=m)):r.target==="openapi-3.0"?(t.items={anyOf:u},c&&t.items.anyOf.push(c),d>0&&(t.minItems=d),p&&(t.maxItems=m)):(t.items=u,p?t.additionalItems=!1:c&&(t.additionalItems=c),d>0&&(t.minItems=d),p&&(t.maxItems=m));let{minimum:f,maximum:h}=re(e);typeof f=="number"&&(t.minItems=f),typeof h=="number"&&(t.maxItems=h)};function Ac(e,r,i){if(r.$ref){if(i.has(r))return r;i.add(r);let h=e.get(r)?.def;if(!h)return r;let _=Ac(e,h,i);return _===h?r:_}for(let h of["anyOf","oneOf"]){let _=r[h];if(!Array.isArray(_))continue;let k=_.map(P=>Ac(e,P,i));k.some((P,T)=>P!==_[T])&&(r={...r,[h]:k})}let o=Array.isArray(r.type)?r.type:[r.type],t=!o.includes("string")&&o.some(h=>h==="number"||h==="integer"),n=r.enum??(r.const!==void 0?[r.const]:void 0);if(!t&&!n?.some(h=>typeof h=="number"))return r;let{minimum:a,maximum:s,exclusiveMinimum:u,exclusiveMaximum:c,multipleOf:d,format:m,id:p,...f}=r;return f.enum?f.enum=f.enum.map(h=>typeof h=="number"?String(h):h):typeof f.const=="number"&&(f.const=String(f.const)),t&&(f.type="string",n||(f.pattern=(o.includes("number")?He:Cr).source)),f}var Tc=new WeakMap;function i_(e){let r=new Map;for(let o of e.seen.values())o.def&&!r.has(o.schema)&&r.set(o.schema,o);let i=new Map;for(let o of Tc.get(e)??[]){let t=e.seen.get(o),n=(t?.def??t?.schema)?.propertyNames;if(!n||n===!0||i.has(n))continue;let a=Ac(r,n,new Set);a!==n&&i.set(n,a)}if(i.size)for(let o of e.seen.values())for(let t of[o.schema,o.def]){let n=t&&i.get(t.propertyNames);n&&(t.propertyNames=n)}}var nl=(e,r,i,o)=>{let t=i,n=e._zod.def;t.type="object";let a=n.keyType,s=re(a).patterns;if(n.mode==="loose"&&s&&s.size>0){let d=G(n.valueType,r,{...o,path:[...o.path,"patternProperties","*"]});t.patternProperties={};for(let m of s)ae(t.patternProperties,dp(m).source,d)}else{if(r.target==="draft-07"||r.target==="draft-2020-12"){t.propertyNames=G(n.keyType,r,{...o,path:[...o.path,"propertyNames"]});let d=Tc.get(r);d||(d=[],Tc.set(r,d),r.deferred.push(()=>i_(r))),d.push(e)}t.additionalProperties=G(n.valueType,r,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,c=r.io==="input"&&sn(n.valueType)!==void 0;if(u&&!n.partial&&!c){let d=[...u].filter(m=>typeof m=="string"||typeof m=="number");d.length>0&&(t.required=d.map(String))}},il=(e,r,i,o)=>{let t=e._zod.def,n=G(t.innerType,r,o),a=r.seen.get(e);r.target==="openapi-3.0"?(a.ref=t.innerType,i.nullable=!0):i.anyOf=[n,{type:"null"}]},ol=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);n.ref=t.innerType},al=Symbol();function mp(e,r,i,o,t){let n=!1,a=JSON.stringify(e,(s,u)=>typeof u!="bigint"?u:(n=!0,null));return n?(te(r,i,o,t,"BigInt defaults cannot be represented in JSON Schema"),al):JSON.parse(a)}var sl=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);n.ref=t.innerType;let a=mp(t.defaultValue,e,r,i,o);a!==al&&(i.default=a)},ul=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);if(n.ref=t.innerType,r.io!=="input")return;let a=mp(t.defaultValue,e,r,i,o);a!==al&&(i._prefault=a)},cl=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);n.ref=t.innerType;let a;try{a=t.catchValue(void 0)}catch{te(e,r,i,o,"Dynamic catch values are not supported in JSON Schema");return}i.default=a},ll=(e,r,i,o)=>{let t=e._zod.def,n=t.in._zod.traits.has("$ZodTransform"),a=r.io==="input"?n?t.out:t.in:t.out;G(a,r,o);let s=r.seen.get(e);s.ref=a},dl=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);n.ref=t.innerType,i.readOnly=!0},ml=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);n.ref=t.innerType},lo=(e,r,i,o)=>{let t=e._zod.def;G(t.innerType,r,o);let n=r.seen.get(e);n.ref=t.innerType},fl=(e,r,i,o)=>{let t=e._zod.innerType;G(t,r,o);let n=r.seen.get(e);n.ref=t},uo={string:Pc,number:Oc,boolean:Dc,bigint:jc,symbol:Nc,null:Uc,undefined:Ec,void:Cc,never:Zc,any:Rc,unknown:Lc,date:Mc,enum:Vc,literal:Fc,nan:Gc,template_literal:Bc,file:Jc,success:Wc,custom:Kc,function:Hc,transform:Xc,map:qc,set:Yc,array:Qc,object:el,union:co,intersection:tl,tuple:rl,record:nl,nullable:il,nonoptional:ol,default:sl,prefault:ul,catch:cl,pipe:ll,readonly:dl,promise:ml,optional:lo,lazy:fl};function mo(e,r){if("_idmap"in e){let o=e,t=nt({...r,processors:uo}),n={};for(let u of o._idmap.entries()){let[c,d]=u;G(d,t)}let a={},s={registry:o,uri:r?.uri,defs:n};t.external=s;for(let u of o._idmap.entries()){let[c,d]=u;it(t,d),ae(a,c,ot(t,d))}if(Object.keys(n).length>0){let u=t.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[u]:n}}return{schemas:a}}let i=nt({...r,processors:uo});return G(e,i),it(i,e),ot(i,e)}var fo=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(r){this.ctx.counter=r}get seen(){return this.ctx.seen}constructor(r){let i=r?.target??"draft-2020-12";i==="draft-4"&&(i="draft-04"),i==="draft-7"&&(i="draft-07"),this.ctx=nt({processors:uo,target:i,...r?.metadata&&{metadata:r.metadata},...r?.unrepresentable&&{unrepresentable:r.unrepresentable},...r?.override&&{override:r.override},...r?.io&&{io:r.io}})}process(r,i={path:[],schemaPath:[]}){return G(r,this.ctx,i)}emit(r,i){i&&(i.cycles&&(this.ctx.cycles=i.cycles),i.reused&&(this.ctx.reused=i.reused),i.external&&(this.ctx.external=i.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,it(this.ctx,r);let o=ot(this.ctx,r),{"~standard":t,...n}=o;return n}};var fp={};var vr={};Je(vr,{ZodAny:()=>Ul,ZodArray:()=>Rl,ZodBase64:()=>Do,ZodBase64URL:()=>jo,ZodBigInt:()=>gr,ZodBigIntFormat:()=>Eo,ZodBoolean:()=>pr,ZodCIDRv4:()=>Po,ZodCIDRv6:()=>Oo,ZodCUID:()=>xo,ZodCUID2:()=>ko,ZodCatch:()=>ad,ZodCodec:()=>vn,ZodCreditCard:()=>zl,ZodCustom:()=>bn,ZodCustomStringFormat:()=>Pt,ZodDate:()=>dn,ZodDefault:()=>ed,ZodDiscriminatedUnion:()=>Ml,ZodE164:()=>No,ZodEmail:()=>$o,ZodEmoji:()=>_o,ZodEnum:()=>dr,ZodExactOptional:()=>Lo,ZodFile:()=>Xl,ZodFunction:()=>hd,ZodGUID:()=>yo,ZodIBAN:()=>Al,ZodIPv4:()=>Ao,ZodIPv6:()=>To,ZodISODate:()=>st,ZodISODateTime:()=>at,ZodISODuration:()=>ct,ZodISOTime:()=>ut,ZodInstanceOf:()=>$d,ZodIntersection:()=>Vl,ZodJWT:()=>Uo,ZodKSUID:()=>zo,ZodLazy:()=>fd,ZodLiteral:()=>Hl,ZodMAC:()=>Sl,ZodMap:()=>Wl,ZodNaN:()=>ud,ZodNanoID:()=>wo,ZodNever:()=>Cl,ZodNonOptional:()=>Mo,ZodNull:()=>jl,ZodNullable:()=>Ql,ZodNumber:()=>fr,ZodNumberFormat:()=>Ot,ZodObject:()=>fn,ZodOptional:()=>gn,ZodPipe:()=>hn,ZodPrefault:()=>rd,ZodPreprocess:()=>cd,ZodPromise:()=>gd,ZodReadonly:()=>ld,ZodRecord:()=>lr,ZodSet:()=>Kl,ZodString:()=>mr,ZodStringFormat:()=>B,ZodSuccess:()=>od,ZodSymbol:()=>Ol,ZodTemplateLiteral:()=>md,ZodTransform:()=>ql,ZodTuple:()=>Gl,ZodType:()=>Z,ZodULID:()=>Io,ZodURL:()=>ln,ZodUUID:()=>Me,ZodUndefined:()=>Dl,ZodUnion:()=>pn,ZodUnknown:()=>El,ZodVoid:()=>Zl,ZodXID:()=>So,ZodXor:()=>Ll,_ZodString:()=>bo,_default:()=>td,_function:()=>Ig,any:()=>rg,array:()=>mn,base64:()=>Ep,base64url:()=>Cp,bigint:()=>qp,boolean:()=>Pl,catch:()=>sd,check:()=>Sg,cidrv4:()=>Np,cidrv6:()=>Up,codec:()=>_g,creditCard:()=>Rp,cuid:()=>Sp,cuid2:()=>zp,currencyCode:()=>Bp,custom:()=>zg,date:()=>ig,describe:()=>Ag,discriminatedUnion:()=>lg,e164:()=>Zp,email:()=>hp,emoji:()=>kp,enum:()=>Zo,exactOptional:()=>Yl,file:()=>vg,float32:()=>Wp,float64:()=>Kp,function:()=>Ig,guid:()=>vp,hash:()=>Jp,hex:()=>Gp,hostname:()=>Fp,httpUrl:()=>xp,iban:()=>Lp,instanceof:()=>Pg,int:()=>ho,int32:()=>Hp,int64:()=>Yp,intersection:()=>Fl,invertCodec:()=>wg,ipv4:()=>Op,ipv6:()=>jp,json:()=>Dg,jwt:()=>Mp,keyof:()=>og,ksuid:()=>Pp,lazy:()=>pd,literal:()=>hg,looseObject:()=>ug,looseRecord:()=>mg,mac:()=>Dp,map:()=>fg,meta:()=>Tg,nan:()=>yg,nanoid:()=>Ip,nativeEnum:()=>gg,never:()=>Co,nonoptional:()=>id,null:()=>Nl,nullable:()=>cn,nullish:()=>bg,number:()=>Tl,object:()=>ag,optional:()=>At,partialRecord:()=>dg,pipe:()=>vo,prefault:()=>nd,preprocess:()=>jg,promise:()=>kg,readonly:()=>dd,record:()=>Jl,refine:()=>vd,set:()=>pg,strictObject:()=>sg,string:()=>un,stringFormat:()=>Vp,stringbool:()=>Og,success:()=>$g,superRefine:()=>bd,symbol:()=>eg,templateLiteral:()=>xg,transform:()=>Ro,tuple:()=>Bl,uint32:()=>Xp,uint64:()=>Qp,ulid:()=>Ap,undefined:()=>tg,union:()=>hr,unknown:()=>zt,url:()=>wp,uuid:()=>bp,uuidv4:()=>$p,uuidv6:()=>yp,uuidv7:()=>_p,void:()=>ng,xid:()=>Tp,xor:()=>cg});var po={};Je(po,{endsWith:()=>Qt,gt:()=>Re,gte:()=>Se,includes:()=>qt,length:()=>It,lowercase:()=>Ht,lt:()=>Ze,lte:()=>Ie,maxLength:()=>kt,maxSize:()=>rt,mime:()=>tr,minLength:()=>Xe,minSize:()=>Le,multipleOf:()=>tt,negative:()=>io,nonnegative:()=>ao,nonpositive:()=>oo,normalize:()=>rr,overwrite:()=>Ee,positive:()=>no,properties:()=>er,property:()=>so,regex:()=>Kt,size:()=>xt,slugify:()=>ar,startsWith:()=>Yt,toLowerCase:()=>ir,toUpperCase:()=>or,trim:()=>nr,uppercase:()=>Xt});var pp=new WeakSet([Object.prototype,Error.prototype]);function go(e,r,i){Object.defineProperty(e,r,{configurable:!0,enumerable:!1,get(){let o=i(this);return Object.defineProperty(this,r,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,r,{value:o,configurable:!0,writable:!0})}})}var gp=(e,r)=>{ga.init(e,r),e.name="ZodError";let i=Object.getPrototypeOf(e);pp.has(i)||(pp.add(i),go(i,"format",o=>t=>jr(o,t)),go(i,"flatten",o=>t=>Dr(o,t)),go(i,"addIssue",o=>t=>{o.issues.push(t),o.message=JSON.stringify(o.issues,Ut,2)}),go(i,"addIssues",o=>t=>{o.issues.push(...t),o.message=JSON.stringify(o.issues,Ut,2)}),Object.defineProperty(i,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},a_=g("ZodError",gp),ke=g("ZodError",gp,void 0,{Parent:Error});var pl=Rt(ke),gl=Lt(ke),hl=Mt(ke),vl=Vt(ke),bl=Fn(ke),$l=Gn(ke),yl=Bn(ke),_l=Jn(ke),wl=Wn(ke),xl=Kn(ke),kl=Hn(ke),Il=Xn(ke);function u_(){ie.localeError||Y(Ai())}function Tt(){ie.memoizer||Y({memoizer:qr()})}var Z=g("ZodType",(e,r)=>(u_(),C.init(e,r),e.def=r,e.type=r.type,e),{check(...e){let r=this.def;return this.clone($.mergeDefs(r,{checks:[...r.checks??[],...e.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,r){return V(this,e,r)},brand(){return this},register(e,r){return e.add(this,r),this},refine(e,r){return this.check(vd(e,r))},superRefine(e,r){return this.check(bd(e,r))},overwrite(e){return this.check(Ee(e))},optional(){return At(this)},exactOptional(){return Yl(this)},nullable(){return cn(this)},nullish(){return At(cn(this))},nonoptional(e){return id(this,e)},array(){return mn(this)},or(e){return hr([this,e])},and(e){return Fl(this,e)},transform(e){return vo(this,Ro(e))},default(e){return td(this,e)},prefault(e){return nd(this,e)},catch(e){return sd(this,e)},pipe(e){return vo(this,e)},readonly(){return dd(this)},describe(e){let r=this.clone();return se.add(r,{description:e}),r},meta(...e){if(e.length===0)return se.get(this);let r=this.clone();return se.add(r,e[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...r){return r.length===0?e(this):e(this,...r)},get"~standard"(){return $.hide(this,"~standard",{...si(this),jsonSchema:{input:sr(this,"input"),output:sr(this,"output")}})},set"~standard"(e){$.own(this,"~standard",e)},parse:function e(r,i){return pl(this,r,i,{callee:e})},parseAsync:async function e(r,i){return await gl(this,r,i,{callee:e})},safeParse(e,r){return hl(this,e,r)},async safeParseAsync(e,r){return vl(this,e,r)},get spa(){return this?.safeParseAsync},set spa(e){$.own(this,"spa",e)},validate(e,r){return Nr(this,e,r)},validateAsync(e,r){return Ur(this,e,r)},encode:function e(r,i){return bl(this,r,i,{callee:e})},decode:function e(r,i){return $l(this,r,i,{callee:e})},encodeAsync:async function e(r,i){return await yl(this,r,i,{callee:e})},decodeAsync:async function e(r,i){return await _l(this,r,i,{callee:e})},safeEncode(e,r){return wl(this,e,r)},safeDecode(e,r){return xl(this,e,r)},async safeEncodeAsync(e,r){return kl(this,e,r)},async safeDecodeAsync(e,r){return Il(this,e,r)},toJSONSchema(e){return zc(this,{})(e)},get description(){return se.get(this)?.description},get _def(){return this._zod.def}}),bo=g("_ZodString",(e,r)=>{bt.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Pc(e,i,o,t)},$.derived({format:e=>re(e).format??null,minLength:e=>re(e).minimum??null,maxLength:e=>re(e).maximum??null},{regex(...e){return this.check(Kt(...e))},includes(...e){return this.check(qt(...e))},startsWith(...e){return this.check(Yt(...e))},endsWith(...e){return this.check(Qt(...e))},min(...e){return this.check(Xe(...e))},max(...e){return this.check(kt(...e))},length(...e){return this.check(It(...e))},nonempty(...e){return this.check(Xe(1,...e))},lowercase(e){return this.check(Ht(e))},uppercase(e){return this.check(Xt(e))},trim(){return this.check(nr())},normalize(...e){return this.check(rr(...e))},toLowerCase(){return this.check(ir())},toUpperCase(){return this.check(or())},slugify(){return this.check(ar())}})),mr=g("ZodString",(e,r)=>{bt.init(e,r),bo.init(e,r)},{email(e){return this.check(Ei($o,e))},url(e){return this.check(en(ln,e))},jwt(e){return this.check(ro(Uo,e))},emoji(e){return this.check(Vi(_o,e))},guid(e){return this.check(Ci(yo,e))},uuid(e){return this.check(Zi(Me,e))},uuidv4(e){return this.check(Ri(Me,e))},uuidv6(e){return this.check(Li(Me,e))},uuidv7(e){return this.check(Mi(Me,e))},nanoid(e){return this.check(Fi(wo,e))},cuid(e){return this.check(Gi(xo,e))},cuid2(e){return this.check(Bi(ko,e))},ulid(e){return this.check(Ji(Io,e))},base64(e){return this.check(Qi(Do,e))},base64url(e){return this.check(eo(jo,e))},xid(e){return this.check(Wi(So,e))},ksuid(e){return this.check(Ki(zo,e))},ipv4(e){return this.check(Hi(Ao,e))},ipv6(e){return this.check(Xi(To,e))},cidrv4(e){return this.check(qi(Po,e))},cidrv6(e){return this.check(Yi(Oo,e))},e164(e){return this.check(to(No,e))},datetime(e){return this.check(tn(at,e))},date(e){return this.check(rn(st,e))},time(e){return this.check(nn(ut,e))},duration(e){return this.check(on(ct,e))}});function un(e){return Fu(mr,e)}var B=g("ZodStringFormat",(e,r)=>{F.init(e,r),bo.init(e,r)}),at=g("ZodISODateTime",(e,r)=>{Us.init(e,r),B.init(e,r)}),st=g("ZodISODate",(e,r)=>{Es.init(e,r),B.init(e,r)}),ut=g("ZodISOTime",(e,r)=>{Cs.init(e,r),B.init(e,r)}),ct=g("ZodISODuration",(e,r)=>{Zs.init(e,r),B.init(e,r)}),$o=g("ZodEmail",(e,r)=>{ks.init(e,r),B.init(e,r)});function hp(e){return Ei($o,e)}var yo=g("ZodGUID",(e,r)=>{ws.init(e,r),B.init(e,r)});function vp(e){return Ci(yo,e)}var Me=g("ZodUUID",(e,r)=>{xs.init(e,r),B.init(e,r)});function bp(e){return Zi(Me,e)}function $p(e){return Ri(Me,e)}function yp(e){return Li(Me,e)}function _p(e){return Mi(Me,e)}var ln=g("ZodURL",(e,r)=>{zs.init(e,r),B.init(e,r)});function wp(e){return en(ln,e)}function xp(e){return en(ln,{protocol:Er,hostname:Za,...$.normalizeParams(e)})}var _o=g("ZodEmoji",(e,r)=>{As.init(e,r),B.init(e,r)});function kp(e){return Vi(_o,e)}var wo=g("ZodNanoID",(e,r)=>{Ts.init(e,r),B.init(e,r)});function Ip(e){return Fi(wo,e)}var xo=g("ZodCUID",(e,r)=>{Ps.init(e,r),B.init(e,r)});function Sp(e){return Gi(xo,e)}var ko=g("ZodCUID2",(e,r)=>{Os.init(e,r),B.init(e,r)});function zp(e){return Bi(ko,e)}var Io=g("ZodULID",(e,r)=>{Ds.init(e,r),B.init(e,r)});function Ap(e){return Ji(Io,e)}var So=g("ZodXID",(e,r)=>{js.init(e,r),B.init(e,r)});function Tp(e){return Wi(So,e)}var zo=g("ZodKSUID",(e,r)=>{Ns.init(e,r),B.init(e,r)});function Pp(e){return Ki(zo,e)}var Ao=g("ZodIPv4",(e,r)=>{Rs.init(e,r),B.init(e,r)});function Op(e){return Hi(Ao,e)}var Sl=g("ZodMAC",(e,r)=>{Ms.init(e,r),B.init(e,r)});function Dp(e){return Bu(Sl,e)}var To=g("ZodIPv6",(e,r)=>{Ls.init(e,r),B.init(e,r)});function jp(e){return Xi(To,e)}var Po=g("ZodCIDRv4",(e,r)=>{Vs.init(e,r),B.init(e,r)});function Np(e){return qi(Po,e)}var Oo=g("ZodCIDRv6",(e,r)=>{Fs.init(e,r),B.init(e,r)});function Up(e){return Yi(Oo,e)}var Do=g("ZodBase64",(e,r)=>{Gs.init(e,r),B.init(e,r)});function Ep(e){return Qi(Do,e)}var jo=g("ZodBase64URL",(e,r)=>{Bs.init(e,r),B.init(e,r)});function Cp(e){return eo(jo,e)}var No=g("ZodE164",(e,r)=>{Js.init(e,r),B.init(e,r)});function Zp(e){return to(No,e)}var zl=g("ZodCreditCard",(e,r)=>{Ws.init(e,r),B.init(e,r)});function Rp(e){return Ju(zl,e)}var Al=g("ZodIBAN",(e,r)=>{Ks.init(e,r),B.init(e,r)});function Lp(e){return Wu(Al,e)}var Uo=g("ZodJWT",(e,r)=>{Hs.init(e,r),B.init(e,r)});function Mp(e){return ro(Uo,e)}var Pt=g("ZodCustomStringFormat",(e,r)=>{Xs.init(e,r),B.init(e,r)});function Vp(e,r,i={}){return St(Pt,e,r,i)}function Fp(e){return St(Pt,"hostname",Ca,e)}function Gp(e){return St(Pt,"hex",Ya,e)}function Bp(e){return St(Pt,"currency_code",La,e)}function Jp(e,r){let i=r?.enc??"hex",o=`${e}_${i}`,t=Te[o];if(!t)throw new Error(`Unrecognized hash format: ${o}`);return St(Pt,o,t,r)}var fr=g("ZodNumber",(e,r)=>{vi.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Oc(e,i,o,t),e.isFinite=!0},$.derived({minValue:e=>{let{minimum:r,exclusiveMinimum:i}=re(e);return Math.max(r??Number.NEGATIVE_INFINITY,i??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:r,exclusiveMaximum:i}=re(e);return Math.min(r??Number.POSITIVE_INFINITY,i??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:r,multipleOf:i}=re(e);return!!r||!!i?.some(Number.isSafeInteger)},format:e=>re(e).format??null},{gt(e,r){return this.check(Re(e,r))},gte(e,r){return this.check(Se(e,r))},min(e,r){return this.check(Se(e,r))},lt(e,r){return this.check(Ze(e,r))},lte(e,r){return this.check(Ie(e,r))},max(e,r){return this.check(Ie(e,r))},int(e){return this.check(ho(e))},safe(e){return this.check(ho(e))},positive(e){return this.check(Re(0,e))},nonnegative(e){return this.check(Se(0,e))},negative(e){return this.check(Ze(0,e))},nonpositive(e){return this.check(Ie(0,e))},multipleOf(e,r){return this.check(tt(e,r))},step(e,r){return this.check(tt(e,r))},finite(){return this}}));function Tl(e){return Hu(fr,e)}var Ot=g("ZodNumberFormat",(e,r)=>{qs.init(e,r),fr.init(e,r)});function ho(e){return qu(Ot,e)}function Wp(e){return Yu(Ot,e)}function Kp(e){return Qu(Ot,e)}function Hp(e){return ec(Ot,e)}function Xp(e){return tc(Ot,e)}var pr=g("ZodBoolean",(e,r)=>{Br.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Dc(e,i,o,t)});function Pl(e){return rc(pr,e)}var gr=g("ZodBigInt",(e,r)=>{bi.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>jc(e,i,o,t)},$.derived({minValue:e=>re(e).minimum??null,maxValue:e=>re(e).maximum??null,format:e=>re(e).format??null},{gte(e,r){return this.check(Se(e,r))},min(e,r){return this.check(Se(e,r))},gt(e,r){return this.check(Re(e,r))},lt(e,r){return this.check(Ze(e,r))},lte(e,r){return this.check(Ie(e,r))},max(e,r){return this.check(Ie(e,r))},positive(e){return this.check(Re(BigInt(0),e))},negative(e){return this.check(Ze(BigInt(0),e))},nonpositive(e){return this.check(Ie(BigInt(0),e))},nonnegative(e){return this.check(Se(BigInt(0),e))},multipleOf(e,r){return this.check(tt(e,r))}}));function qp(e){return ic(gr,e)}var Eo=g("ZodBigIntFormat",(e,r)=>{Ys.init(e,r),gr.init(e,r)});function Yp(e){return ac(Eo,e)}function Qp(e){return sc(Eo,e)}var Ol=g("ZodSymbol",(e,r)=>{Qs.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Nc(e,i,o,t)});function eg(e){return uc(Ol,e)}var Dl=g("ZodUndefined",(e,r)=>{eu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Ec(e,i,o,t)});function tg(e){return cc(Dl,e)}var jl=g("ZodNull",(e,r)=>{tu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Uc(e,i,o,t)});function Nl(e){return lc(jl,e)}var Ul=g("ZodAny",(e,r)=>{ru.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Rc(e,i,o,t)});function rg(){return dc(Ul)}var El=g("ZodUnknown",(e,r)=>{nu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Lc(e,i,o,t)});function zt(){return mc(El)}var Cl=g("ZodNever",(e,r)=>{iu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Zc(e,i,o,t)});function Co(e){return fc(Cl,e)}var Zl=g("ZodVoid",(e,r)=>{ou.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Cc(e,i,o,t)});function ng(e){return pc(Zl,e)}var dn=g("ZodDate",(e,r)=>{au.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Mc(e,i,o,t),e.min=(i,o)=>e.check(Se(i,o)),e.max=(i,o)=>e.check(Ie(i,o))},$.derived({minDate:e=>{let{minimum:r}=re(e);return r?new Date(r):null},maxDate:e=>{let{maximum:r}=re(e);return r?new Date(r):null}},{}));function ig(e){return gc(dn,e)}var Rl=g("ZodArray",(e,r)=>{Tt(),su.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Qc(e,i,o,t),e.element=r.element},{min(e,r){return this.check(Xe(e,r))},nonempty(e){return this.check(Xe(1,e))},max(e,r){return this.check(kt(e,r))},length(e,r){return this.check(It(e,r))},unwrap(){return this.element}});function mn(e,r){return bc(Rl,e,r)}function og(e){let r=e._zod.def.shape;return Zo(Object.keys(r))}var fn=g("ZodObject",(e,r)=>{Tt(),uu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>el(e,i,o,t),$.installLazyProp(e,"shape",i=>i._zod.def.shape,!1)},{keyof(){return Zo(Object.keys(this._zod.def.shape))},catchall(e){return this.clone($.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone($.mergeDefs(this._zod.def,{catchall:zt()}))},loose(){return this.clone($.mergeDefs(this._zod.def,{catchall:zt()}))},strict(){return this.clone($.mergeDefs(this._zod.def,{catchall:Co()}))},strip(){return this.clone($.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return $.extend(this,e)},safeExtend(e){return $.safeExtend(this,e)},merge(e){return $.merge(this,e)},pick(e){return $.pick(this,e)},omit(e){return $.omit(this,e)},partial(...e){return $.partial(gn,this,e[0])},exactPartial(...e){return $.partial(Lo,this,e[0],"exactPartial")},required(...e){return $.required(Mo,this,e[0])}});function ag(e,r){let i={type:"object",shape:e??{},...$.normalizeParams(r)};return new fn(i)}function sg(e,r){return new fn({type:"object",shape:e,catchall:Co(),...$.normalizeParams(r)})}function ug(e,r){return new fn({type:"object",shape:e,catchall:zt(),...$.normalizeParams(r)})}var pn=g("ZodUnion",(e,r)=>{Jr.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>co(e,i,o,t),e.options=r.options});function hr(e,r){return new pn({type:"union",options:e,...$.normalizeParams(r)})}var Ll=g("ZodXor",(e,r)=>{pn.init(e,r),cu.init(e,r),e._zod.processJSONSchema=(i,o,t)=>co(e,i,o,t),e.options=r.options});function cg(e,r){return new Ll({type:"union",options:e,inclusive:!1,...$.normalizeParams(r)})}var Ml=g("ZodDiscriminatedUnion",(e,r)=>{pn.init(e,r),du.init(e,r)});function lg(e,r,i){return new Ml({type:"union",options:r,discriminator:e,...$.normalizeParams(i)})}var Vl=g("ZodIntersection",(e,r)=>{mu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>tl(e,i,o,t)});function Fl(e,r){return new Vl({type:"intersection",left:e,right:r})}var Gl=g("ZodTuple",(e,r)=>{Tt(),$i.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>rl(e,i,o,t)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(r=>new gn({type:"optional",innerType:r}))})}});function Bl(e,r,i){let o=r instanceof C,t=o?i:r,n=o?r:null;return new Gl({type:"tuple",items:e,rest:n,...$.normalizeParams(t)})}var lr=g("ZodRecord",(e,r)=>{Tt(),fu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>nl(e,i,o,t),e.keyType=r.keyType,e.valueType=r.valueType});function Jl(e,r,i){return!r||!r._zod?new lr({type:"record",keyType:un(),valueType:e,...$.normalizeParams(r)}):new lr({type:"record",keyType:e,valueType:r,...$.normalizeParams(i)})}function dg(e,r,i){return new lr({type:"record",keyType:e,valueType:r,...$.normalizeParams(i),partial:!0})}function mg(e,r,i){return new lr({type:"record",keyType:e,valueType:r,mode:"loose",...$.normalizeParams(i)})}var Wl=g("ZodMap",(e,r)=>{Tt(),pu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>qc(e,i,o,t),e.keyType=r.keyType,e.valueType=r.valueType,e.min=(...i)=>e.check(Le(...i)),e.nonempty=i=>e.check(Le(1,i)),e.max=(...i)=>e.check(rt(...i)),e.size=(...i)=>e.check(xt(...i))});function fg(e,r,i){return new Wl({type:"map",keyType:e,valueType:r,...$.normalizeParams(i)})}var Kl=g("ZodSet",(e,r)=>{Tt(),gu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Yc(e,i,o,t),e.min=(...i)=>e.check(Le(...i)),e.nonempty=i=>e.check(Le(1,i)),e.max=(...i)=>e.check(rt(...i)),e.size=(...i)=>e.check(xt(...i))});function pg(e,r){return new Kl({type:"set",valueType:e,...$.normalizeParams(r)})}var dr=g("ZodEnum",(e,r)=>{hu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(o,t,n)=>Vc(e,o,t,n),e.enum=r.entries,e.options=[...e._zod.values];let i=new Set(Object.keys(r.entries));e.extract=(o,t)=>{let n={};for(let a of o)if(i.has(a))n[a]=r.entries[a];else throw new Error(`Key ${a} not found in enum`);return new dr({...r,checks:[],...$.normalizeParams(t),entries:n})},e.exclude=(o,t)=>{let n={...r.entries};for(let a of o)if(i.has(a))delete n[a];else throw new Error(`Key ${a} not found in enum`);return new dr({...r,checks:[],...$.normalizeParams(t),entries:n})}});function Zo(e,r){let i=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new dr({type:"enum",entries:i,...$.normalizeParams(r)})}function gg(e,r){return new dr({type:"enum",entries:e,...$.normalizeParams(r)})}var Hl=g("ZodLiteral",(e,r)=>{vu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Fc(e,i,o,t),e.values=new Set(r.values),Object.defineProperty(e,"value",{get(){if(r.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});function hg(e,r){return new Hl({type:"literal",values:Array.isArray(e)?e:[e],...$.normalizeParams(r)})}var Xl=g("ZodFile",(e,r)=>{bu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Jc(e,i,o,t),e.min=(i,o)=>e.check(Le(i,o)),e.max=(i,o)=>e.check(rt(i,o)),e.mime=(i,o)=>e.check(tr(Array.isArray(i)?i:[i],o))});function vg(e){return $c(Xl,e)}var ql=g("ZodTransform",(e,r)=>{Tt(),$u.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Xc(e,i,o,t),e._zod.parse=(i,o)=>{if(o.direction==="backward")throw new et(e.constructor.name);i.addIssue=n=>{if(typeof n=="string")i.issues.push($.issue(n,i.value,r));else{let a=n;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),"input"in a||(a.input=i.value),a.inst??(a.inst=e),i.issues.push($.issue(a))}};let t=r.transform(i.value,i);return t instanceof Promise?t.then(n=>(i.value=n,i)):(i.value=t,i)}});function Ro(e){return new ql({type:"transform",transform:e})}var gn=g("ZodOptional",(e,r)=>{yi.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>lo(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function At(e){return new gn({type:"optional",innerType:e})}var Lo=g("ZodExactOptional",(e,r)=>{yu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>lo(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function Yl(e){return new Lo({type:"optional",innerType:e})}var Ql=g("ZodNullable",(e,r)=>{_u.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>il(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function cn(e){return new Ql({type:"nullable",innerType:e})}function bg(e){return At(cn(e))}var ed=g("ZodDefault",(e,r)=>{wu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>sl(e,i,o,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function td(e,r){return new ed({type:"default",innerType:e,get defaultValue(){return typeof r=="function"?r():$.shallowClone(r)}})}var rd=g("ZodPrefault",(e,r)=>{xu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>ul(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function nd(e,r){return new rd({type:"prefault",innerType:e,get defaultValue(){return typeof r=="function"?r():$.shallowClone(r)}})}var Mo=g("ZodNonOptional",(e,r)=>{ku.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>ol(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function id(e,r){return new Mo({type:"nonoptional",innerType:e,...$.normalizeParams(r)})}var od=g("ZodSuccess",(e,r)=>{Iu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Wc(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function $g(e){return new od({type:"success",innerType:e})}var ad=g("ZodCatch",(e,r)=>{Su.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>cl(e,i,o,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function sd(e,r){return new ad({type:"catch",innerType:e,catchValue:typeof r=="function"?r:$.constantCatch(r)})}var ud=g("ZodNaN",(e,r)=>{zu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Gc(e,i,o,t)});function yg(e){return vc(ud,e)}var hn=g("ZodPipe",(e,r)=>{_i.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>ll(e,i,o,t),e.in=r.in,e.out=r.out});function vo(e,r){return new hn({type:"pipe",in:e,out:r})}var vn=g("ZodCodec",(e,r)=>{hn.init(e,r),Wr.init(e,r)});function _g(e,r,i){return new vn({type:"pipe",in:e,out:r,transform:i.decode,reverseTransform:i.encode})}function wg(e){let r=e._zod.def;return new vn({type:"pipe",in:r.out,out:r.in,transform:r.reverseTransform,reverseTransform:r.transform})}var cd=g("ZodPreprocess",(e,r)=>{hn.init(e,r),Au.init(e,r)}),ld=g("ZodReadonly",(e,r)=>{Tu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>dl(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function dd(e){return new ld({type:"readonly",innerType:e})}var md=g("ZodTemplateLiteral",(e,r)=>{Pu.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Bc(e,i,o,t)});function xg(e,r){return new md({type:"template_literal",parts:e,...$.normalizeParams(r)})}var fd=g("ZodLazy",(e,r)=>{Kr.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>fl(e,i,o,t),e.unwrap=()=>e._zod.def.getter()});function pd(e){return new fd({type:"lazy",getter:e})}var gd=g("ZodPromise",(e,r)=>{Du.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>ml(e,i,o,t),e.unwrap=()=>e._zod.def.innerType});function kg(e){return new gd({type:"promise",innerType:e})}var hd=g("ZodFunction",(e,r)=>{Ou.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Hc(e,i,o,t)});function Ig(e){return new hd({type:"function",input:Array.isArray(e?.input)?Bl(e?.input):e?.input??mn(zt()),output:e?.output??zt()})}var bn=g("ZodCustom",(e,r)=>{ju.init(e,r),Z.init(e,r),e._zod.processJSONSchema=(i,o,t)=>Kc(e,i,o,t)});function Sg(e){let r=new K({check:"custom"});return r._zod.check=e,r}function zg(e,r){return yc(bn,e??(()=>!0),r)}function vd(e,r={}){return _c(bn,e,r)}function bd(e,r){return wc(e,r)}var Ag=xc,Tg=kc,$d=g("ZodInstanceOf",(e,r)=>{bn.init(e,r)},{properties(e,r){return this.check(er(e,r))}});function Pg(e,r={}){let i=new $d({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...$.normalizeParams(r)});return i._zod.bag.Class=e,i._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:i,path:[...i._zod.def.path??[]]})},i}var Og=(...e)=>Ic({Codec:vn,Boolean:pr,String:mr},...e);function Dg(e){let r=pd(()=>hr([un(e),Tl(),Pl(),Nl(),mn(r),Jl(un(),r)]));return r}function jg(e,r){return new cd({type:"pipe",in:Ro(e),out:r})}var c_={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function l_(e){Y({customError:e})}function d_(){return Y().customError}var yd;yd||(yd={});var $n={};Je($n,{ZodISODate:()=>st,ZodISODateTime:()=>at,ZodISODuration:()=>ct,ZodISOTime:()=>ut,date:()=>f_,datetime:()=>m_,duration:()=>g_,time:()=>p_});function m_(e){return tn(at,e)}function f_(e){return rn(st,e)}function p_(e){return nn(ut,e)}function g_(e){return on(ct,e)}var O={...vr,...po,iso:$n},h_=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function v_(e,r){let i=e.$schema;return i==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":i==="http://json-schema.org/draft-07/schema#"?"draft-7":i==="http://json-schema.org/draft-04/schema#"?"draft-4":r??"draft-2020-12"}function Ng(e,r){return e.map((i,o)=>o<r?i:i.optional())}function b_(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function $_(e,r){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let i=e.slice(1).split("/").filter(Boolean);if(i.length===0)return r.rootSchema;let o=r.version==="draft-2020-12"?"$defs":"definitions";if(i[0]===o){let t=i[1]===void 0?void 0:b_(i[1]);if(!t||!r.defs[t])throw new Error(`Reference not found: ${e}`);return r.defs[t]}throw new Error(`Reference not found: ${e}`)}function y_(e,r){return O.transform(o=>o).check(o=>{let t=o.value;if(typeof t!="object"||t===null||Array.isArray(t))return;let n=Object.getOwnPropertyNames(t);if(r.minProperties!==void 0&&n.length<r.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:r.minProperties,inclusive:!0,message:`Too small: expected object to have >=${r.minProperties} properties`,input:t,inst:e,continue:!0}),r.maxProperties!==void 0&&n.length>r.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:r.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${r.maxProperties} properties`,input:t,inst:e,continue:!0}),r.keySchema)for(let a of n){let s=r.keySchema.safeParse(a);s.success||o.issues.push({code:"invalid_key",origin:"record",issues:s.error.issues,input:a,path:[a],continue:!0})}}).pipe(e)}function _d(e,r){if(e===null)return"z";let i=typeof e;if(i!=="object"){if(i==="number"&&Number.isNaN(e))return null;let o=String(e);return`${i[0]}${o.length}:${o}`}if(r.has(e))return null;r.add(e);try{if(Array.isArray(e)){let n=[];for(let a of e){let s=_d(a,r);if(s===null)return null;n.push(s)}return`a${n.length}:[${n.join(",")}]`}let o=Object.keys(e).sort(),t=[];for(let n of o){let a=_d(e[n],r);if(a===null)return null;t.push(`${n.length}:${n}=${a}`)}return`o${t.length}:{${t.join(",")}}`}finally{r.delete(e)}}var __=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),w_=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function yn(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(yn):typeof e.$ref=="string"?!0:Object.entries(e).some(([r,i])=>__.has(r)?yn(i):!w_.has(r)||typeof i!="object"||i===null?!1:Object.values(i).some(yn))}function Ug(e){return e===1?"element":"elements"}function x_(e,r){return O.transform(o=>o).check(o=>{let t=o.value;if(Array.isArray(t)){if(r.uniqueItems===!0){let n=new Map;for(let a=0;a<t.length;a++){let s=_d(t[a],new Set);if(s===null)continue;let u=n.get(s);if(u===void 0){n.set(s,a);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${a} duplicates the one at index ${u}`,input:t,path:[a],continue:!0})}}if(r.containsSchema){let n=r.minContains??1,a=r.maxContains!==void 0?r.maxContains+1:Number.POSITIVE_INFINITY,s=0;for(let u of t)if(r.containsSchema.safeParse(u).success&&++s>=a)break;s<n&&o.issues.push({code:"custom",message:`Array must contain at least ${n} matching ${Ug(n)}; found ${s}`,input:t,continue:!0}),r.maxContains!==void 0&&s>r.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${r.maxContains} matching ${Ug(r.maxContains)}`,input:t,continue:!0})}}}).pipe(e)}function Eg(e,r){if(e!==!1)return e===void 0||e===!0?O.any():ve(e,r)}var k_=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function Cg(e,r){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return O.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let t=e.$ref;if(r.refs.has(t))return r.refs.get(t);if(r.processing.has(t))return O.lazy(()=>{if(!r.refs.has(t))throw new Error(`Circular reference not resolved: ${t}`);return r.refs.get(t)});r.processing.add(t);let n=$_(t,r),a=ve(n,r);return r.refs.set(t,a),r.processing.delete(t),a}if(e.enum!==void 0){let t=e.enum;if(r.version==="openapi-3.0"&&e.nullable===!0&&t.length===1&&t[0]===null)return O.null();if(t.length===0)return O.never();if(t.length===1)return O.literal(t[0]);if(t.every(a=>typeof a=="string"))return O.enum(t);let n=t.map(a=>O.literal(a));return n.length<2?n[0]:O.union([n[0],n[1],...n.slice(2)])}if(e.const!==void 0)return O.literal(e.const);let i=e.type;if(Array.isArray(i)){let t=i.map(n=>{let a={...e,type:n};return Cg(a,r)});return t.length===0?O.never():t.length===1?t[0]:O.union(t)}if(!i)return O.any();let o;switch(i){case"string":{let t=O.string();if(e.format){let n=e.format;n==="email"?t=t.check(O.email()):n==="uri"||n==="uri-reference"?t=t.check(O.url()):n==="uuid"||n==="guid"?t=t.check(O.uuid()):n==="date-time"?t=t.check(O.iso.datetime({offset:!0})):n==="date"?t=t.check(O.iso.date()):n==="time"?t=t.check(O.regex(k_)):n==="duration"?t=t.check(O.iso.duration()):n==="hostname"?t=t.check(O.hostname()):n==="ipv4"?t=t.check(O.ipv4()):n==="ipv6"?t=t.check(O.ipv6()):n==="mac"?t=t.check(O.mac()):n==="cidr"?t=t.check(O.cidrv4()):n==="cidr-v6"?t=t.check(O.cidrv6()):n==="base64"?t=t.check(O.base64()):n==="base64url"?t=t.check(O.base64url()):n==="e164"?t=t.check(O.e164()):n==="credit_card"?t=t.check(O.creditCard()):n==="iban"?t=t.check(O.iban()):n==="jwt"?t=t.check(O.jwt()):n==="emoji"?t=t.check(O.emoji()):n==="nanoid"?t=t.check(O.nanoid()):n==="cuid"?t=t.check(O.cuid()):n==="cuid2"?t=t.check(O.cuid2()):n==="ulid"?t=t.check(O.ulid()):n==="xid"?t=t.check(O.xid()):n==="ksuid"&&(t=t.check(O.ksuid()))}typeof e.minLength=="number"&&(t=t.min(e.minLength)),typeof e.maxLength=="number"&&(t=t.max(e.maxLength)),e.pattern&&(t=t.regex(new RegExp(e.pattern))),o=t;break}case"number":case"integer":{let t=i==="integer"?O.number().int():O.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(t=t.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(t=t.max(e.maximum)),typeof e.exclusiveMinimum=="number"?t=t.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(t=t.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?t=t.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(t=t.lt(e.maximum)),typeof e.multipleOf=="number"&&(t=t.multipleOf(e.multipleOf)),o=t;break}case"boolean":{o=O.boolean();break}case"null":{o=O.null();break}case"object":{let t={},n=e.properties||{},a=new Set(e.required||[]),s=typeof e.additionalProperties=="object"?ve(e.additionalProperties,r):void 0;for(let[m,p]of Object.entries(n)){let f=ve(p,r);ae(t,m,a.has(m)?f:f.optional())}if(e.patternProperties){let m=e.patternProperties,p=Object.keys(m),f=[];for(let _ of p){let k=ve(m[_],r),P=O.string().regex(new RegExp(_));f.push(O.looseRecord(P,k))}let h=[];if(Object.keys(t).length>0&&h.push(O.object(t).passthrough()),h.push(...f),h.length===0)o=O.object({}).passthrough();else if(h.length===1)o=h[0];else{let _=O.intersection(h[0],h[1]);for(let k=2;k<h.length;k++)_=O.intersection(_,h[k]);o=_}if(e.additionalProperties===!1){let _=Object.keys(t),k=p.map(T=>new RegExp(T)),P=o;o=o.check(T=>{if(!ze(T.value))return;let U=[];for(let I of Object.keys(T.value))_.includes(I)||k.some(A=>A.test(I))||U.push(I);U.length&&T.issues.push({code:"unrecognized_keys",keys:U,input:T.value,inst:P})})}}else{let m=O.object(t);e.additionalProperties===!1?o=m.strict():s?o=m.catchall(s):o=m.passthrough()}let u=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties=="number"?e.minProperties:void 0,d=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(u||c!==void 0||d!==void 0){let m;if(u){let p=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;m=ve(p,r)}o=y_(o,{keySchema:m,minProperties:c,maxProperties:d})}break}case"array":{let t=e.prefixItems,n=e.items;if(t&&Array.isArray(t)){let a=typeof e.minItems=="number"?e.minItems:0,s=t.map(m=>ve(m,r)),u=Ng(s,a),c=Array.isArray(n)?void 0:Eg(n,r),d=O.tuple(u);o=c?d.rest(c):d,typeof e.minItems=="number"&&(o=o.check(O.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(O.maxLength(e.maxItems)))}else if(Array.isArray(n)){let a=typeof e.minItems=="number"?e.minItems:0,s=n.map(m=>ve(m,r)),u=Ng(s,a),c=Eg(e.additionalItems,r),d=O.tuple(u);o=c?d.rest(c):d,typeof e.minItems=="number"&&(o=o.check(O.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(O.maxLength(e.maxItems)))}else if(n!==void 0){let a=ve(n,r),s=O.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),o=s}else o=O.array(O.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=x_(o,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?ve(e.contains,r):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${i}`)}return o}function ve(e,r){if(typeof e=="boolean")return e?O.any():O.never();let i=Cg(e,r),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let s=e.anyOf.map(c=>ve(c,r)),u=O.union(s);i=o?O.intersection(i,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map(c=>ve(c,r)),u=O.xor(s);i=o?O.intersection(i,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)i=o?i:O.any();else{let s=o?i:ve(e.allOf[0],r),u=o?0:1;for(let c=u;c<e.allOf.length;c++)s=O.intersection(s,ve(e.allOf[c],r));i=s}e.nullable===!0&&r.version==="openapi-3.0"&&(i=O.nullable(i)),e.readOnly===!0&&(i=O.readonly(i)),e.default!==void 0&&(i=i.default(e.default));let t={},n=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of n)s in e&&(t[s]=e[s]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let s of a)s in e&&(t[s]=e[s]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!yn(e.propertyNames)&&(t.propertyNames=e.propertyNames);for(let s of["minProperties","maxProperties"])e[s]!==void 0&&(t[s]=e[s])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!yn(e.contains)&&(t.contains=e.contains);for(let s of["uniqueItems","minContains","maxContains"])e[s]!==void 0&&(t[s]=e[s])}for(let s of Object.keys(e))h_.has(s)||ae(t,s,e[s]);return Object.keys(t).length>0&&r.registry.add(i,t),e.description&&(i=i.describe(e.description)),i}function Zg(e,r){if(typeof e=="boolean")return e?O.any():O.never();let i;try{i=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=v_(i,r?.defaultTarget),t=i.$defs||i.definitions||{},n={version:o,defs:t,refs:new Map,processing:new Set,rootSchema:i,registry:r?.registry??se};return ve(i,n)}var Rg=Symbol("z.visit/resolving");function _n(e,r){let i=typeof r=="function"?r:(a,s)=>{let u=r[a._zod.def.type];return u?u(a,s):a},o=new Map;function t(a){let s=o.get(a);if(s===Rg)return new Kr({type:"lazy",getter:()=>o.get(a)});if(s!==void 0)return s;o.set(a,Rg);let u=n(a),c=i(u,u!==a);return o.set(a,c),c}function n(a){let s=a._zod.def,u=s.type;switch(u){case"object":{let c=s.shape,d=Object.keys(c),m=!1,p={};for(let h of d){let _=t(c[h]);_!==c[h]&&(m=!0),p[h]=_}let f=s.catchall;return s.catchall&&(f=t(s.catchall),f!==s.catchall&&(m=!0)),m?V(a,{...s,shape:p,catchall:f}):a}case"array":{let c=t(s.element);return c===s.element?a:V(a,{...s,element:c})}case"tuple":{let c=s.items,d=!1,m=[];for(let f of c){let h=t(f);h!==f&&(d=!0),m.push(h)}let p=s.rest;return s.rest&&(p=t(s.rest),p!==s.rest&&(d=!0)),d?V(a,{...s,items:m,rest:p}):a}case"record":case"map":{let c=t(s.keyType),d=t(s.valueType);return c===s.keyType&&d===s.valueType?a:V(a,{...s,keyType:c,valueType:d})}case"set":{let c=t(s.valueType);return c===s.valueType?a:V(a,{...s,valueType:c})}case"union":{let c=s.options,d=!1,m=[];for(let p of c){let f=t(p);f!==p&&(d=!0),m.push(f)}return d?V(a,{...s,options:m}):a}case"intersection":{let c=t(s.left),d=t(s.right);return c===s.left&&d===s.right?a:V(a,{...s,left:c,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let c=t(s.innerType);return c===s.innerType?a:V(a,{...s,innerType:c})}case"pipe":{let c=t(s.in),d=t(s.out);return c===s.in&&d===s.out?a:V(a,{...s,in:c,out:d})}case"function":{let c=t(s.input),d=t(s.output);return c===s.input&&d===s.output?a:V(a,{...s,input:c,output:d})}case"lazy":{let c=s.getter,{_cachedInner:d,...m}=s;return V(a,{...m,getter:()=>t(c())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return a;default:return a}}return t(e)}function Lg(e){return _n(e,{object:r=>r.partial(),union:r=>{let i=r._zod.def;return i.discriminator===void 0?r:hr(i.options)}})}function I_(e,r){if(!r?.length)return e;let i=e._zod.def;return V(e,Ne(i,{checks:[...i.checks??[],...r]}),{parent:!0})}function Mg(e){return I_(e.out,e.checks)}function S_(e){return e.in._zod.traits.has("$ZodTransform")?Mg(e):e.in}function Vg(e){return _n(e,{pipe:r=>S_(r._zod.def),default:(r,i)=>i?At(r._zod.def.innerType):r,catch:(r,i)=>i?r._zod.def.innerType:r})}function Fg(e){return _n(e,{pipe:r=>Mg(r._zod.def),prefault:(r,i)=>i?r._zod.def.innerType:r})}var wd={};Je(wd,{bigint:()=>P_,boolean:()=>T_,date:()=>O_,number:()=>A_,string:()=>z_});function z_(e){return Gu(mr,e)}function A_(e){return Xu(fr,e)}function T_(e){return nc(pr,e)}function P_(e){return oc(gr,e)}function O_(e){return hc(dn,e)}var be=l.strictObject({tabId:l.number().int().nonnegative().optional()}),xd=l.strictObject({stable:l.boolean(),stabilityWaitMs:l.number().finite().nonnegative(),lastMutationAgoMs:l.number().finite().nonnegative(),fontsReady:l.boolean(),pendingImages:l.number().int().nonnegative().max(1e6),timeoutReached:l.boolean()}),Gg=be.extend({maxEntries:l.number().int().min(1).max(100).default(50),reset:l.boolean().default(!0)}),D_=be.extend({selector:l.string().min(1).max(2048),durationMs:l.number().int().min(500).max(3e4).default(3e3)}),mS=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url(),highlighted:l.boolean()}),xn=l.strictObject({level:l.enum(["warn","error"]),message:l.string().max(512),timestamp:l.number().finite().nonnegative()}),kd=l.strictObject({url:l.url().max(1024),method:l.string().max(16),resourceType:l.string().max(32),status:l.number().int().min(100).max(599).optional(),error:l.string().max(128).optional(),timestamp:l.number().finite().nonnegative()}),fS=l.strictObject({tabId:l.number().int().nonnegative(),entries:l.array(xn).max(100),dropped:l.number().int().nonnegative(),forwardingDropped:l.number().int().nonnegative()}),pS=l.strictObject({tabId:l.number().int().nonnegative(),entries:l.array(kd).max(100),dropped:l.number().int().nonnegative()}),Id=l.strictObject({url:l.url(),title:l.string().max(160),readyState:l.enum(["loading","interactive","complete"]),viewport:l.strictObject({width:l.number().int().positive(),height:l.number().int().positive(),devicePixelRatio:l.number().finite().positive()}),scroll:l.strictObject({x:l.number().finite(),y:l.number().finite()}),stabilityPending:l.boolean(),consoleInstrumentationActive:l.boolean(),consoleForwardingDropped:l.number().int().nonnegative()}),gS=Id.extend({tabId:l.number().int().nonnegative(),targetState:l.enum(["authorized","reauthorization_required","none"]),runtimeErrorCount:l.number().int().nonnegative(),consoleEntryCount:l.number().int().nonnegative(),networkFailureCount:l.number().int().nonnegative()}),kn=l.enum(["click","type","press_key","hover","scroll","select","focus"]),wn=be.extend({selector:l.string().min(1).max(2048)}),j_=wn.extend({text:l.string().max(4096),clear:l.boolean().default(!0)}),N_=be.extend({selector:l.string().min(1).max(2048).optional(),key:l.string().max(12).refine(e=>e.length===1||["Enter","Escape","Tab","Backspace","Delete","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"].includes(e)),shift:l.boolean().default(!1)}),U_=be.extend({selector:l.string().min(1).max(2048).optional(),x:l.number().finite().min(-1e6).max(1e6).default(0),y:l.number().finite().min(-1e6).max(1e6).default(0),mode:l.enum(["by","to"]).default("by")}),E_=wn.extend({value:l.string().max(4096)}),hS=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url(),action:kn,inputSource:l.literal("dom"),completed:l.literal(!0),scroll:l.strictObject({x:l.number().finite(),y:l.number().finite()}).optional()}),Ve=be.extend({url:l.url().optional(),format:l.enum(["png","jpeg"]).default("jpeg"),quality:l.number().int().min(0).max(100).default(85),waitForStable:l.boolean().default(!1),includeOverlay:l.boolean().optional(),stableWindowMs:l.number().int().min(20).max(1e3).default(100),maxWaitMs:l.number().int().min(50).max(5e3).default(2e3)}),C_=be.extend({bypassCache:l.boolean().default(!1)}),Z_=Ve.extend({x:l.number().finite().nonnegative(),y:l.number().finite().nonnegative(),width:l.number().finite().positive().max(32768),height:l.number().finite().positive().max(32768)}),R_=Ve.extend({selector:l.string().min(1).max(2048),padding:l.number().finite().min(0).max(1e3).default(0)}),L_=Ve.extend({maxPixels:l.number().int().min(1).max(32e6).default(16e6),maxSegments:l.number().int().min(1).max(64).default(32),timeoutMs:l.number().int().min(500).max(8e3).default(7e3)}),M_=be.extend({url:l.url()}),vS=l.strictObject({baseline:l.uuid().optional().describe("A prior PNG imageReference from this session. Omit and use referenceImagePath instead to diff against an external design reference."),referenceImagePath:l.string().min(1).max(4096).optional().describe("Path (relative to the MCP server's working directory, or absolute) to a local PNG design reference to diff the live capture against. Exactly one of baseline/referenceImagePath is required."),current:l.uuid().optional(),tabId:l.number().int().nonnegative().optional().describe("Only used with referenceImagePath when current is omitted, to select which tab to capture. Ignored otherwise (baseline's own tab is used)."),threshold:l.number().finite().min(0).max(1).default(.1),checkpoint:l.string().min(1).max(200).regex(/^[A-Za-z0-9_-]+$/).optional().describe("Visual Convergence best-so-far tracking id (e.g. 'hero-desktop'). Only meaningful together with referenceImagePath: persists the best-known result locally and objectively reports isBest/regressed on every call, independent of the agent's own assessment.")}),Bg=l.enum(["mobile-small","mobile","tablet","desktop","desktop-wide"]),V_=be.extend({profile:Bg.optional(),width:l.number().int().min(200).max(8192).optional(),height:l.number().int().min(200).max(8192).optional(),dedicatedPreview:l.boolean().default(!0),close:l.boolean().optional().describe("Close the current dedicated preview window instead of creating or resizing one. Width/height/profile are ignored when true. Idempotent: has no effect if no preview is open.")}),bS=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url(),windowId:l.number().int().nonnegative(),width:l.number().int().positive(),height:l.number().int().positive(),devicePixelRatio:l.number().finite().positive(),zoom:l.number().finite().positive(),outerWidth:l.number().int().positive(),outerHeight:l.number().int().positive(),dedicatedPreview:l.boolean(),sourceTabId:l.number().int().nonnegative().optional(),requested:l.strictObject({width:l.number().int().positive(),height:l.number().int().positive(),profile:Bg.optional()}).optional(),exact:l.boolean().optional(),attempts:l.number().int().min(0).max(3).optional(),requiresTargetSelection:l.boolean().optional(),sourceWindowUnchanged:l.boolean().optional(),previewClosed:l.boolean().optional().describe("Present when close:true was requested. True if a dedicated preview window was actually open and closed; false if there was none to close.")}),Jg=be.extend({selector:l.string().min(1).max(2048).optional(),depth:l.number().int().min(0).max(8).default(3),maxNodes:l.number().int().min(1).max(300).default(100),textLength:l.number().int().min(0).max(300).default(160),maxBytes:l.number().int().min(2048).max(65536).default(32768)}),F_=Jg.extend({selector:l.string().min(1).max(2048)}),G_=be.extend({maxRegions:l.number().int().min(1).max(100).default(50),reset:l.boolean().default(!0)}),B_=l.enum(["highlight","clear_highlight","capture_region","capture_element","capture_full_page","get_dom","get_element","get_changed_regions","get_viewport","set_viewport",...kn.options,"get_console","get_network_failures","get_page_status"]),Wg=l.strictObject({x:l.number().finite(),y:l.number().finite(),width:l.number().finite().nonnegative(),height:l.number().finite().nonnegative()}),J_=l.strictObject({index:l.number().int().nonnegative(),parent:l.number().int().nonnegative().optional(),depth:l.number().int().min(0).max(8),tag:l.string().max(80),id:l.string().max(160).optional(),classes:l.array(l.string().max(80)).max(6).optional(),role:l.string().max(80).optional(),text:l.string().max(300).optional(),ariaLabel:l.string().max(300).optional(),name:l.string().max(160).optional(),type:l.string().max(80).optional(),href:l.string().max(1024).optional(),bounds:Wg,visible:l.boolean(),redacted:l.boolean().optional(),disabled:l.boolean().optional(),checked:l.boolean().optional(),selected:l.boolean().optional()}),$S=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url(),nodes:l.array(J_).max(300),truncated:l.boolean(),payloadBytes:l.number().int().max(65536)}),yS=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url(),regions:l.array(Wg.extend({reason:l.enum(["mutation","resize","attribute","text"]),selector:l.string().max(240).optional()})).max(100),trackingStarted:l.boolean(),dropped:l.number().int().nonnegative(),coverage:l.literal("potential-dom-and-layout-changes")}),Sd=l.strictObject({type:l.enum(["error","unhandledrejection","console-error"]),message:l.string().max(4096),source:l.string().max(2048).optional(),line:l.number().int().nonnegative().optional(),column:l.number().int().nonnegative().optional(),timestamp:l.number().nonnegative()}),Kg=l.strictObject({extensionVersion:l.string().max(80).optional(),extensionId:l.string().min(1).max(256).optional(),capabilities:l.array(B_).max(20).optional(),selectedTab:l.number().int().nonnegative().nullable(),url:l.string().max(2048).nullable(),targetState:l.enum(["none","authorized","reauthorization_required"]).optional(),browser:l.strictObject({name:l.enum(["firefox","chrome"]),version:l.string().max(80)}).optional(),backgroundCapture:l.strictObject({enabled:l.boolean(),permissionGranted:l.boolean()}).optional()}),Hg=l.discriminatedUnion("type",[l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("highlight"),payload:D_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("clear_highlight"),payload:be}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_console"),payload:Gg}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_network_failures"),payload:Gg}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_page_status"),payload:be}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("click"),payload:wn}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("type"),payload:j_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("press_key"),payload:N_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("hover"),payload:wn}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("scroll"),payload:U_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("select"),payload:E_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("focus"),payload:wn}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_viewport"),payload:be}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("set_viewport"),payload:V_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_dom"),payload:Jg}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_element"),payload:F_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_changed_regions"),payload:G_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("capture_region"),payload:Z_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("capture_element"),payload:R_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("capture_full_page"),payload:L_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("capture"),payload:Ve}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("reload"),payload:C_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("navigate"),payload:M_}),l.strictObject({id:l.uuid(),version:l.literal(1),type:l.literal("get_errors"),payload:be})]),_S=l.discriminatedUnion("ok",[l.strictObject({id:l.uuid(),version:l.literal(1),ok:l.literal(!0),result:l.unknown()}),l.strictObject({id:l.uuid(),version:l.literal(1),ok:l.literal(!1),error:l.strictObject({code:l.string().max(80),message:l.string().max(4096),stability:xd.optional()})})]),wS=l.strictObject({version:l.literal(1),type:l.literal("hello"),token:l.string().regex(/^[a-f0-9]{64}$/),state:Kg}),xS=l.strictObject({version:l.literal(1),type:l.literal("state"),state:Kg}),Xg=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url(),width:l.number().int().positive(),height:l.number().int().positive(),format:l.enum(["png","jpeg"]),captureMs:l.number().nonnegative(),processingMs:l.number().nonnegative().optional(),totalMs:l.number().nonnegative().optional(),segments:l.number().int().positive().max(64).optional(),scrollRestored:l.boolean().optional(),stabilityWaitMs:l.number().nonnegative().optional(),extensionTotalMs:l.number().nonnegative().optional(),renderAppearsStable:l.boolean().optional(),stable:l.boolean().optional(),lastMutationAgoMs:l.number().finite().nonnegative().optional(),fontsReady:l.boolean().optional(),pendingImages:l.number().int().nonnegative().optional(),timeoutReached:l.boolean().optional(),dataUrl:l.string().max(16*1024*1024)}),kS=l.strictObject({tabId:l.number().int().nonnegative(),url:l.url()}),IS=l.strictObject({tabId:l.number().int().nonnegative(),errors:l.array(Sd).max(200)}),x=class extends Error{constructor(i,o,t){super(o);this.code=i;this.stability=t}};function Fe(e,r=[]){let i=new URL(e);if(!["http:","https:"].includes(i.protocol)||i.username||i.password||!["localhost","127.0.0.1","[::1]"].includes(i.hostname)&&!r.includes(i.origin))throw new x("GS_URL_NOT_ALLOWED","Use a localhost URL or explicitly authorize this origin in both server and extension settings.")}var W_="background-capture-offscreen.html",K_=6e3;function eh(e,r){if(e!==r)throw new x("GS_PREVIEW_BACKGROUND_INELIGIBLE","This responsive preview is not eligible for Background Capture while inactive (a Chrome platform limitation, not a GazeSight restriction). Activate the preview window to capture it, or capture the authorized primary target instead.")}async function H_(){return(await chrome.runtime.getContexts({contextTypes:[chrome.runtime.ContextType.OFFSCREEN_DOCUMENT]})).length>0}async function qg(){await H_()&&await chrome.offscreen.closeDocument().catch(()=>{})}var Yg=Promise.resolve();function zd(e,r,i){return new Promise((o,t)=>{let n=setTimeout(()=>t(new x("GS_TIMEOUT",i)),r);e.then(a=>{clearTimeout(n),o(a)},a=>{clearTimeout(n),t(a)})})}async function Qg(e,r,i){let o;try{o=await chrome.tabCapture.getMediaStreamId({targetTabId:e})}catch(t){throw new x("GS_CAPTURE_FAILED",`Background capture stream unavailable: ${String(t?.message??t)}`)}await qg(),await chrome.offscreen.createDocument({url:chrome.runtime.getURL(W_),reasons:[chrome.offscreen.Reason.USER_MEDIA],justification:"Decode a tabCapture MediaStream frame into a still image for GazeSight's Background Capture."});try{let t=await zd(chrome.runtime.sendMessage({type:"gazesight-background-capture-offscreen",streamId:o,format:r,quality:i}),K_,"Background capture timed out waiting for the offscreen document.");if(!t?.ok||typeof t.dataUrl!="string")throw new x("GS_CAPTURE_FAILED",typeof t?.error=="string"?t.error:"Background capture failed.");return t.dataUrl}finally{await qg()}}function th(e,r,i){let o=Yg.then(()=>Qg(e,r,i),()=>Qg(e,r,i));return Yg=o.catch(()=>{}),o}function Ad(e){let r=typeof e=="object"&&e!==null&&"message"in e?e.message:e;return String(r).slice(0,512)}function rh(e,r){return e instanceof x?e:new x(r==="capture"?"GS_CAPTURE_FAILED":"GS_OPERATION_FAILED",`Firefox ${r}: ${Ad(e)}`)}var Vo=class{constructor(r,i,o,t,n,a){this.port=r;this.token=i;this.state=o;this.handler=t;this.status=n;this.keepaliveMs=a}socket;timer;keepalive;delay=250;stopped=!1;paired=!1;start(){this.stopped=!1,this.connect()}stop(){this.stopped=!0,clearTimeout(this.timer),clearInterval(this.keepalive),this.socket?.close(),this.status(!1)}async publish(){this.paired&&this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify({version:1,type:"state",state:await this.state()}))}async connect(){if(this.stopped)return;let r=new WebSocket(`ws://127.0.0.1:${this.port}`);this.socket=r,this.paired=!1;let i=setTimeout(()=>r.close(),4e3);r.onopen=()=>{this.state().then(t=>{r.readyState===WebSocket.OPEN&&r.send(JSON.stringify({version:1,type:"hello",token:this.token,state:t}))})};let o=Promise.resolve();r.onmessage=t=>{o=o.then(async()=>{try{if(typeof t.data!="string"||t.data.length>32768)throw new Error("Invalid message");let n=JSON.parse(t.data);if(!this.paired){if(JSON.stringify(n)!==JSON.stringify({version:1,type:"paired"}))throw new Error("Pairing failed");this.paired=!0,clearTimeout(i),this.delay=250,this.status(!0),this.keepaliveMs&&(this.keepalive=setInterval(()=>{this.publish().catch(()=>{})},this.keepaliveMs));return}let a=Hg.parse(n),s;try{s={id:a.id,version:1,ok:!0,result:await this.handler(a)}}catch(u){let c=rh(u,a.type);s={id:a.id,version:1,ok:!1,error:{code:c.code,message:c.message,...c.stability?{stability:c.stability}:{}}}}r.readyState===WebSocket.OPEN&&r.send(JSON.stringify(s))}catch{r.close(1008,"Invalid message")}})},r.onerror=()=>r.close(),r.onclose=()=>{clearTimeout(i),clearInterval(this.keepalive),this.paired=!1,this.stopped||this.status(!1),this.stopped||(this.timer=setTimeout(()=>void this.connect(),this.delay),this.delay=Math.min(this.delay*2,5e3))}}};var Fo=class{selectedTab=null;selectedOrigin=null;state="none";generation=0;choose(r,i){this.selectedTab=r,this.selectedOrigin=i?new URL(i).origin:null,this.state="authorized",this.generation++}reauthorize(r){r===this.selectedTab&&(this.state="reauthorization_required",this.generation++)}refresh(r){r===this.selectedTab&&this.generation++}resume(r){r===this.selectedTab&&this.state==="reauthorization_required"&&(this.state="authorized")}assertAuthorized(r){if(r!==this.selectedTab)throw new x("GS_TARGET_MISMATCH","The requested tab is not the target explicitly selected in GazeSight.");if(this.state!=="authorized")throw new x("GS_REAUTHORIZE_TARGET","Click the GazeSight extension icon or use the configured selection shortcut (default Ctrl+Shift+Y) in the target tab to grant Firefox permission for this document.")}assertAuthorizedUrl(r,i){if(this.assertAuthorized(r),this.selectedOrigin!==null&&new URL(i).origin!==this.selectedOrigin)throw new x("GS_REAUTHORIZE_TARGET","The target moved to a different origin. Select it again before GazeSight accesses it.")}isSelectedOrigin(r){try{return this.selectedOrigin!==null&&new URL(r).origin===this.selectedOrigin}catch{return!1}}remove(r){this.selectedTab===r&&(this.selectedTab=null,this.selectedOrigin=null,this.state="none",this.generation++)}resolve(r){let i=r??this.selectedTab;if(i===null)throw new x("GS_NO_TARGET_TAB","Open your preview page in Firefox and click the GazeSight icon.");return i}};async function nh(e){try{return await e()}catch(r){throw X_(r)}}function X_(e){let r=Ad(e),i=/activeTab|<all_urls>|permission/i.test(r);return new x(i?"GS_PERMISSION_DENIED":"GS_CAPTURE_FAILED",`Firefox captureVisibleTab: ${r}${i?" Click the GazeSight icon or use the configured selection shortcut (default Ctrl+Shift+Y) in the selected tab to grant activeTab again.":""}`)}var In=class{constructor(r,i,o){this.nativeCapture=r;this.contentOperation=i;this.services=o}capture(r){return this.nativeCapture(r)}executeContentOperation(r){return this.contentOperation(r)}getTarget(r){return browser.tabs.get(r)}async reload(r,i){await browser.tabs.reload(r,{bypassCache:i})}async navigate(r,i){await browser.tabs.update(r,{url:i})}getViewport(r){return this.services.getViewport(r)}resizePreview(...r){return this.services.resizePreview(...r)}getDiagnostics(r){return this.services.getDiagnostics(r)}};var ih=l.discriminatedUnion("op",[l.strictObject({op:l.literal("metrics")}),l.strictObject({op:l.literal("begin")}),l.strictObject({op:l.literal("restore"),lease:l.uuid()}),l.strictObject({op:l.literal("scroll"),lease:l.uuid(),x:l.number().finite().nonnegative(),y:l.number().finite().nonnegative()}),l.strictObject({op:l.literal("element"),lease:l.uuid(),selector:l.string().min(1).max(2048),padding:l.number().min(0).max(1e3)})]);async function Td(e,r,i,o,t,n,a=()=>performance.now()){e.assertAuthorized(r);let s=a()+5e3;e.reauthorize(r);let u=e.generation,c=()=>{if(a()>=s)throw new x("GS_TIMEOUT","Navigation preparation exceeded its bounded deadline; no navigation was issued.");if(e.selectedTab!==r||e.generation!==u||e.state!=="reauthorization_required")throw new x("GS_TARGET_CHANGED","The target changed before navigation; no navigation was issued.")};await o(),c();let d=await t();if(c(),d!==i)throw new x("GS_TARGET_CHANGED","The document changed before navigation; no navigation was issued.");await n()}function Pd(e,r,i){if(![e.x,e.y,e.width,e.height,r.width,r.height,i.width,i.height].every(Number.isFinite)||r.width<=0||r.height<=0||e.width<=0||e.height<=0||e.x<0||e.y<0||e.x+e.width>r.width+.5||e.y+e.height>r.height+.5)throw new x("GS_REGION_OUT_OF_VIEWPORT","The complete region must fit inside the current CSS viewport.");let o=i.width/r.width,t=i.height/r.height,n=Math.floor(e.x*o),a=Math.floor(e.y*t);return{x:n,y:a,width:Math.min(i.width,Math.ceil((e.x+e.width)*o))-n,height:Math.min(i.height,Math.ceil((e.y+e.height)*t))-a}}function oh(e,r,i,o,t,n=0){if(![e,r,i,o].every(s=>Number.isFinite(s)&&s>0)||e>32768||r>32768)throw new x("GS_CAPTURE_LIMIT","Page dimensions exceed the capture limits.");if(i=e>i?Math.max(1,i-n*2):i,o=r>o?Math.max(1,o-n*2):o,Math.ceil(e/i)*Math.ceil(r/o)>t)throw new x("GS_CAPTURE_LIMIT","Page requires too many capture segments.");let a=[];for(let s=0;s<r;s+=o)for(let u=0;u<e;u+=i)a.push({x:u,y:s,width:Math.min(i,e-u),height:Math.min(o,r-s)});return a}var br=l.object({width:l.number().finite().positive(),height:l.number().finite().positive(),pageWidth:l.number().finite().positive(),pageHeight:l.number().finite().positive(),x:l.number().finite(),y:l.number().finite(),devicePixelRatio:l.number().finite().positive()}),ah=br.extend({lease:l.uuid()}),sh=br.extend({rect:l.object({x:l.number(),y:l.number(),width:l.number().positive(),height:l.number().positive()})});async function uh(e,r,i){let o=performance.now(),t=r.payload,n=o+(r.type==="capture_full_page"?r.payload.timeoutMs:7e3);async function a(I){let A=n-performance.now();if(A<=0)throw new x("GS_TIMEOUT","Capture suite deadline reached.");let S;try{return await Promise.race([I(),new Promise((j,M)=>{S=setTimeout(()=>M(new x("GS_TIMEOUT","Capture suite deadline reached.")),A)})])}finally{clearTimeout(S)}}let s=I=>a(()=>e.executeContentOperation(I)),u=Ve.parse({tabId:t.tabId,url:t.url,format:t.format,quality:t.quality,waitForStable:t.waitForStable,stableWindowMs:t.stableWindowMs,maxWaitMs:t.maxWaitMs,includeOverlay:t.includeOverlay}),c=0,d=0,m=0,p=0,f,h=!0,_,k,P;async function T(){let I=Xg.parse(await a(()=>e.capture(u)));if(c+=I.captureMs,p+=I.stabilityWaitMs??0,m++,_??=I,!new RegExp(`^data:image/${I.format};base64,[A-Za-z0-9+/]+={0,2}$`).test(I.dataUrl))throw new x("GS_CAPTURE_FAILED","Native capture returned an invalid image data URL.");let A=performance.now(),S=await a(async()=>{let j=await createImageBitmap(await(await fetch(I.dataUrl)).blob());if(performance.now()>n)throw j.close(),new x("GS_TIMEOUT","Image decoding exceeded the capture deadline.");return j});return d+=performance.now()-A,S}function U(I,A,S=16e6){if(!Number.isFinite(I*A)||I<1||A<1||I>32768||A>32768||I*A>S)throw new x("GS_CAPTURE_LIMIT","Output image exceeds the pixel/memory limit.");return k=i.createSurface(I,A),k}try{if(r.type==="capture_full_page"){let S=ah.parse(await s({op:"begin"}));f=S.lease;let j=oh(S.pageWidth,S.pageHeight,S.width,S.height,r.payload.maxSegments,1),M,H=0,X=0;for(let D of j){let J=br.parse(await s({op:"scroll",lease:f,x:Math.max(0,D.x-1),y:Math.max(0,D.y-1)}));if(J.pageWidth!==S.pageWidth||J.pageHeight!==S.pageHeight||J.width!==S.width||J.height!==S.height)throw new x("GS_PAGE_CHANGED","Page dimensions changed during capture; infinite or dynamic pages are not stitched.");let W=await T();try{let mt=performance.now();if(M||(H=W.width/J.width,X=W.height/J.height,M=U(Math.ceil(S.pageWidth*H),Math.ceil(S.pageHeight*X),r.payload.maxPixels)),Math.abs(W.width/J.width-H)>.001||Math.abs(W.height/J.height-X)>.001)throw new x("GS_TARGET_CHANGED","Capture scale changed during stitching.");let me=Pd({x:D.x-J.x,y:D.y-J.y,width:D.width,height:D.height},J,W),Dt=Math.floor(D.x*H),Md=Math.floor(D.y*X),Uh=Math.ceil((D.x+D.width)*H)-Dt,Eh=Math.ceil((D.y+D.height)*X)-Md;M.drawImage(W,me.x,me.y,me.width,me.height,Dt,Md,Uh,Eh),d+=performance.now()-mt}finally{W.close()}let je=br.parse(await s({op:"metrics"}));if(je.pageWidth!==S.pageWidth||je.pageHeight!==S.pageHeight||Math.abs(je.x-J.x)>.5||Math.abs(je.y-J.y)>.5)throw new x("GS_PAGE_CHANGED","Page size or scroll changed during native capture.")}}else{let S,j;if(r.type==="capture_element"){f=ah.parse(await s({op:"begin"})).lease;let D=sh.parse(await s({op:"element",lease:f,selector:r.payload.selector,padding:r.payload.padding}));S=D,j=D.rect}else S=br.parse(await s({op:"metrics"})),j=r.payload;let M=await T();try{let X=performance.now(),D=Pd(j,S,M);U(D.width,D.height).drawImage(M,D.x,D.y,D.width,D.height,0,0,D.width,D.height),d+=performance.now()-X}finally{M.close()}let H=br.parse(await s({op:"metrics"}));if(S.width!==H.width||S.height!==H.height||S.x!==H.x||S.y!==H.y)throw new x("GS_TARGET_CHANGED","Viewport or scroll changed during capture.");if(r.type==="capture_element"){let X=sh.parse(await s({op:"element",lease:f,selector:r.payload.selector,padding:r.payload.padding}));if(JSON.stringify(X.rect)!==JSON.stringify(j))throw new x("GS_PAGE_CHANGED","Element geometry changed during capture.")}}if(!k||!_)throw new x("GS_CAPTURE_FAILED","No capture segments produced.");let I=performance.now(),A=await k.encode(t.format,t.quality);if(d+=performance.now()-I,A.length>16*1024*1024)throw new x("GS_CAPTURE_LIMIT","Encoded image exceeds the bridge payload limit.");if(performance.now()>n)throw new x("GS_TIMEOUT","Local image processing exceeded the capture deadline.");return P={..._,width:k.width,height:k.height,dataUrl:A,segments:m,captureMs:c,processingMs:d,stabilityWaitMs:p,extensionTotalMs:performance.now()-o,totalMs:performance.now()-o,scrollRestored:h},P}finally{if(f){let I;try{if(h=l.object({scrollRestored:l.boolean()}).parse(await Promise.race([e.executeContentOperation({op:"restore",lease:f}),new Promise((S,j)=>{I=setTimeout(()=>j(new x("GS_SCROLL_RESTORE_FAILED","Scroll restoration timed out; content watchdog remains active.")),500)})])).scrollRestored,!h)throw new x("GS_SCROLL_RESTORE_FAILED","The original scroll position could not be restored.")}finally{clearTimeout(I)}}k&&k.dispose(),P&&Object.assign(P,{scrollRestored:h,totalMs:performance.now()-o,extensionTotalMs:performance.now()-o})}}function q_(e){return new Promise((r,i)=>{let o=new FileReader;o.onload=()=>r(o.result),o.onerror=()=>i(o.error),o.readAsDataURL(e)})}var Go=class{createSurface(r,i){let o=new OffscreenCanvas(r,i),t=o.getContext("2d");if(!t)throw new x("GS_CAPTURE_FAILED","Unable to allocate local image processing surface.");return{width:r,height:i,drawImage:(n,a,s,u,c,d,m,p,f)=>t.drawImage(n,a,s,u,c,d,m,p,f),encode:async(n,a)=>{let s=await o.convertToBlob({type:`image/${n}`,quality:a/100});return q_(s)},dispose:()=>{o.width=0,o.height=0}}}};var Y_="fullpage-stitch-offscreen.html",Q_=8e3;async function ew(){return(await chrome.runtime.getContexts({contextTypes:[chrome.runtime.ContextType.OFFSCREEN_DOCUMENT]})).length>0}async function ch(){await ew()&&await chrome.offscreen.closeDocument().catch(()=>{})}var lh=Promise.resolve();async function dh(e,r,i,o,t){await ch(),await chrome.offscreen.createDocument({url:chrome.runtime.getURL(Y_),reasons:[chrome.offscreen.Reason.BLOBS],justification:"Decode and draw already-cropped capture tiles onto a DOM canvas for GazeSight's Chrome full-page composition."});try{let n=await zd(chrome.runtime.sendMessage({type:"gazesight-fullpage-stitch-offscreen",tiles:e,width:r,height:i,format:o,quality:t}),Q_,"Offscreen full-page stitch timed out.");if(!n?.ok||typeof n.dataUrl!="string")throw new x("GS_CAPTURE_FAILED",typeof n?.error=="string"?n.error:"Offscreen full-page stitch failed.");return n.dataUrl}finally{await ch()}}function mh(e,r,i,o,t){let n=lh.then(()=>dh(e,r,i,o,t),()=>dh(e,r,i,o,t));return lh=n.catch(()=>{}),n}function tw(e){let r=new Uint8Array(e),i="",o=32768;for(let t=0;t<r.length;t+=o)i+=String.fromCharCode(...r.subarray(t,t+o));return btoa(i)}function rw(e,r,i,o,t){let n=new OffscreenCanvas(o,t),a=n.getContext("2d");if(!a)throw new x("GS_CAPTURE_FAILED","Unable to allocate local image processing surface.");return a.drawImage(e,r,i,o,t,0,0,o,t),n.convertToBlob({type:"image/png"}).then(s=>s.arrayBuffer()).then(s=>`data:image/png;base64,${tw(s)}`)}var Bo=class{createSurface(r,i){let o=[];return{width:r,height:i,drawImage:(t,n,a,s,u,c,d,m,p)=>{o.push(rw(t,n,a,s,u).then(f=>({dataUrl:f,sw:s,sh:u,dx:c,dy:d,dw:m,dh:p})))},encode:async(t,n)=>{let a=await Promise.all(o);return mh(a.map(s=>({dataUrl:s.dataUrl,sx:0,sy:0,sw:s.sw,sh:s.sh,dx:s.dx,dy:s.dy,dw:s.dw,dh:s.dh})),r,i,t,n)},dispose:()=>{}}}};var nw={"mobile-small":{width:320,height:568},mobile:{width:390,height:844},tablet:{width:768,height:1024},desktop:{width:1440,height:900},"desktop-wide":{width:1920,height:1080}},pz=l.strictObject({op:l.literal("measure")}),fh=l.strictObject({width:l.number().int().positive(),height:l.number().int().positive(),devicePixelRatio:l.number().finite().positive()});function ph(e){let r=e.profile?nw[e.profile]:void 0,i=e.width??r?.width,o=e.height??r?.height;if(!i||!o)throw new x("GS_INVALID_VIEWPORT","Provide a profile or both width and height in CSS pixels.");return{width:i,height:o,...e.profile?{profile:e.profile}:{}}}function gh(e,r,i,o){if(!i.width||!i.height||!Number.isFinite(o)||o<=0)throw new x("GS_VIEWPORT_FAILED","Window dimensions or zoom are unavailable.");return{width:Math.max(200,Math.min(8192,Math.round(i.width+(e.width-r.width)*o))),height:Math.max(200,Math.min(8192,Math.round(i.height+(e.height-r.height)*o)))}}function hh(e,r){return["width","height","left","top","state"].every(i=>e[i]===r[i])}function Jo(e,r){if(e.tabs?.length!==1||e.tabs[0].id!==r)throw new x("GS_PREVIEW_IN_USE","The preview now contains other tabs; GazeSight will not resize it.")}function iw(e){return{incognito:!!e.incognito}}var Wo=class{preview;async get(r){let i=Od(r),o=await browser.tabs.sendMessage(r.id,{type:"gazesight-viewport-content",operation:{op:"measure"}},{frameId:0});if(!o?.ok)throw new x("GS_VIEWPORT_FAILED","Viewport measurement unavailable; select the target again.");let t=fh.parse(o.value),n=await browser.windows.get(i),a=await browser.tabs.getZoom(r.id);return{tabId:r.id,url:r.url,windowId:i,...t,zoom:a,outerWidth:n.width,outerHeight:n.height,dedicatedPreview:!!(this.preview&&this.preview.tabId===r.id),...this.preview&&this.preview.tabId===r.id?{sourceTabId:this.preview.sourceTabId}:{}}}async set(r,i,o){let t=ph(i),n=Od(r),a=i.dedicatedPreview&&this.preview&&this.preview.tabId===r.id?this.preview.sourceWindowId:n,s=await browser.windows.get(a).catch(()=>{}),u=r,c=!1,d=!1;if(i.dedicatedPreview){if(this.preview){let k=await browser.windows.get(this.preview.windowId,{populate:!0}).catch(()=>{});if(!k)this.preview=void 0;else{if(Jo(k,this.preview.tabId),r.id!==this.preview.tabId&&(r.id!==this.preview.sourceTabId||r.url!==this.preview.url||!!r.incognito!==this.preview.incognito))throw new x("GS_PREVIEW_IN_USE","An existing preview belongs to another source. Close that preview before creating a different one.");if(u=await browser.tabs.get(this.preview.tabId),t.width<500&&r.id===this.preview.tabId&&k.type!=="popup"){await o();let P={...this.preview},T=await browser.windows.create({tabId:P.tabId,type:"popup",focused:!0,width:Math.min(8192,t.width+32),height:Math.min(8192,t.height+120)});if(T.id===void 0)throw new x("GS_VIEWPORT_FAILED","Chrome did not return the compact preview window.");this.preview={...P,windowId:T.id},u=await browser.tabs.get(P.tabId),c=!0}}}if(!this.preview){let k=iw(r);await o();let P=await browser.windows.create({url:r.url,type:t.width<500?"popup":"normal",focused:!0,width:Math.min(8192,t.width+32),height:Math.min(8192,t.height+120),incognito:k.incognito}),T=P.tabs?.[0];if(P.id===void 0||T?.id===void 0)throw new x("GS_VIEWPORT_FAILED","Chrome did not return a preview tab.");this.preview={windowId:P.id,tabId:T.id,sourceTabId:r.id,sourceWindowId:n,incognito:k.incognito,url:r.url},u=T,d=!0}}let m,p,f;for(let k=0;k<20;k++){await o();let P=await browser.tabs.get(u.id);if(P.status==="complete"&&P.url!==r.url)throw new x("GS_TARGET_CHANGED","The preview navigated away from its source URL.");if(u=P,u.status==="complete"){if(d){try{await ow(u.id)}catch(T){p=T}d=!1}try{m=await this.get(u);break}catch(T){f=T}}await new Promise(T=>setTimeout(T,100))}if(!m){let k=p??f;throw new x("GS_VIEWPORT_FAILED","Preview created but its measured viewport is unavailable."+(k?` ${p?"Injection":"Measurement"} error: ${String(k?.message??k)}`:""))}let h=0;for(;h<3&&(m.width!==t.width||m.height!==t.height);h++){await o();let k=Od(u),P=await browser.windows.get(k,{populate:!0});i.dedicatedPreview&&Jo(P,u.id);let T=gh(t,m,P,m.zoom);await browser.windows.update(k,{state:"normal"}),await o(),await browser.windows.update(k,T),await new Promise(I=>setTimeout(I,150)),await o();let U=await browser.tabs.get(u.id);if(U.url!==r.url)throw new x("GS_TARGET_CHANGED","The preview navigated during resize.");m=await this.get(U)}let _=await browser.windows.get(a).catch(()=>{});return{...m,movedToCompact:c,requested:t,exact:m.width===t.width&&m.height===t.height,attempts:h,...s&&_?{sourceWindowUnchanged:hh(s,_)}:{}}}removeWindow(r){this.preview?.windowId===r&&(this.preview=void 0)}previewSourceTabId(r){return this.preview&&this.preview.tabId===r?this.preview.sourceTabId:void 0}currentPreviewTabId(){return this.preview?.tabId}clear(){this.preview=void 0}snapshot(){return this.preview?{...this.preview}:void 0}async hydrate(r,i){if(i.selectedTab!==r.sourceTabId||i.state!=="authorized")return!1;try{let o=await browser.windows.get(r.windowId,{populate:!0});return Jo(o,r.tabId),(await browser.tabs.get(r.tabId)).url!==r.url?!1:(this.preview={...r},!0)}catch{return!1}}};async function ow(e){await browser.scripting.executeScript({target:{tabId:e},files:["content.js"]})}function Od(e){if(e.id===void 0||e.windowId===void 0||!e.url)throw new x("GS_VIEWPORT_FAILED","Chrome tab identity or window is unavailable.");return e.windowId}var aw="gazesight-select-target";async function vh(e,r){if(e!==aw)return;let i=r??(await browser.tabs.query({active:!0,lastFocusedWindow:!0}))[0];if(!(i?.id===void 0||i.active!==!0))return i}function Ge(e,r){return e.slice(0,4096).replace(/https?:\/\/[^\s"'<>]+/gi,i=>{try{let o=new URL(i);return o.origin+o.pathname}catch{return"[redacted URL]"}}).replace(/(?:bearer\s+)[\w.+/=-]+/gi,"[redacted]").replace(/\beyJ[\w-]+\.[\w-]+(?:\.[\w-]+)?/g,"[redacted]").replace(/\b[a-zA-Z0-9_+/-]{24,}={0,2}\b/g,"[redacted]").replace(/((?:password|passwd|token|secret|credential|api[-_]?key|authorization)["']?\s*[:=]\s*["']?)[^\s,;"']+/gi,"$1[redacted]").replace(/\s+/g," ").trim().slice(0,r)}function Sn(e,r){try{let i=new URL(e,r);return["http:","https:"].includes(i.protocol)?(i.origin+i.pathname.split("/").map(o=>Ge(o,200)).join("/")).slice(0,1024):void 0}catch{return}}var Iz=l.strictObject({op:l.enum(["status","stop"])}),Sz=l.discriminatedUnion("type",[l.strictObject({namespace:l.literal("gazesight-console"),type:l.literal("entry"),entry:xn}),l.strictObject({namespace:l.literal("gazesight-console"),type:l.enum(["ready","stopped"])})]),zn=class{entries=[];dropped=0;get count(){return this.entries.length}push(r){this.entries.length===100&&(this.entries.shift(),this.dropped++),this.entries.push(r)}clear(){this.entries=[],this.dropped=0}read(r,i){let o=Math.max(1,Math.min(100,Math.floor(r))),t={entries:this.entries.slice(-o),dropped:this.dropped+Math.max(0,this.entries.length-o)};return i&&this.clear(),t}};function bh(e){if(!e.error&&!(e.statusCode!==void 0&&e.statusCode>=400&&e.statusCode<=599))return;let r=Sn(e.url,e.url);if(r)return kd.parse({url:r,method:Ge(e.method,16),resourceType:Ge(e.type,32),timestamp:e.timeStamp,...e.statusCode!==void 0?{status:e.statusCode}:{},...e.error?{error:/^NS_ERROR_[A-Z_]{1,96}$/.test(e.error)?e.error:Ge(e.error,128)}:{}})}var $h=l.strictObject({type:l.literal("gazesight-ui"),action:l.enum(["status","select","disconnect","fast","stable","diagnostics","background-enable","background-denied","background-disable","continuous-enable","continuous-denied","continuous-disable"])});function yh(e,r,i,o){return e?r==="none"?"WAIT":r==="reauthorization_required"?"AUTH":i?"WAIT":o?"ERR":"ON":"OFF"}function Dd(e,r,i,o=!1){if(e.id!==r||!o&&e.tab||!e.url)return!1;try{let t=new URL(e.url),n=new URL(i);return t.origin===n.origin&&t.pathname===n.pathname}catch{return!1}}var _h="0.5.3";async function wh(e){if(e.tabId!==e.targetTabId)throw new x("GS_TARGET_MISMATCH","The requested tab is not the target explicitly selected in GazeSight.");let r=e.backgroundMode==="enabled"&&e.permissionGranted,i=await e.currentTarget();if(i.id!==e.tabId||i.url!==e.url||e.currentGeneration()!==e.generation)throw new x("GS_TARGET_CHANGED","The target changed before capture.");if(!r&&!i.active)throw new x("GS_CAPTURE_FAILED","Bring the authorized target tab to the front.");let o=await(r?e.background():e.foreground()),t=await e.currentTarget();if(t.id!==e.tabId||t.url!==e.url||e.currentGeneration()!==e.generation)throw new x("GS_TARGET_CHANGED","The target changed during capture.");if(!r&&!t.active)throw new x("GS_CAPTURE_FAILED","The active tab changed during capture.");return o}function An(e){return String(e).padStart(2,"0")}function sw(e=new Date){return`GazeSight/gazesight-${e.getFullYear()}-${An(e.getMonth()+1)}-${An(e.getDate())}_${An(e.getHours())}-${An(e.getMinutes())}-${An(e.getSeconds())}.png`}var Ko=class{busy=!1;async run(r){if(this.busy)throw new x("GS_CAPTURE_BUSY","A manual screenshot is already in progress.");this.busy=!0;try{if(!await r.permissionGranted())throw new x("GS_PERMISSION_DENIED","Download permission required.");let i=await r.capture();if(i.format!=="png"||!/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(i.dataUrl))throw new x("GS_CAPTURE_FAILED","Capture failed to produce a PNG image.");let o=sw(r.now),t;try{if(t=await r.download({url:i.dataUrl,filename:o,saveAs:!1,conflictAction:"uniquify"}),!await r.waitForCompletion(t))throw new Error("interrupted")}catch{throw new x("GS_DOWNLOAD_FAILED","Download failed.")}return{filename:o,downloadId:t}}finally{this.busy=!1}}};function jd(e,r,i,o){if(!i.enabled||!i.hostPermissionGranted)return!1;let t=o(e);return t!==void 0&&t===r.selectedTab&&r.state==="authorized"}function xh(e,r,i,o,t){return jd(e,i,o,t)&&i.isSelectedOrigin(r)}function Nd(e,r){if(r===null)return!1;try{return new URL(e).origin===r}catch{return!1}}var b=new Fo,dt=new Wo,uw=new Go,cw=new Bo,Oe=new Map,yr=new zn,_r=new zn,Q,Be=[],De=!1,$r=null,Pn=!1,Ed=!1,On=!1,$e="disabled",le=!1,oe=!1,ue=!1,lw=new Ko;function Sh(e){return jd(e,b,{enabled:ue,hostPermissionGranted:le},r=>dt.previewSourceTabId(r))}function dw(e,r){return xh(e,r,b,{enabled:ue,hostPermissionGranted:le},i=>dt.previewSourceTabId(i))}function ne(e){Sh(e)||b.assertAuthorized(e)}function zh(e,r){dw(e,r)||b.assertAuthorizedUrl(e,r)}function mw(e){return e===b.selectedTab?b.state==="authorized":Sh(e)}async function Pe(){await browser.storage.session.set({sessionTargetTabId:b.selectedTab,sessionTargetOrigin:b.selectedOrigin,sessionTargetState:b.state,sessionPreview:dt.snapshot()??null})}async function Ho(){await browser.storage.session.remove(["sessionTargetTabId","sessionTargetOrigin","sessionTargetState","sessionPreview"])}async function fw(e){let r=Date.now()+15e3;for(;Date.now()<r;){let[i]=await browser.downloads.search({id:e});if(i?.state==="complete")return!0;if(i?.state==="interrupted")return!1;await new Promise(o=>setTimeout(o,100))}return!1}var Ah,Th;async function pw(e,r){for(let i=1;;i++)try{return await browser.tabs.captureVisibleTab(e,r)}catch(o){let t=o instanceof Error?o.message:String(o);if(i>=4||!/MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND/.test(t))throw o;await new Promise(n=>setTimeout(n,550))}}var Ph={getViewport:e=>dt.get(e),resizePreview:(...e)=>dt.set(...e),getDiagnostics:vw},ee=new In(async e=>{let r=b.resolve(e.tabId);ne(r);let i=b.generation,o=await ee.getTarget(r);if(zh(r,o.url??""),i!==b.generation)throw new x("GS_TARGET_CHANGED","The target changed before native capture.");Fe(o.url??"",Be);let t=o.windowId;if(t===void 0)throw new x("GS_CAPTURE_FAILED","The authorized target window is unavailable.");let n=()=>nh(()=>pw(t,{format:e.format,quality:e.quality}));return wh({tabId:r,targetTabId:r,generation:i,currentGeneration:()=>b.generation,url:o.url??"",currentTarget:()=>ee.getTarget(r),backgroundMode:$e,permissionGranted:oe,foreground:n,background:()=>o.active?n():(eh(r,b.selectedTab),th(r,e.format??"jpeg",e.quality??85))})},async e=>{let r=b.resolve();ne(r);let i=await browser.tabs.sendMessage(r,{type:"gazesight-capture-content",operation:ih.parse(e)},{frameId:0});if(!i?.ok)throw new x("GS_CAPTURE_FAILED","Fixed content operation failed.");return i.value},Ph);function gw(){return/Chrom(?:e|ium)\/([\d.]+)/.exec(globalThis.navigator?.userAgent??"")?.[1]??"unknown"}async function hw(){let e={extensionVersion:_h,extensionId:browser.runtime.id,capabilities:["highlight","clear_highlight","capture_region","capture_element","capture_full_page","get_dom","get_element","get_changed_regions","get_viewport","set_viewport",...kn.options,"get_console","get_network_failures","get_page_status"],targetState:b.state,browser:{name:"chrome",version:gw()},backgroundCapture:{enabled:$e==="enabled",permissionGranted:oe}};if(b.selectedTab===null)return{selectedTab:null,url:null,...e};try{let r=await ee.getTarget(b.selectedTab);return{selectedTab:b.selectedTab,url:r.url??null,...e}}catch{return b.remove(b.selectedTab),await Ho(),{selectedTab:null,url:null,...e,targetState:b.state}}}var Ud=Promise.resolve(),Tn;function de(){let e={text:yh(De,b.state,Ed,On),color:De&&b.state==="authorized"?"#15734b":"#8c5321",title:b.state==="reauthorization_required"?"GazeSight: click in the target tab to reauthorize this document":"GazeSight: use this tab"};return Ud=Ud.catch(()=>{}).then(async()=>{try{let r=await Promise.allSettled([Tn?.text!==e.text?Promise.resolve().then(()=>browser.action.setBadgeText({text:e.text})):void 0,Tn?.color!==e.color?Promise.resolve().then(()=>browser.action.setBadgeBackgroundColor({color:e.color})):void 0,Tn?.title!==e.title?Promise.resolve().then(()=>browser.action.setTitle({title:e.title})):void 0]);for(let i of r)if(i.status==="rejected")throw i.reason;Tn=e}catch(r){throw Tn=void 0,r}}),Ud}function kh(){return browser.scripting}async function Nn(e){await kh().executeScript({target:{tabId:e},files:["content.js"]}).catch(()=>{}),De&&b.selectedTab===e&&b.state==="authorized"&&(await kh().executeScript({target:{tabId:e,frameIds:[0]},files:["diagnostics-page.js"],world:"MAIN",injectImmediately:!0}).catch(()=>{}),!De||b.selectedTab!==e||b.state!=="authorized"?await Xo(e):await lt(e))}async function vw(e){let r=await browser.tabs.sendMessage(e,{type:"gazesight-diagnostics-content",operation:{op:"status"}},{frameId:0});if(!r?.ok)throw new x("GS_DIAGNOSTICS_UNAVAILABLE","Select the target again to initialize diagnostics.");return Id.parse(r.value)}async function Xo(e){await Dn(e,{op:"clear"}).catch(()=>{}),await wr(e,{op:"set",state:"none"}),$r===e&&($r=null),await browser.tabs.sendMessage(e,{type:"gazesight-diagnostics-content",operation:{op:"stop"}},{frameId:0}).catch(()=>{})}async function Dn(e,r){let i=await browser.tabs.sendMessage(e,{type:"gazesight-overlay-content",operation:r},{frameId:0});if(!i?.ok)throw new x(i?.code??"GS_HIGHLIGHT_UNAVAILABLE","The overlay operation was refused or unavailable.");return i.value===!0}function bw(e){return e?$e==="enabled"&&oe?"background":"authorized":"none"}async function wr(e,r){await browser.tabs.sendMessage(e,{type:"gazesight-target-indicator-content",operation:r}).catch(()=>{})}async function lt(e){await wr(e,{op:"set",state:bw(b.state==="authorized"&&b.selectedTab===e)})}function jn(){yr.clear(),_r.clear()}function Oh(e){if(!(!De||b.state!=="authorized"||e.tabId!==b.selectedTab||!b.isSelectedOrigin(e.url)))try{Fe(e.url,Be);let r=bh(e);r&&_r.push(r)}catch{}}browser.webRequest.onCompleted.addListener(Oh,{urls:["http://*/*","https://*/*"]});browser.webRequest.onErrorOccurred.addListener(Oh,{urls:["http://*/*","https://*/*"]});async function $w(e){let r=e.payload.tabId;if(r===void 0&&e.type.startsWith("capture")&&"url"in e.payload&&e.payload.url){let o=e.payload.url,t=(await browser.tabs.query({})).filter(n=>n.url===o);if(t.length!==1)throw new x("GS_TAB_NOT_FOUND","Provide a tabId or a URL matching exactly one open Chrome tab.");r=t[0].id}r=b.resolve(r),ne(r);let i;try{i=await ee.getTarget(r)}catch{throw new x("GS_TAB_NOT_FOUND","The Chrome tab was closed. Select a new target.")}return Fe(i.url??"",Be),zh(r,i.url??""),i}async function Dh(e){let r=await $w(e),i=r.id;if(e.type==="highlight"||e.type==="clear_highlight"){if(ne(i),Pn)throw new x("GS_CAPTURE_BUSY","Wait for the current capture before changing its overlay.");let o=b.generation,t=await Dn(i,e.type==="highlight"?{op:"show",options:e.payload}:{op:"clear"}),n=await ee.getTarget(i);if(o!==b.generation||n.url!==r.url)throw await Dn(i,{op:"clear"}).catch(()=>{}),new x("GS_TARGET_CHANGED","The target changed while highlighting.");return ne(i),$r=t?i:null,{tabId:i,url:n.url,highlighted:t}}if(e.type==="get_console"||e.type==="get_network_failures"||e.type==="get_page_status"){ne(i);let o=b.generation,t=e.type==="get_network_failures"?void 0:await ee.getDiagnostics(i),n=await ee.getTarget(i);if(o!==b.generation||n.url!==r.url)throw new x("GS_TARGET_CHANGED","The target document changed during diagnostics.");return ne(i),e.type==="get_console"?{tabId:i,...yr.read(e.payload.maxEntries,e.payload.reset),forwardingDropped:t.consoleForwardingDropped}:e.type==="get_network_failures"?{tabId:i,..._r.read(e.payload.maxEntries,e.payload.reset)}:{...t,tabId:i,targetState:b.state,runtimeErrorCount:Oe.get(i)?.length??0,consoleEntryCount:yr.count,networkFailureCount:_r.count}}if(kn.safeParse(e.type).success){ne(i);let o=b.generation,t=await browser.tabs.sendMessage(i,{type:"gazesight-interaction-content",operation:{type:e.type,options:e.payload}},{frameId:0}).catch(()=>{throw new x("GS_TARGET_CHANGED","Interaction content unavailable; select the target again.")}),n=await ee.getTarget(i);if(o!==b.generation||n.url!==r.url)throw new x("GS_TARGET_CHANGED","The document changed during interaction; the action may already have occurred. Inspect before retrying.");if(ne(i),!t?.ok)throw new x(typeof t?.code=="string"&&t.code.startsWith("GS_")?t.code:"GS_INTERACTION_FAILED","The DOM interaction was refused or failed.");return{tabId:i,url:n.url,action:e.type,inputSource:"dom",completed:!0,...t.value}}if(e.type==="get_viewport"||e.type==="set_viewport"){ne(i);let o=b.generation,t=async()=>{ne(i);let u=await ee.getTarget(i);if(b.generation!==o||u.url!==r.url)throw new x("GS_TARGET_CHANGED","The selected source changed during viewport operation.")},n=e.type==="get_viewport"?await ee.getViewport(r):await ee.resizePreview(r,e.payload,t);await t(),Fe(n.url,Be),e.type==="set_viewport"&&await Pe();let{movedToCompact:a,...s}={movedToCompact:!1,...n};return a&&(ue&&le?b.refresh(n.tabId):b.reauthorize(n.tabId),await Pe(),await de(),await Q?.publish()),{...s,requiresTargetSelection:!mw(n.tabId)}}if(e.type==="get_dom"||e.type==="get_element"||e.type==="get_changed_regions"){ne(i);let o=b.generation,t=await browser.tabs.sendMessage(i,{type:"gazesight-dom-content",operation:{type:e.type,options:{...e.payload,tabId:i}}},{frameId:0}).catch(()=>{throw new x("GS_TARGET_CHANGED","DOM content script unavailable; reauthorize the target.")});ne(i);let n=await ee.getTarget(i);if(b.generation!==o||n.url!==r.url)throw new x("GS_TARGET_CHANGED","The target changed during inspection.");if(!t?.ok)throw new x(typeof t?.code=="string"&&t.code.startsWith("GS_")?t.code:"GS_DOM_FAILED","The fixed DOM inspection operation failed.");return t.value}if(e.type==="capture_region"||e.type==="capture_element"||e.type==="capture_full_page"){ne(i);let o=b.generation;async function t(){ne(i);let a=await ee.getTarget(i);if(o!==b.generation||a.url!==r.url||($e!=="enabled"||!oe)&&!a.active)throw new x("GS_TARGET_CHANGED","The authorized active target changed during capture.")}let n=new In(async a=>(await t(),Dh({id:e.id,version:1,type:"capture",payload:Ve.parse({...a,tabId:i})})),async a=>{await t();let s=await browser.tabs.sendMessage(i,{type:"gazesight-capture-content",operation:a},{frameId:0}).catch(()=>{throw new x("GS_TARGET_CHANGED","Capture content script unavailable; reauthorize the target.")});if(await t(),!s?.ok)throw new x(typeof s?.code=="string"&&s.code.startsWith("GS_")?s.code:"GS_CAPTURE_FAILED","The fixed content capture operation failed.");return s.value},Ph);return uh(n,e,e.type==="capture_full_page"?cw:uw)}if(e.type==="capture"){ne(i);let o=performance.now(),t=b.generation;if(($e!=="enabled"||!oe)&&!r.active)throw new x("GS_CAPTURE_FAILED","Bring the selected GazeSight tab to the front in its Chrome window before capturing.");let n=0,a;if(e.payload.waitForStable){let h=await browser.tabs.sendMessage(i,{type:"gazesight-wait-stable",options:e.payload},{frameId:0}).catch(()=>{throw new x("GS_TARGET_CHANGED","The target document closed or navigated, or its content script is unavailable. Click the GazeSight icon in the target tab.")});if(!h?.ok)throw new x(h?.code==="GS_TARGET_CHANGED"?"GS_TARGET_CHANGED":"GS_RENDER_NOT_STABLE","The render did not appear stable before maxWaitMs. Retry after updates settle.",h?.stability?xd.parse(h.stability):void 0);n=h.stabilityWaitMs,a={lastMutationAgoMs:h.lastMutationAgoMs,fontsReady:h.fontsReady,pendingImages:h.pendingImages,timeoutReached:h.timeoutReached}}if(t!==b.generation)throw new x("GS_TARGET_CHANGED","The target document changed during capture preparation.");let s=performance.now(),u=await ee.capture(e.payload).then(h=>{if(typeof h!="string")throw new x("GS_CAPTURE_FAILED","Invalid native capture result.");return h}).catch(async h=>{throw h instanceof x&&h.code==="GS_PERMISSION_DENIED"?(b.reauthorize(i),await Pe(),await de(),await Q?.publish(),new x("GS_REAUTHORIZE_TARGET","Chrome requires permission again. Click the GazeSight extension icon in the target tab.")):h}),c=performance.now()-s,d=$e==="enabled"&&oe?[await ee.getTarget(i)]:await browser.tabs.query({active:!0,windowId:r.windowId});if(t!==b.generation)throw new x("GS_TARGET_CHANGED","The target document changed during native capture. Click the GazeSight icon in the target tab again.");if(d[0]?.id!==i||d[0]?.url!==r.url)throw new x("GS_CAPTURE_FAILED","The active tab changed during capture. Retry with the preview tab active.");let m=await createImageBitmap(await(await fetch(u)).blob()),p=m.width,f=m.height;return m.close(),{tabId:i,url:r.url,width:p,height:f,format:e.payload.format,captureMs:c,stabilityWaitMs:n,extensionTotalMs:performance.now()-o,renderAppearsStable:e.payload.waitForStable,stable:e.payload.waitForStable,...a,dataUrl:u}}if(e.type==="get_errors"){ne(i);let o=Oe.get(i)??[];return Oe.set(i,[]),{tabId:i,errors:o}}if(e.type==="reload")return await Td(b,i,r.url,async()=>{await Pe(),await de(),await Q?.publish()},async()=>(await ee.getTarget(i)).url??"",()=>ee.reload(i,e.payload.bypassCache)),await Ih(i),{tabId:i,url:r.url};if(e.type!=="navigate")throw new x("GS_INVALID_MESSAGE","Unsupported operation.");return Fe(e.payload.url,Be),await Td(b,i,r.url,async()=>{await Pe(),await de(),await Q?.publish()},async()=>(await ee.getTarget(i)).url??"",()=>ee.navigate(i,e.payload.url)),await Ih(i),{tabId:i,url:e.payload.url}}async function Ih(e){if(!(ue&&le))return;let r=Date.now()+5e3;for(;Date.now()<r;){if(b.selectedTab!==e||b.state==="none"||b.state==="authorized")return;let i=await browser.tabs.get(e).catch(()=>{});if(i?.status==="complete"&&b.isSelectedOrigin(i.url??"")){b.resume(e),await Pe(),await lt(e),await de(),await Q?.publish();return}await new Promise(o=>setTimeout(o,100))}}async function yw(){let e=await browser.storage.session.get(["sessionTargetTabId","sessionTargetOrigin","sessionTargetState","sessionPreview"]),r=typeof e.sessionTargetTabId=="number"?e.sessionTargetTabId:null,i=typeof e.sessionTargetOrigin=="string"?e.sessionTargetOrigin:null;if(r===null||i===null)return!1;try{let o=await browser.tabs.get(r);if(!o.url)throw new x("GS_TARGET_CHANGED","Stale session target.");return Fe(o.url,Be),b.choose(r,o.url),(e.sessionTargetState==="reauthorization_required"||!Nd(o.url,i))&&b.reauthorize(r),e.sessionPreview&&typeof e.sessionPreview=="object"&&await dt.hydrate(e.sessionPreview,b).catch(()=>!1),await Nn(r),await de(),!0}catch{return await Ho(),!1}}async function _w(){let e=await browser.storage.local.get(["continuousAuthPrimaryTabId","continuousAuthOrigin"]),r=typeof e.continuousAuthPrimaryTabId=="number"?e.continuousAuthPrimaryTabId:null,i=typeof e.continuousAuthOrigin=="string"?e.continuousAuthOrigin:null;if(!(r===null||i===null))try{let o=await browser.tabs.get(r);if(!o.url||!Nd(o.url,i))throw new x("GS_TARGET_CHANGED","Stale persisted target.");Fe(o.url,Be),b.choose(r,o.url),await Pe(),await Nn(r),await de()}catch{await browser.storage.local.remove(["continuousAuthPrimaryTabId","continuousAuthOrigin"])}}async function Zd(){Q?.stop();let e=await browser.storage.local.get(["port","token","allowedOrigins","backgroundCaptureEnabled","continuousAuthorizationEnabled"]);if(le=await browser.permissions.contains({origins:["<all_urls>"]}),oe=await chrome.permissions.contains({permissions:["tabCapture","offscreen"]}),$e=e.backgroundCaptureEnabled===!0&&oe?"enabled":"disabled",e.backgroundCaptureEnabled===!0&&!oe&&await browser.storage.local.set({backgroundCaptureEnabled:!1}),ue=e.continuousAuthorizationEnabled===!0&&le,e.continuousAuthorizationEnabled===!0&&!le&&await browser.storage.local.set({continuousAuthorizationEnabled:!1}),Be=Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],b.selectedTab===null&&!await yw()&&ue&&await _w(),typeof e.token!="string"||!/^[a-f0-9]{64}$/.test(e.token))return;let r=Number(e.port??32147);!Number.isInteger(r)||r<1024||r>65535||(Q=new Vo(r,e.token,hw,Cd,i=>{De=i,!i&&b.selectedTab!==null&&(Rd(b.selectedTab),Xo(b.selectedTab)),i&&b.state==="authorized"&&b.selectedTab!==null&&Nn(b.selectedTab),de()},2e4),Q.start())}async function Cd(e){let r=e.type==="capture"||e.type.startsWith("capture_"),i=!1,o=$r;if(r&&o!==null){if(Pn)throw new x("GS_CAPTURE_BUSY","Wait for the current overlay capture to complete.");ne(b.resolve(e.payload.tabId)),Pn=!0;try{(!("includeOverlay"in e.payload)||e.payload.includeOverlay!==!0)&&(i=await Dn(o,{op:"suspend"}),i||($r=null))}catch(a){throw Pn=!1,a}}let t=r&&b.state==="authorized"?b.selectedTab:null;t!==null&&await wr(t,{op:"suspend"});let n;r&&(Ed=!0,n=setTimeout(()=>{de().catch(()=>{})},120));try{let a=await Dh(e);if(On=!1,r){let s=a;Ah={mode:e.payload&&"waitForStable"in e.payload&&e.payload.waitForStable?"STABLE":"FAST",width:s.width,height:s.height,time:new Date().toISOString()}}return a}catch(a){throw On=!0,Th={code:a instanceof x?a.code:"GS_OPERATION_FAILED",message:Ge(a instanceof Error?a.message:"Operation failed",512),time:new Date().toISOString()},a}finally{t!==null&&await wr(t,{op:"resume"}),i&&o!==null&&(await Dn(o,{op:"resume"}).catch(()=>!1)||($r=null)),r&&o!==null&&(Pn=!1),n!==void 0&&clearTimeout(n),r&&(Ed=!1),de().catch(()=>{})}}async function Ce(){let e,r;if(b.selectedTab!==null){let i=await browser.tabs.get(b.selectedTab).catch(()=>{});e=i?.url?Sn(i.url,i.url):void 0,De&&b.state==="authorized"&&(r=(await ee.getDiagnostics(b.selectedTab).catch(()=>{}))?.viewport)}return{connected:De,paired:De,targetState:b.state,url:e,viewport:r,lastCapture:Ah,lastError:Th,backgroundMode:$e,backgroundCapture:{enabled:$e==="enabled",permissionGranted:oe},continuousAuthorization:{enabled:ue,permissionGranted:le,authorizedOrigin:ue&&b.state==="authorized"?b.selectedOrigin:null},consoleCount:yr.count,networkCount:_r.count,runtimeErrorCount:b.selectedTab===null?0:Oe.get(b.selectedTab)?.length??0}}async function ww(e){if(e==="status")return Ce();if(e==="background-enable")return $e="requesting",oe=await chrome.permissions.contains({permissions:["tabCapture","offscreen"]}),$e=oe?"enabled":"permission_denied",await browser.storage.local.set({backgroundCaptureEnabled:oe}),b.state==="authorized"&&b.selectedTab!==null&&await lt(b.selectedTab),await Q?.publish(),Ce();if(e==="background-denied")return $e="permission_denied",oe=!1,await browser.storage.local.set({backgroundCaptureEnabled:!1}),b.state==="authorized"&&b.selectedTab!==null&&await lt(b.selectedTab),await Q?.publish(),Ce();if(e==="background-disable")return $e="disabled",await browser.storage.local.set({backgroundCaptureEnabled:!1}),await chrome.permissions.remove({permissions:["tabCapture","offscreen"]}),oe=await chrome.permissions.contains({permissions:["tabCapture","offscreen"]}),b.state==="authorized"&&b.selectedTab!==null&&await lt(b.selectedTab),await Q?.publish(),Ce();if(e==="continuous-enable")return ue=!1,le=await browser.permissions.contains({origins:["<all_urls>"]}),ue=le,await browser.storage.local.set({continuousAuthorizationEnabled:le}),ue&&b.state==="authorized"&&b.selectedTab!==null&&b.selectedOrigin!==null&&await browser.storage.local.set({continuousAuthPrimaryTabId:b.selectedTab,continuousAuthOrigin:b.selectedOrigin}),await Q?.publish(),Ce();if(e==="continuous-denied")return ue=!1,await browser.storage.local.set({continuousAuthorizationEnabled:!1}),await Q?.publish(),Ce();if(e==="continuous-disable")return ue=!1,await browser.storage.local.set({continuousAuthorizationEnabled:!1}),await browser.storage.local.remove(["continuousAuthPrimaryTabId","continuousAuthOrigin"]),await browser.permissions.remove({origins:["<all_urls>"]}),le=await browser.permissions.contains({origins:["<all_urls>"]}),await Q?.publish(),Ce();if(e==="disconnect"){let i=b.selectedTab;return i!==null&&(await Rd(i),await Xo(i),b.remove(i)),jn(),Oe.clear(),On=!1,await Ho(),await browser.storage.local.remove(["continuousAuthPrimaryTabId","continuousAuthOrigin"]),dt.clear(),await de(),await Q?.publish(),Ce()}if(e==="select"){let[i]=await browser.tabs.query({active:!0,lastFocusedWindow:!0});if(!i?.id)throw new x("GS_NO_TARGET_TAB","Activate your preview page before using this tab.");if(Fe(i.url??"",Be),!await Ld(i))throw new x("GS_TARGET_SELECTION_FAILED","Selection failed. Check the allowed origin and settings.");return Ce()}if(!De)throw new x("GS_NOT_CONNECTED","Start the GazeSight MCP server and check pairing in settings.");let r=b.resolve();return ne(r),e==="diagnostics"?{status:await Ce(),console:yr.read(10,!1),network:_r.read(10,!1),runtimeErrors:(Oe.get(r)??[]).slice(-10)}:e==="fast"?lw.run({permissionGranted:()=>browser.permissions.contains({permissions:["downloads"]}),capture:async()=>await Cd({id:crypto.randomUUID(),version:1,type:"capture",payload:Ve.parse({tabId:r,format:"png",waitForStable:!1})}),download:async i=>{let o=await(await fetch(i.url)).blob(),t=URL.createObjectURL(o);try{return await browser.downloads.download({...i,url:t})}finally{setTimeout(()=>URL.revokeObjectURL(t),3e4)}},waitForCompletion:fw}):(await Cd({id:crypto.randomUUID(),version:1,type:"capture",payload:Ve.parse({tabId:r,waitForStable:!0})}),Ce())}async function Rd(e){await browser.tabs.sendMessage(e,{type:"gazesight-dom-content",operation:{type:"stop_tracking"}},{frameId:0}).catch(()=>{})}async function Ld(e){try{return Fe(e.url??"",Be),b.selectedTab!==null&&(await Rd(b.selectedTab),await Xo(b.selectedTab)),jn(),Oe.clear(),b.choose(e.id,e.url),On=!1,await Pe(),ue&&b.selectedOrigin!==null&&await browser.storage.local.set({continuousAuthPrimaryTabId:e.id,continuousAuthOrigin:b.selectedOrigin}),await Nn(e.id),await de(),await Q?.publish(),!0}catch{return await browser.runtime.openOptionsPage(),!1}}browser.action.onClicked.addListener(Ld);browser.commands.onCommand.addListener(async(e,r)=>{try{let i=await vh(e,r);i&&await Ld(i)}catch{await browser.runtime.openOptionsPage()}});browser.tabs.onRemoved.addListener(e=>{e===b.selectedTab&&(jn(),Ho(),browser.storage.local.remove(["continuousAuthPrimaryTabId","continuousAuthOrigin"])),b.remove(e),Oe.delete(e),de(),Q?.publish()});browser.windows.onRemoved.addListener(e=>{dt.removeWindow(e),Pe()});browser.tabs.onUpdated.addListener((e,r)=>{if(e===b.selectedTab){if(r.url&&!b.isSelectedOrigin(r.url)){jn(),Oe.delete(e),b.reauthorize(e),Pe(),wr(e,{op:"set",state:"none"}),de(),Q?.publish();return}r.status==="loading"&&(jn(),Oe.delete(e),$e==="enabled"&&oe||ue&&le?b.refresh(e):(b.reauthorize(e),wr(e,{op:"set",state:"none"})),Pe(),de()),r.status==="complete"&&(ue&&le&&browser.tabs.get(e).then(i=>{b.selectedTab===e&&b.state==="reauthorization_required"&&b.isSelectedOrigin(i.url??"")&&(b.resume(e),Pe(),lt(e),de(),Q?.publish())}).catch(()=>{}),Nn(e)),Q?.publish()}});browser.runtime.onMessage.addListener((e,r)=>{if(r.id===browser.runtime.id){if(e?.type==="gazesight-ui"){if(!Dd(r,browser.runtime.id,browser.runtime.getURL("popup.html"))&&!Dd(r,browser.runtime.id,browser.runtime.getURL("permission.html"),!0))return;let i=$h.safeParse(e);return i.success?ww(i.data.action).then(o=>({ok:!0,value:o}),o=>({ok:!1,error:Ge(o instanceof Error?o.message:"GS_OPERATION_FAILED",512)})):Promise.resolve({ok:!1,error:"GS_INVALID_MESSAGE"})}if(!(!De||b.state!=="authorized"||r.tab?.id!==b.selectedTab||!b.isSelectedOrigin(r.tab?.url??"")||r.frameId!==0)){if(e?.type==="console-diagnostic"){let i=xn.safeParse(e.entry);i.success&&yr.push({...i.data,message:Ge(i.data.message,512)});return}if(e?.type==="runtime-error"&&r.tab?.id!==void 0&&r.frameId===0){let i=Sd.safeParse(e.error);if(i.success&&r.tab.id===b.selectedTab){let o=Oe.get(r.tab.id)??[];o.push({...i.data,message:Ge(i.data.message,4096),source:i.data.source?Sn(i.data.source,r.tab.url??i.data.source):void 0}),Oe.set(r.tab.id,o.slice(-200))}}}}});browser.storage.onChanged.addListener((e,r)=>{r==="local"&&["port","token","allowedOrigins"].some(i=>i in e)&&Zd()});function jh(e,r){return e?.some(i=>r.includes(i))??!1}browser.permissions.onRemoved.addListener(e=>{e.origins?.includes("<all_urls>")&&(le=!1,ue=!1,browser.storage.local.set({continuousAuthorizationEnabled:!1}),browser.storage.local.remove(["continuousAuthPrimaryTabId","continuousAuthOrigin"]));let r=jh(e.permissions,["tabCapture","offscreen"]);r&&(oe=!1,$e="disabled",browser.storage.local.set({backgroundCaptureEnabled:!1})),(e.origins?.includes("<all_urls>")||r)&&b.state==="authorized"&&b.selectedTab!==null&&lt(b.selectedTab),Q?.publish()});browser.permissions.onAdded.addListener(e=>{e.origins?.includes("<all_urls>")&&(le=!0),jh(e.permissions,["tabCapture","offscreen"])&&(oe=!0),b.state==="authorized"&&b.selectedTab!==null&&lt(b.selectedTab),Q?.publish()});var Nh="gazesight-reconnect";browser.alarms.create(Nh,{periodInMinutes:1});browser.alarms.onAlarm.addListener(e=>{e.name===Nh&&!De&&Zd()});Zd();})();