[ SYSTEM ]: Linux wordpress 6.1.0-41-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.158-1 (2025-11-09) x86_64
[ SERVER ]: Apache/2.4.66 (Debian) | PHP: 8.2.30
[ USER ]: www-data | IP: 172.19.30.54
GEFORCE FILE MANAGER
/
var
/
www
/
html
/
wordpress
/
wp-content
/
plugins
/
elementor
/
assets
/
js
/
packages
/
editor-mcp
/
UPLOAD:
NAME
SIZE
QUICK PERMS
ACTIONS
📄 editor-mcp.asset.php
267 B
SET
[ EDIT ]
|
[ DEL ]
📄 editor-mcp.js.LICENSE.txt
51,016 B
SET
[ EDIT ]
|
[ DEL ]
📄 editor-mcp.min.js
439,436 B
SET
[ EDIT ]
|
[ DEL ]
📄 editor-mcp.min.js.LICENSE.txt
95 B
SET
[ EDIT ]
|
[ DEL ]
📄 editor-mcp.strings.js
0 B
SET
[ EDIT ]
|
[ DEL ]
DELETE SELECTED
[ CLOSE ]
EDIT: editor-mcp.min.js
!function(){"use strict";var e={323:function(e,t){function r(e,t){return{validate:e,compare:t}}Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0,t.fullFormats={date:r(i,a),time:r(c(!0),d),"date-time":r(h(!0),p),"iso-time":r(c(),u),"iso-date-time":r(h(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(e){return f.test(e)&&g.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:function(e){if(b.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}},uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:function(e){return _.lastIndex=0,_.test(e)},int32:{type:"number",validate:function(e){return Number.isInteger(e)&&e<=v&&e>=y}},int64:{type:"number",validate:function(e){return Number.isInteger(e)}},float:{type:"number",validate:w},double:{type:"number",validate:w},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:r(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,d),"date-time":r(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":r(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);const s=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,n=[0,31,28,31,30,31,30,31,31,30,31,30,31];function i(e){const t=s.exec(e);if(!t)return!1;const r=+t[1],i=+t[2],a=+t[3];return i>=1&&i<=12&&a>=1&&a<=(2===i&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:n[i])}function a(e,t){if(e&&t)return e>t?1:e<t?-1:0}const o=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){const r=o.exec(t);if(!r)return!1;const s=+r[1],n=+r[2],i=+r[3],a=r[4],c="-"===r[5]?-1:1,d=+(r[6]||0),u=+(r[7]||0);if(d>23||u>59||e&&!a)return!1;if(s<=23&&n<=59&&i<60)return!0;const l=n-u*c,h=s-d*c-(l<0?1:0);return(23===h||-1===h)&&(59===l||-1===l)&&i<61}}function d(e,t){if(!e||!t)return;const r=new Date("2020-01-01T"+e).valueOf(),s=new Date("2020-01-01T"+t).valueOf();return r&&s?r-s:void 0}function u(e,t){if(!e||!t)return;const r=o.exec(e),s=o.exec(t);return r&&s?(e=r[1]+r[2]+r[3])>(t=s[1]+s[2]+s[3])?1:e<t?-1:0:void 0}const l=/t|\s/i;function h(e){const t=c(e);return function(e){const r=e.split(l);return 2===r.length&&i(r[0])&&t(r[1])}}function p(e,t){if(!e||!t)return;const r=new Date(e).valueOf(),s=new Date(t).valueOf();return r&&s?r-s:void 0}function m(e,t){if(!e||!t)return;const[r,s]=e.split(l),[n,i]=t.split(l),o=a(r,n);return void 0!==o?o||d(s,i):void 0}const f=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm,y=-(2**31),v=2**31-1;function w(){return!0}const b=/[^\\]\\Z/},340:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n=r(9048),i={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:e})=>s._`{propertyName: ${e.propertyName}}`},code(e){const{gen:t,schema:r,data:i,it:a}=e;if((0,n.alwaysValidSchema)(a,r))return;const o=t.name("valid");t.forIn("key",i,r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},o),t.if((0,s.not)(o),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(o)}};t.default=i},343:function(e,t,r){const{isUUID:s}=r(4834),n=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=["http","https","ws","wss","urn","urn:uuid"];function a(e){return!0===e.secure||!1!==e.secure&&!!e.scheme&&!(3!==e.scheme.length||"w"!==e.scheme[0]&&"W"!==e.scheme[0]||"s"!==e.scheme[1]&&"S"!==e.scheme[1]||"s"!==e.scheme[2]&&"S"!==e.scheme[2])}function o(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function c(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const d={scheme:"http",domainHost:!0,parse:o,serialize:c},u={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=a(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(a(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,r]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}},l={http:d,https:{scheme:"https",domainHost:d.domainHost,parse:o,serialize:c},ws:u,wss:{scheme:"wss",domainHost:u.domainHost,parse:u.parse,serialize:u.serialize},urn:{scheme:"urn",parse:function(e,t){if(!e.path)return e.error="URN can not be parsed",e;const r=e.path.match(n);if(r){const s=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];const n=h(`${s}:${t.nid||e.nid}`);e.path=void 0,n&&(e=n.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){if(void 0===e.nid)throw new Error("URN without nid cannot be serialized");const r=t.scheme||e.scheme||"urn",s=e.nid.toLowerCase(),n=h(`${r}:${t.nid||s}`);n&&(e=n.serialize(e,t));const i=e,a=e.nss;return i.path=`${s||t.nid}:${a}`,t.skipEscape=!0,i},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(e,t){const r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&s(r.uuid)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};function h(e){return e&&(l[e]||l[e.toLowerCase()])||void 0}Object.setPrototypeOf(l,null),e.exports={wsIsSecure:a,SCHEMES:l,isValidSchemeName:function(e){return-1!==i.indexOf(e)},getSchemeHandler:h}},513:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.getRules=t.isJSONType=void 0;const r=new Set(["string","number","integer","boolean","null","object","array"]);t.isJSONType=function(e){return"string"==typeof e&&r.has(e)},t.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}},647:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const s=r(9981),n=r(781),i=r(5870),a=r(2546),o=["/properties"],c="http://json-schema.org/draft-07/schema";class d extends s.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,c,!1),this.refs["http://json-schema.org/schema"]=c}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(c)?c:void 0)}}t.Ajv=d,e.exports=t=d,e.exports.Ajv=d,Object.defineProperty(t,"__esModule",{value:!0}),t.default=d;var u=r(3697);Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=r(6596);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var h=r(3781);Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return h.default}});var p=r(7346);Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})},781:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(2365),n=r(5105),i=r(5215),a=r(6545),o=r(6836),c=[s.default,n.default,(0,i.default)(),a.default,o.metadataVocabulary,o.contentVocabulary];t.default=c},978:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;const s=r(9048),n=r(2017),i=r(2775),a=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);t.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!c(e):!!t&&d(e)<=t)};const o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function c(e){for(const t in e){if(o.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(c))return!0;if("object"==typeof r&&c(r))return!0}return!1}function d(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!a.has(r)&&("object"==typeof e[r]&&(0,s.eachItem)(e[r],e=>t+=d(e)),t===1/0))return 1/0}return t}function u(e,t="",r){!1!==r&&(t=p(t));const s=e.parse(t);return l(e,s)}function l(e,t){return e.serialize(t).split("#")[0]+"#"}t.getFullPath=u,t._getFullPath=l;const h=/#\/?$/;function p(e){return e?e.replace(h,""):""}t.normalizeId=p,t.resolveUrl=function(e,t,r){return r=p(r),e.resolve(t,r)};const m=/^[a-z_][-a-z0-9._]*$/i;t.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:s}=this.opts,a=p(e[r]||t),o={"":a},c=u(s,a,!1),d={},l=new Set;return i(e,{allKeys:!0},(e,t,s,n)=>{if(void 0===n)return;const i=c+t;let a=o[n];function u(t){const r=this.opts.uriResolver.resolve;if(t=p(a?r(a,t):t),l.has(t))throw f(t);l.add(t);let s=this.refs[t];return"string"==typeof s&&(s=this.refs[s]),"object"==typeof s?h(e,s.schema,t):t!==p(i)&&("#"===t[0]?(h(e,d[t],t),d[t]=e):this.refs[t]=i),t}function g(e){if("string"==typeof e){if(!m.test(e))throw new Error(`invalid anchor "${e}"`);u.call(this,`#${e}`)}}"string"==typeof e[r]&&(a=u.call(this,e[r])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),o[t]=a}),d;function h(e,t,r){if(void 0!==t&&!n(e,t))throw f(r)}function f(e){return new Error(`reference "${e}" resolves to more than one schema`)}}},1070:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n=r(9048),i={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?s.str`must contain at least ${e} valid item(s)`:s.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?s._`{minContains: ${e}}`:s._`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:r,parentSchema:i,data:a,it:o}=e;let c,d;const{minContains:u,maxContains:l}=i;o.opts.next?(c=void 0===u?1:u,d=l):c=1;const h=t.const("len",s._`${a}.length`);if(e.setParams({min:c,max:d}),void 0===d&&0===c)return void(0,n.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==d&&c>d)return(0,n.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,n.alwaysValidSchema)(o,r)){let t=s._`${h} >= ${c}`;return void 0!==d&&(t=s._`${t} && ${h} <= ${d}`),void e.pass(t)}o.items=!0;const p=t.name("valid");function m(){const e=t.name("_valid"),r=t.let("count",0);f(e,()=>t.if(e,()=>function(e){t.code(s._`${e}++`),void 0===d?t.if(s._`${e} >= ${c}`,()=>t.assign(p,!0).break()):(t.if(s._`${e} > ${d}`,()=>t.assign(p,!1).break()),1===c?t.assign(p,!0):t.if(s._`${e} >= ${c}`,()=>t.assign(p,!0)))}(r)))}function f(r,s){t.forRange("i",0,h,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:n.Type.Num,compositeRule:!0},r),s()})}void 0===d&&1===c?f(p,()=>t.if(p,()=>t.break())):0===c?(t.let(p,!0),void 0!==d&&t.if(s._`${a}.length > 0`,m)):(t.let(p,!1),m()),e.result(p,()=>e.reset())}};t.default=i},1140:function(e,t){function r(e,t){return t.rules.some(t=>s(e,t))}function s(e,t){var r;return void 0!==e[t.keyword]||(null===(r=t.definition.implements)||void 0===r?void 0:r.some(t=>void 0!==e[t]))}Object.defineProperty(t,"__esModule",{value:!0}),t.shouldUseRule=t.shouldUseGroup=t.schemaHasRulesForType=void 0,t.schemaHasRulesForType=function({schema:e,self:t},s){const n=t.RULES.types[s];return n&&!0!==n&&r(e,n)},t.shouldUseGroup=r,t.shouldUseRule=s},1234:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n=r(9048),i=r(5311),a={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>s._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:a,schemaCode:o,schema:c}=e;a||c&&"object"==typeof c?e.fail$data(s._`!${(0,n.useFunc)(t,i.default)}(${r}, ${o})`):e.fail(s._`${c} !== ${r}`)}};t.default=a},1430:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.resolveSchema=t.getCompilingSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;const s=r(6596),n=r(3781),i=r(6670),a=r(978),o=r(9048),c=r(3697);class d{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,a.normalizeId)(null==r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==r?void 0:r.$async,this.refs={}}}function u(e){const t=h.call(this,e);if(t)return t;const r=(0,a.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:o,lines:d}=this.opts.code,{ownProperties:u}=this.opts,l=new s.CodeGen(this.scope,{es5:o,lines:d,ownProperties:u});let p;e.$async&&(p=l.scopeValue("Error",{ref:n.default,code:s._`require("ajv/dist/runtime/validation_error").default`}));const m=l.scopeName("validate");e.validateName=m;const f={gen:l,allErrors:this.opts.allErrors,data:i.default.data,parentData:i.default.parentData,parentDataProperty:i.default.parentDataProperty,dataNames:[i.default.data],dataPathArr:[s.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:l.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,s.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:s.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:s._`""`,opts:this.opts,self:this};let g;try{this._compilations.add(e),(0,c.validateFunctionCode)(f),l.optimize(this.opts.code.optimize);const t=l.toString();g=`${l.scopeRefs(i.default.scope)}return ${t}`,this.opts.code.process&&(g=this.opts.code.process(g,e));const r=new Function(`${i.default.self}`,`${i.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:r}),r.errors=null,r.schema=e.schema,r.schemaEnv=e,e.$async&&(r.$async=!0),!0===this.opts.code.source&&(r.source={validateName:m,validateCode:t,scopeValues:l._values}),this.opts.unevaluated){const{props:e,items:t}=f;r.evaluated={props:e instanceof s.Name?void 0:e,items:t instanceof s.Name?void 0:t,dynamicProps:e instanceof s.Name,dynamicItems:t instanceof s.Name},r.source&&(r.source.evaluated=(0,s.stringify)(r.evaluated))}return e.validate=r,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error("Error compiling schema, function code:",g),t}finally{this._compilations.delete(e)}}function l(e){return(0,a.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:u.call(this,e)}function h(e){for(const t of this._compilations)if(p(t,e))return t}function p(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function m(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||f.call(this,e,t)}function f(e,t){const r=this.opts.uriResolver.parse(t),s=(0,a._getFullPath)(this.opts.uriResolver,r);let n=(0,a.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&s===n)return _.call(this,r,e);const i=(0,a.normalizeId)(s),o=this.refs[i]||this.schemas[i];if("string"==typeof o){const t=f.call(this,e,o);if("object"!=typeof(null==t?void 0:t.schema))return;return _.call(this,r,t)}if("object"==typeof(null==o?void 0:o.schema)){if(o.validate||u.call(this,o),i===(0,a.normalizeId)(t)){const{schema:t}=o,{schemaId:r}=this.opts,s=t[r];return s&&(n=(0,a.resolveUrl)(this.opts.uriResolver,n,s)),new d({schema:t,schemaId:r,root:e,baseId:n})}return _.call(this,r,o)}}t.SchemaEnv=d,t.compileSchema=u,t.resolveRef=function(e,t,r){var s;r=(0,a.resolveUrl)(this.opts.uriResolver,t,r);const n=e.refs[r];if(n)return n;let i=m.call(this,e,r);if(void 0===i){const n=null===(s=e.localRefs)||void 0===s?void 0:s[r],{schemaId:a}=this.opts;n&&(i=new d({schema:n,schemaId:a,root:e,baseId:t}))}return void 0!==i?e.refs[r]=l.call(this,i):void 0},t.getCompilingSchema=h,t.resolveSchema=f;const g=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function _(e,{baseId:t,schema:r,root:s}){var n;if("/"!==(null===(n=e.fragment)||void 0===n?void 0:n[0]))return;for(const s of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;const e=r[(0,o.unescapeFragment)(s)];if(void 0===e)return;const n="object"==typeof(r=e)&&r[this.opts.schemaId];!g.has(s)&&n&&(t=(0,a.resolveUrl)(this.opts.uriResolver,t,n))}let i;if("boolean"!=typeof r&&r.$ref&&!(0,o.schemaHasRulesButRef)(r,this.RULES)){const e=(0,a.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=f.call(this,s,e)}const{schemaId:c}=this.opts;return i=i||new d({schema:r,schemaId:c,root:s,baseId:t}),i.schema!==i.root.schema?i:void 0}},1464:function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};t.default=r},1526:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(9048),n={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:n}=e;if((0,s.alwaysValidSchema)(n,r))return void e.fail();const i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};t.default=n},1808:function(e){e.exports=JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},1828:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(9877),n=r(6596),i=r(9048),a=r(5311),o={message:({params:{i:e,j:t}})=>n.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>n._`{i: ${e}, j: ${t}}`},c={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:o,code(e){const{gen:t,data:r,$data:o,schema:c,parentSchema:d,schemaCode:u,it:l}=e;if(!o&&!c)return;const h=t.let("valid"),p=d.items?(0,s.getSchemaTypes)(d.items):[];function m(i,a){const o=t.name("item"),c=(0,s.checkDataTypes)(p,o,l.opts.strictNumbers,s.DataType.Wrong),d=t.const("indices",n._`{}`);t.for(n._`;${i}--;`,()=>{t.let(o,n._`${r}[${i}]`),t.if(c,n._`continue`),p.length>1&&t.if(n._`typeof ${o} == "string"`,n._`${o} += "_"`),t.if(n._`typeof ${d}[${o}] == "number"`,()=>{t.assign(a,n._`${d}[${o}]`),e.error(),t.assign(h,!1).break()}).code(n._`${d}[${o}] = ${i}`)})}function f(s,o){const c=(0,i.useFunc)(t,a.default),d=t.name("outer");t.label(d).for(n._`;${s}--;`,()=>t.for(n._`${o} = ${s}; ${o}--;`,()=>t.if(n._`${c}(${r}[${s}], ${r}[${o}])`,()=>{e.error(),t.assign(h,!1).break(d)})))}e.block$data(h,function(){const s=t.let("i",n._`${r}.length`),i=t.let("j");e.setParams({i:s,j:i}),t.assign(h,!0),t.if(n._`${s} > 1`,()=>(p.length>0&&!p.some(e=>"object"===e||"array"===e)?m:f)(s,i))},n._`${u} === false`),e.ok(h)}};t.default=c},1980:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;const s=r(6596),n=r(9048),i=r(6670),a=r(9048);function o(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:s._`Object.prototype.hasOwnProperty`})}function c(e,t,r){return s._`${o(e)}.call(${t}, ${r})`}function d(e,t,r,n){const i=s._`${t}${(0,s.getProperty)(r)} === undefined`;return n?(0,s.or)(i,(0,s.not)(c(e,t,r))):i}function u(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}t.checkReportMissingProp=function(e,t){const{gen:r,data:n,it:i}=e;r.if(d(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:s._`${t}`},!0),e.error()})},t.checkMissingProp=function({gen:e,data:t,it:{opts:r}},n,i){return(0,s.or)(...n.map(n=>(0,s.and)(d(e,t,n,r.ownProperties),s._`${i} = ${n}`)))},t.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},t.hasPropFunc=o,t.isOwnProperty=c,t.propertyInData=function(e,t,r,n){const i=s._`${t}${(0,s.getProperty)(r)} !== undefined`;return n?s._`${i} && ${c(e,t,r)}`:i},t.noPropertyInData=d,t.allSchemaProperties=u,t.schemaProperties=function(e,t){return u(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))},t.callValidateCode=function({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:o},it:c},d,u,l){const h=l?s._`${e}, ${t}, ${n}${a}`:t,p=[[i.default.instancePath,(0,s.strConcat)(i.default.instancePath,o)],[i.default.parentData,c.parentData],[i.default.parentDataProperty,c.parentDataProperty],[i.default.rootData,i.default.rootData]];c.opts.dynamicRef&&p.push([i.default.dynamicAnchors,i.default.dynamicAnchors]);const m=s._`${h}, ${r.object(...p)}`;return u!==s.nil?s._`${d}.call(${u}, ${m})`:s._`${d}(${m})`};const l=s._`new RegExp`;t.usePattern=function({gen:e,it:{opts:t}},r){const n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,o=i(r,n);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:s._`${"new RegExp"===i.code?l:(0,a.useFunc)(e,i)}(${r}, ${n})`})},t.validateArray=function(e){const{gen:t,data:r,keyword:i,it:a}=e,o=t.name("valid");if(a.allErrors){const e=t.let("valid",!0);return c(()=>t.assign(e,!1)),e}return t.var(o,!0),c(()=>t.break()),o;function c(a){const c=t.const("len",s._`${r}.length`);t.forRange("i",0,c,r=>{e.subschema({keyword:i,dataProp:r,dataPropType:n.Type.Num},o),t.if((0,s.not)(o),a)})}},t.validateUnion=function(e){const{gen:t,schema:r,keyword:i,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(e=>(0,n.alwaysValidSchema)(a,e))&&!a.opts.unevaluated)return;const o=t.let("valid",!1),c=t.name("_valid");t.block(()=>r.forEach((r,n)=>{const a=e.subschema({keyword:i,schemaProp:n,compositeRule:!0},c);t.assign(o,s._`${o} || ${c}`),e.mergeValidEvaluated(a,c)||t.if((0,s.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}},2010:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n=r(9048),i=r(6158),a={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const r="maxLength"===e?"more":"fewer";return s.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>s._`{limit: ${e}}`},code(e){const{keyword:t,data:r,schemaCode:a,it:o}=e,c="maxLength"===t?s.operators.GT:s.operators.LT,d=!1===o.opts.unicode?s._`${r}.length`:s._`${(0,n.useFunc)(e.gen,i.default)}(${r})`;e.fail$data(s._`${d} ${c} ${a}`)}};t.default=a},2017:function(e){e.exports=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var s,n,i;if(Array.isArray(t)){if((s=t.length)!=r.length)return!1;for(n=s;0!==n--;)if(!e(t[n],r[n]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((s=(i=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(n=s;0!==n--;)if(!Object.prototype.hasOwnProperty.call(r,i[n]))return!1;for(n=s;0!==n--;){var a=i[n];if(!e(t[a],r[a]))return!1}return!0}return t!=t&&r!=r}},2149:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(9048),n={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,s.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};t.default=n},2327:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(1980),n=r(6596),i=r(6670),a=r(9048),o={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>n._`{additionalProperty: ${e.additionalProperty}}`},code(e){const{gen:t,schema:r,parentSchema:o,data:c,errsCount:d,it:u}=e;if(!d)throw new Error("ajv implementation error");const{allErrors:l,opts:h}=u;if(u.props=!0,"all"!==h.removeAdditional&&(0,a.alwaysValidSchema)(u,r))return;const p=(0,s.allSchemaProperties)(o.properties),m=(0,s.allSchemaProperties)(o.patternProperties);function f(e){t.code(n._`delete ${c}[${e}]`)}function g(s){if("all"===h.removeAdditional||h.removeAdditional&&!1===r)f(s);else{if(!1===r)return e.setParams({additionalProperty:s}),e.error(),void(l||t.break());if("object"==typeof r&&!(0,a.alwaysValidSchema)(u,r)){const r=t.name("valid");"failing"===h.removeAdditional?(_(s,r,!1),t.if((0,n.not)(r),()=>{e.reset(),f(s)})):(_(s,r),l||t.if((0,n.not)(r),()=>t.break()))}}}function _(t,r,s){const n={keyword:"additionalProperties",dataProp:t,dataPropType:a.Type.Str};!1===s&&Object.assign(n,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(n,r)}t.forIn("key",c,r=>{p.length||m.length?t.if(function(r){let i;if(p.length>8){const e=(0,a.schemaRefOrVal)(u,o.properties,"properties");i=(0,s.isOwnProperty)(t,e,r)}else i=p.length?(0,n.or)(...p.map(e=>n._`${r} === ${e}`)):n.nil;return m.length&&(i=(0,n.or)(i,...m.map(t=>n._`${(0,s.usePattern)(e,t)}.test(${r})`))),(0,n.not)(i)}(r),()=>g(r)):g(r)}),e.ok(n._`${d} === ${i.default.errors}`)}};t.default=o},2363:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;const s=r(6596),n=r(9048);function i(e,t,r){const{gen:i,compositeRule:a,data:o,opts:c}=e;if(void 0===r)return;const d=s._`${o}${(0,s.getProperty)(t)}`;if(a)return void(0,n.checkStrictMode)(e,`default is ignored for: ${d}`);let u=s._`${d} === undefined`;"empty"===c.useDefaults&&(u=s._`${u} || ${d} === null || ${d} === ""`),i.if(u,s._`${d} = ${(0,s.stringify)(r)}`)}t.assignDefaults=function(e,t){const{properties:r,items:s}=e.schema;if("object"===t&&r)for(const t in r)i(e,t,r[t].default);else"array"===t&&Array.isArray(s)&&s.forEach((t,r)=>i(e,r,t.default))}},2365:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(1464),n=r(3740),i=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",s.default,n.default];t.default=i},2546:function(e){e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}')},2775:function(e){var t=e.exports=function(e,t,s){"function"==typeof t&&(s=t,t={}),r(t,"function"==typeof(s=t.cb||s)?s:s.pre||function(){},s.post||function(){},e,"",e)};function r(e,n,i,a,o,c,d,u,l,h){if(a&&"object"==typeof a&&!Array.isArray(a)){for(var p in n(a,o,c,d,u,l,h),a){var m=a[p];if(Array.isArray(m)){if(p in t.arrayKeywords)for(var f=0;f<m.length;f++)r(e,n,i,m[f],o+"/"+p+"/"+f,c,o,p,a,f)}else if(p in t.propsKeywords){if(m&&"object"==typeof m)for(var g in m)r(e,n,i,m[g],o+"/"+p+"/"+s(g),c,o,p,a,g)}else(p in t.keywords||e.allKeys&&!(p in t.skipKeywords))&&r(e,n,i,m,o+"/"+p,c,o,p,a)}i(a,o,c,d,u,l,h)}}function s(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}},2986:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;const s=r(6596),n=r(6670),i=r(1980),a=r(4971);function o(e){const{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,s._`${n.parentData}[${n.parentDataProperty}]`))}function c(e,t,r){if(void 0===r)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword","function"==typeof r?{ref:r}:{ref:r,code:(0,s.stringify)(r)})}t.macroKeywordCode=function(e,t){const{gen:r,keyword:n,schema:i,parentSchema:a,it:o}=e,d=t.macro.call(o.self,i,a,o),u=c(r,n,d);!1!==o.opts.validateSchema&&o.self.validateSchema(d,!0);const l=r.name("valid");e.subschema({schema:d,schemaPath:s.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:u,compositeRule:!0},l),e.pass(l,()=>e.error(!0))},t.funcKeywordCode=function(e,t){var r;const{gen:d,keyword:u,schema:l,parentSchema:h,$data:p,it:m}=e;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(m,t);const f=!p&&t.compile?t.compile.call(m.self,l,h,m):t.validate,g=c(d,u,f),_=d.let("valid");function y(r=(t.async?s._`await `:s.nil)){const a=m.opts.passContext?n.default.this:n.default.self,o=!("compile"in t&&!p||!1===t.schema);d.assign(_,s._`${r}${(0,i.callValidateCode)(e,g,a,o)}`,t.modifying)}function v(e){var r;d.if((0,s.not)(null!==(r=t.valid)&&void 0!==r?r:_),e)}e.block$data(_,function(){if(!1===t.errors)y(),t.modifying&&o(e),v(()=>e.error());else{const r=t.async?function(){const e=d.let("ruleErrs",null);return d.try(()=>y(s._`await `),t=>d.assign(_,!1).if(s._`${t} instanceof ${m.ValidationError}`,()=>d.assign(e,s._`${t}.errors`),()=>d.throw(t))),e}():function(){const e=s._`${g}.errors`;return d.assign(e,null),y(s.nil),e}();t.modifying&&o(e),v(()=>function(e,t){const{gen:r}=e;r.if(s._`Array.isArray(${t})`,()=>{r.assign(n.default.vErrors,s._`${n.default.vErrors} === null ? ${t} : ${n.default.vErrors}.concat(${t})`).assign(n.default.errors,s._`${n.default.vErrors}.length`),(0,a.extendErrors)(e)},()=>e.error())}(e,r))}}),e.ok(null!==(r=t.valid)&&void 0!==r?r:_)},t.validSchemaType=function(e,t,r=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&void 0===e)},t.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:s},n,i){if(Array.isArray(n.keyword)?!n.keyword.includes(i):n.keyword!==i)throw new Error("ajv implementation error");const a=n.dependencies;if(null==a?void 0:a.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${i}: ${a.join(",")}`);if(n.validateSchema&&!n.validateSchema(e[i])){const e=`keyword "${i}" value is invalid at path "${s}": `+r.errorsText(n.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);r.logger.error(e)}}},3144:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n=r(9048),i=r(5311),a={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>s._`{allowedValues: ${e}}`},code(e){const{gen:t,data:r,$data:a,schema:o,schemaCode:c,it:d}=e;if(!a&&0===o.length)throw new Error("enum must have non-empty array");const u=o.length>=d.opts.loopEnum;let l;const h=()=>null!=l?l:l=(0,n.useFunc)(t,i.default);let p;if(u||a)p=t.let("valid"),e.block$data(p,function(){t.assign(p,!1),t.forOf("v",c,e=>t.if(s._`${h()}(${r}, ${e})`,()=>t.assign(p,!0).break()))});else{if(!Array.isArray(o))throw new Error("ajv implementation error");const e=t.const("vSchema",c);p=(0,s.or)(...o.map((t,n)=>function(e,t){const n=o[t];return"object"==typeof n&&null!==n?s._`${h()}(${r}, ${e}[${t}])`:s._`${r} === ${n}`}(e,n)))}e.pass(p)}};t.default=a},3231:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class r{}t._CodeOrName=r,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class s extends r{constructor(e){if(super(),!t.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=s;class n extends r{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof s&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function i(e,...t){const r=[e[0]];let s=0;for(;s<t.length;)c(r,t[s]),r.push(e[++s]);return new n(r)}t._Code=n,t.nil=new n(""),t._=i;const a=new n("+");function o(e,...t){const r=[u(e[0])];let s=0;for(;s<t.length;)r.push(a),c(r,t[s]),r.push(a,u(e[++s]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===a){const r=d(e[t-1],e[t+1]);if(void 0!==r){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}(r),new n(r)}function c(e,t){t instanceof n?e.push(...t._items):t instanceof s?e.push(t):e.push(function(e){return"number"==typeof e||"boolean"==typeof e||null===e?e:u(Array.isArray(e)?e.join(","):e)}(t))}function d(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof s||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof s?void 0:`"${e}${t.slice(1)}`}function u(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.str=o,t.addCodeArg=c,t.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`},t.stringify=function(e){return new n(u(e))},t.safeStringify=u,t.getProperty=function(e){return"string"==typeof e&&t.IDENTIFIER.test(e)?new n(`.${e}`):i`[${e}]`},t.getEsmExportName=function(e){if("string"==typeof e&&t.IDENTIFIER.test(e))return new n(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)},t.regexpCode=function(e){return new n(e.toString())}},3501:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(9048),n={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const i=t.name("valid");r.forEach((t,r)=>{if((0,s.alwaysValidSchema)(n,t))return;const a=e.subschema({keyword:"allOf",schemaProp:r},i);e.ok(i),e.mergeEvaluated(a)})}};t.default=n},3663:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(1980),n=r(9048),i=r(6596),a={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>i.str`must match pattern "${e}"`,params:({schemaCode:e})=>i._`{pattern: ${e}}`},code(e){const{gen:t,data:r,$data:a,schema:o,schemaCode:c,it:d}=e,u=d.opts.unicodeRegExp?"u":"";if(a){const{regExp:s}=d.opts.code,a="new RegExp"===s.code?i._`new RegExp`:(0,n.useFunc)(t,s),o=t.let("valid");t.try(()=>t.assign(o,i._`${a}(${c}, ${u}).test(${r})`),()=>t.assign(o,!1)),e.fail$data(i._`!${o}`)}else{const t=(0,s.usePattern)(e,o);e.fail$data(i._`!${t}.test(${r})`)}}};t.default=a},3697:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;const s=r(5962),n=r(9877),i=r(1140),a=r(9877),o=r(2363),c=r(2986),d=r(7344),u=r(6596),l=r(6670),h=r(978),p=r(9048),m=r(4971);function f({gen:e,validateName:t,schema:r,schemaEnv:s,opts:n},i){n.code.es5?e.func(t,u._`${l.default.data}, ${l.default.valCxt}`,s.$async,()=>{e.code(u._`"use strict"; ${g(r,n)}`),function(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,u._`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,u._`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,u._`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,u._`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,u._`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,u._`""`),e.var(l.default.parentData,u._`undefined`),e.var(l.default.parentDataProperty,u._`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,u._`{}`)})}(e,n),e.code(i)}):e.func(t,u._`${l.default.data}, ${function(e){return u._`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?u._`, ${l.default.dynamicAnchors}={}`:u.nil}}={}`}(n)}`,s.$async,()=>e.code(g(r,n)).code(i))}function g(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?u._`/*# sourceURL=${r} */`:u.nil}function _({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const r in e)if(t.RULES.all[r])return!0;return!1}function y(e){return"boolean"!=typeof e.schema}function v(e){(0,p.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:s,self:n}=e;t.$ref&&s.ignoreKeywordsWithRef&&(0,p.schemaHasRulesButRef)(t,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function w(e,t){if(e.opts.jtd)return k(e,[],!1,t);const r=(0,n.getSchemaTypes)(e.schema);k(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function b({gen:e,schemaEnv:t,schema:r,errSchemaPath:s,opts:n}){const i=r.$comment;if(!0===n.$comment)e.code(u._`${l.default.self}.logger.log(${i})`);else if("function"==typeof n.$comment){const r=u.str`${s}/$comment`,n=e.scopeValue("root",{ref:t.root});e.code(u._`${l.default.self}.opts.$comment(${i}, ${r}, ${n}.schema)`)}}function k(e,t,r,s){const{gen:n,schema:o,data:c,allErrors:d,opts:h,self:m}=e,{RULES:f}=m;function g(p){(0,i.shouldUseGroup)(o,p)&&(p.type?(n.if((0,a.checkDataType)(p.type,c,h.strictNumbers)),S(e,p),1===t.length&&t[0]===p.type&&r&&(n.else(),(0,a.reportTypeError)(e)),n.endIf()):S(e,p),d||n.if(u._`${l.default.errors} === ${s||0}`))}!o.$ref||!h.ignoreKeywordsWithRef&&(0,p.schemaHasRulesButRef)(o,f)?(h.jtd||function(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(function(e,t){t.length&&(e.dataTypes.length?(t.forEach(t=>{$(e.dataTypes,t)||E(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const r=[];for(const s of e.dataTypes)$(t,s)?r.push(s):t.includes("integer")&&"number"===s&&r.push("integer");e.dataTypes=r}(e,t)):e.dataTypes=t)}(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&E(e,"use allowUnionTypes to allow union type keyword")}(e,t),function(e,t){const r=e.self.RULES.all;for(const s in r){const n=r[s];if("object"==typeof n&&(0,i.shouldUseRule)(e.schema,n)){const{type:r}=n.definition;r.length&&!r.some(e=>{return s=e,(r=t).includes(s)||"number"===s&&r.includes("integer");var r,s})&&E(e,`missing type "${r.join(",")}" for keyword "${s}"`)}}}(e,e.dataTypes))}(e,t),n.block(()=>{for(const e of f.rules)g(e);g(f.post)})):n.block(()=>x(e,"$ref",f.all.$ref.definition))}function S(e,t){const{gen:r,schema:s,opts:{useDefaults:n}}=e;n&&(0,o.assignDefaults)(e,t.type),r.block(()=>{for(const r of t.rules)(0,i.shouldUseRule)(s,r)&&x(e,r.keyword,r.definition,t.type)})}function $(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function E(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,p.checkStrictMode)(e,t,e.opts.strictTypes)}t.validateFunctionCode=function(e){y(e)&&(v(e),_(e))?function(e){const{schema:t,opts:r,gen:s}=e;f(e,()=>{r.$comment&&t.$comment&&b(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,p.checkStrictMode)(e,"default is ignored in the schema root")}(e),s.let(l.default.vErrors,null),s.let(l.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",u._`${r}.evaluated`),t.if(u._`${e.evaluated}.dynamicProps`,()=>t.assign(u._`${e.evaluated}.props`,u._`undefined`)),t.if(u._`${e.evaluated}.dynamicItems`,()=>t.assign(u._`${e.evaluated}.items`,u._`undefined`))}(e),w(e),function(e){const{gen:t,schemaEnv:r,validateName:s,ValidationError:n,opts:i}=e;r.$async?t.if(u._`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw(u._`new ${n}(${l.default.vErrors})`)):(t.assign(u._`${s}.errors`,l.default.vErrors),i.unevaluated&&function({gen:e,evaluated:t,props:r,items:s}){r instanceof u.Name&&e.assign(u._`${t}.props`,r),s instanceof u.Name&&e.assign(u._`${t}.items`,s)}(e),t.return(u._`${l.default.errors} === 0`))}(e)})}(e):f(e,()=>(0,s.topBoolOrEmptySchema)(e))};class T{constructor(e,t,r){if((0,c.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,p.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",R(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,c.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",l.default.errors))}result(e,t,r){this.failResult((0,u.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,u.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(u._`${t} !== undefined && (${(0,u.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?m.reportExtraError:m.reportError)(this,this.def.error,t)}$dataError(){(0,m.reportError)(this,this.def.$dataError||m.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,m.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,r=u.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=u.nil,t=u.nil){if(!this.$data)return;const{gen:r,schemaCode:s,schemaType:n,def:i}=this;r.if((0,u.or)(u._`${s} === undefined`,t)),e!==u.nil&&r.assign(e,!0),(n.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==u.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:s,it:n}=this;return(0,u.or)(function(){if(r.length){if(!(t instanceof u.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return u._`${(0,a.checkDataTypes)(e,t,n.opts.strictNumbers,a.DataType.Wrong)}`}return u.nil}(),function(){if(s.validateSchema){const r=e.scopeValue("validate$data",{ref:s.validateSchema});return u._`!${r}(${t})`}return u.nil}())}subschema(e,t){const r=(0,d.getSubschema)(this.it,e);(0,d.extendSubschemaData)(r,this.it,e),(0,d.extendSubschemaMode)(r,e);const n={...this.it,...r,items:void 0,props:void 0};return function(e,t){y(e)&&(v(e),_(e))?function(e,t){const{schema:r,gen:s,opts:n}=e;n.$comment&&r.$comment&&b(e),function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,h.resolveUrl)(e.opts.uriResolver,e.baseId,t))}(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const i=s.const("_errs",l.default.errors);w(e,i),s.var(t,u._`${i} === ${l.default.errors}`)}(e,t):(0,s.boolOrEmptySchema)(e,t)}(n,t),n}mergeEvaluated(e,t){const{it:r,gen:s}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=p.mergeEvaluated.props(s,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=p.mergeEvaluated.items(s,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:s}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return s.if(t,()=>this.mergeEvaluated(e,u.Name)),!0}}function x(e,t,r,s){const n=new T(e,r,t);"code"in r?r.code(n,s):n.$data&&r.validate?(0,c.funcKeywordCode)(n,r):"macro"in r?(0,c.macroKeywordCode)(n,r):(r.compile||r.validate)&&(0,c.funcKeywordCode)(n,r)}t.KeywordCxt=T;const P=/^\/(?:[^~]|~0|~1)*$/,I=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function R(e,{dataLevel:t,dataNames:r,dataPathArr:s}){let n,i;if(""===e)return l.default.rootData;if("/"===e[0]){if(!P.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);n=e,i=l.default.rootData}else{const a=I.exec(e);if(!a)throw new Error(`Invalid JSON-pointer: ${e}`);const o=+a[1];if(n=a[2],"#"===n){if(o>=t)throw new Error(c("property/index",o));return s[t-o]}if(o>t)throw new Error(c("data",o));if(i=r[t-o],!n)return i}let a=i;const o=n.split("/");for(const e of o)e&&(i=u._`${i}${(0,u.getProperty)((0,p.unescapeJsonPointer)(e))}`,a=u._`${a} && ${i}`);return a;function c(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}t.getData=R},3740:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;const s=r(7346),n=r(1980),i=r(6596),a=r(6670),o=r(1430),c=r(9048),d={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:r,it:n}=e,{baseId:a,schemaEnv:c,validateName:d,opts:h,self:p}=n,{root:m}=c;if(("#"===r||"#/"===r)&&a===m.baseId)return function(){if(c===m)return l(e,d,c,c.$async);const r=t.scopeValue("root",{ref:m});return l(e,i._`${r}.validate`,m,m.$async)}();const f=o.resolveRef.call(p,m,a,r);if(void 0===f)throw new s.default(n.opts.uriResolver,a,r);return f instanceof o.SchemaEnv?function(t){const r=u(e,t);l(e,r,t,t.$async)}(f):function(s){const n=t.scopeValue("schema",!0===h.code.source?{ref:s,code:(0,i.stringify)(s)}:{ref:s}),a=t.name("valid"),o=e.subschema({schema:s,dataTypes:[],schemaPath:i.nil,topSchemaRef:n,errSchemaPath:r},a);e.mergeEvaluated(o),e.ok(a)}(f)}};function u(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):i._`${r.scopeValue("wrapper",{ref:t})}.validate`}function l(e,t,r,s){const{gen:o,it:d}=e,{allErrors:u,schemaEnv:l,opts:h}=d,p=h.passContext?a.default.this:i.nil;function m(e){const t=i._`${e}.errors`;o.assign(a.default.vErrors,i._`${a.default.vErrors} === null ? ${t} : ${a.default.vErrors}.concat(${t})`),o.assign(a.default.errors,i._`${a.default.vErrors}.length`)}function f(e){var t;if(!d.opts.unevaluated)return;const s=null===(t=null==r?void 0:r.validate)||void 0===t?void 0:t.evaluated;if(!0!==d.props)if(s&&!s.dynamicProps)void 0!==s.props&&(d.props=c.mergeEvaluated.props(o,s.props,d.props));else{const t=o.var("props",i._`${e}.evaluated.props`);d.props=c.mergeEvaluated.props(o,t,d.props,i.Name)}if(!0!==d.items)if(s&&!s.dynamicItems)void 0!==s.items&&(d.items=c.mergeEvaluated.items(o,s.items,d.items));else{const t=o.var("items",i._`${e}.evaluated.items`);d.items=c.mergeEvaluated.items(o,t,d.items,i.Name)}}s?function(){if(!l.$async)throw new Error("async schema referenced by sync schema");const r=o.let("valid");o.try(()=>{o.code(i._`await ${(0,n.callValidateCode)(e,t,p)}`),f(t),u||o.assign(r,!0)},e=>{o.if(i._`!(${e} instanceof ${d.ValidationError})`,()=>o.throw(e)),m(e),u||o.assign(r,!1)}),e.ok(r)}():e.result((0,n.callValidateCode)(e,t,p),()=>f(t),()=>m(t))}t.getValidate=u,t.callRef=l,t.default=d},3781:function(e,t){Object.defineProperty(t,"__esModule",{value:!0});class r extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}t.default=r},4026:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>s.str`must match format "${e}"`,params:({schemaCode:e})=>s._`{format: ${e}}`},code(e,t){const{gen:r,data:n,$data:i,schema:a,schemaCode:o,it:c}=e,{opts:d,errSchemaPath:u,schemaEnv:l,self:h}=c;d.validateFormats&&(i?function(){const i=r.scopeValue("formats",{ref:h.formats,code:d.code.formats}),a=r.const("fDef",s._`${i}[${o}]`),c=r.let("fType"),u=r.let("format");r.if(s._`typeof ${a} == "object" && !(${a} instanceof RegExp)`,()=>r.assign(c,s._`${a}.type || "string"`).assign(u,s._`${a}.validate`),()=>r.assign(c,s._`"string"`).assign(u,a)),e.fail$data((0,s.or)(!1===d.strictSchema?s.nil:s._`${o} && !${u}`,function(){const e=l.$async?s._`(${a}.async ? await ${u}(${n}) : ${u}(${n}))`:s._`${u}(${n})`,r=s._`(typeof ${u} == "function" ? ${e} : ${u}.test(${n}))`;return s._`${u} && ${u} !== true && ${c} === ${t} && !${r}`}()))}():function(){const i=h.formats[a];if(!i)return void function(){if(!1!==d.strictSchema)throw new Error(e());function e(){return`unknown format "${a}" ignored in schema at path "${u}"`}h.logger.warn(e())}();if(!0===i)return;const[o,c,p]=function(e){const t=e instanceof RegExp?(0,s.regexpCode)(e):d.code.formats?s._`${d.code.formats}${(0,s.getProperty)(a)}`:void 0,n=r.scopeValue("formats",{key:a,ref:e,code:t});return"object"!=typeof e||e instanceof RegExp?["string",e,n]:[e.type||"string",e.validate,s._`${n}.validate`]}(i);o===t&&e.pass(function(){if("object"==typeof i&&!(i instanceof RegExp)&&i.async){if(!l.$async)throw new Error("async format in sync schema");return s._`await ${p}(${n})`}return"function"==typeof c?s._`${p}(${n})`:s._`${p}.test(${n})`}())}())}};t.default=n},4076:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>s.str`must be multiple of ${e}`,params:({schemaCode:e})=>s._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:n,it:i}=e,a=i.opts.multipleOfPrecision,o=t.let("res"),c=a?s._`Math.abs(Math.round(${o}) - ${o}) > 1e-${a}`:s._`${o} !== parseInt(${o})`;e.fail$data(s._`(${n} === 0 || (${o} = ${r}/${n}, ${c}))`)}};t.default=n},4176:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n=r(9048),i={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>s.str`must match "${e.ifClause}" schema`,params:({params:e})=>s._`{failingKeyword: ${e.ifClause}}`},code(e){const{gen:t,parentSchema:r,it:i}=e;void 0===r.then&&void 0===r.else&&(0,n.checkStrictMode)(i,'"if" without "then" and "else" is ignored');const o=a(i,"then"),c=a(i,"else");if(!o&&!c)return;const d=t.let("valid",!0),u=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}(),e.reset(),o&&c){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(u,l("then",r),l("else",r))}else o?t.if(u,l("then")):t.if((0,s.not)(u),l("else"));function l(r,n){return()=>{const i=e.subschema({keyword:r},u);t.assign(d,u),e.mergeValidEvaluated(i,d),n?t.assign(n,s._`${r}`):e.setParams({ifClause:r})}}e.pass(d,()=>e.error(!0))}};function a(e,t){const r=e.schema[t];return void 0!==r&&!(0,n.alwaysValidSchema)(e,r)}t.default=i},4362:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const s=r(6596),n=r(9048),i=r(1980);t.error={message:({params:{property:e,depsCount:t,deps:r}})=>{const n=1===t?"property":"properties";return s.str`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>s._`{property: ${e}, missingProperty: ${n}, depsCount: ${t}, deps: ${r}}`};const a={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const s in e)"__proto__"!==s&&((Array.isArray(e[s])?t:r)[s]=e[s]);return[t,r]}(e);o(e,t),c(e,r)}};function o(e,t=e.schema){const{gen:r,data:n,it:a}=e;if(0===Object.keys(t).length)return;const o=r.let("missing");for(const c in t){const d=t[c];if(0===d.length)continue;const u=(0,i.propertyInData)(r,n,c,a.opts.ownProperties);e.setParams({property:c,depsCount:d.length,deps:d.join(", ")}),a.allErrors?r.if(u,()=>{for(const t of d)(0,i.checkReportMissingProp)(e,t)}):(r.if(s._`${u} && (${(0,i.checkMissingProp)(e,d,o)})`),(0,i.reportMissingProp)(e,o),r.else())}}function c(e,t=e.schema){const{gen:r,data:s,keyword:a,it:o}=e,c=r.name("valid");for(const d in t)(0,n.alwaysValidSchema)(o,t[d])||(r.if((0,i.propertyInData)(r,s,d,o.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:d},c);e.mergeValidEvaluated(t,c)},()=>r.var(c,!0)),e.ok(c))}t.validatePropertyDeps=o,t.validateSchemaDeps=c,t.default=a},4368:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(1980),n=r(6596),i=r(9048),a=r(9048),o={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:o,parentSchema:c,it:d}=e,{opts:u}=d,l=(0,s.allSchemaProperties)(r),h=l.filter(e=>(0,i.alwaysValidSchema)(d,r[e]));if(0===l.length||h.length===l.length&&(!d.opts.unevaluated||!0===d.props))return;const p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=t.name("valid");!0===d.props||d.props instanceof n.Name||(d.props=(0,a.evaluatedPropsToName)(t,d.props));const{props:f}=d;function g(e){for(const t in p)new RegExp(e).test(t)&&(0,i.checkStrictMode)(d,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function _(r){t.forIn("key",o,i=>{t.if(n._`${(0,s.usePattern)(e,r)}.test(${i})`,()=>{const s=h.includes(r);s||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:i,dataPropType:a.Type.Str},m),d.opts.unevaluated&&!0!==f?t.assign(n._`${f}[${i}]`,!0):s||d.allErrors||t.if((0,n.not)(m),()=>t.break())})})}!function(){for(const e of l)p&&g(e),d.allErrors?_(e):(t.var(m,!0),_(e),t.if(m))}()}};t.default=o},4560:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(1980),n=r(6596),i=r(9048),a={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>n.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>n._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:r,schemaCode:a,data:o,$data:c,it:d}=e,{opts:u}=d;if(!c&&0===r.length)return;const l=r.length>=u.loopRequired;if(d.allErrors?function(){if(l||c)e.block$data(n.nil,h);else for(const t of r)(0,s.checkReportMissingProp)(e,t)}():function(){const i=t.let("missing");if(l||c){const r=t.let("valid",!0);e.block$data(r,()=>function(r,i){e.setParams({missingProperty:r}),t.forOf(r,a,()=>{t.assign(i,(0,s.propertyInData)(t,o,r,u.ownProperties)),t.if((0,n.not)(i),()=>{e.error(),t.break()})},n.nil)}(i,r)),e.ok(r)}else t.if((0,s.checkMissingProp)(e,r,i)),(0,s.reportMissingProp)(e,i),t.else()}(),u.strictRequired){const t=e.parentSchema.properties,{definedProperties:s}=e.it;for(const e of r)if(void 0===(null==t?void 0:t[e])&&!s.has(e)){const t=`required property "${e}" is not defined at "${d.schemaEnv.baseId+d.errSchemaPath}" (strictRequired)`;(0,i.checkStrictMode)(d,t,d.opts.strictRequired)}}function h(){t.forOf("prop",a,r=>{e.setParams({missingProperty:r}),t.if((0,s.noPropertyInData)(t,o,r,u.ownProperties),()=>e.error())})}}};t.default=a},4834:function(e){const t=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function s(e){let t="",r=0,s=0;for(s=0;s<e.length;s++)if(r=e[s].charCodeAt(0),48!==r){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[s];break}for(s+=1;s<e.length;s++){if(r=e[s].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[s]}return t}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function i(e){return e.length=0,!0}function a(e,t,r){if(e.length){const n=s(e);if(""===n)return r.error=!0,!1;t.push(n),e.length=0}return!0}function o(e){if(function(e){let t=0;for(let r=0;r<e.length;r++)":"===e[r]&&t++;return t}(e)<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const r={error:!1,address:"",zone:""},n=[],o=[];let c=!1,d=!1,u=a;for(let s=0;s<e.length;s++){const a=e[s];if("["!==a&&"]"!==a)if(":"!==a)if("%"===a){if(!u(o,n,r))break;u=i}else o.push(a);else{if(!0===c&&(d=!0),!u(o,n,r))break;if(++t>7){r.error=!0;break}s>0&&":"===e[s-1]&&(c=!0),n.push(":")}}return o.length&&(u===i?r.zone=o.join(""):d?n.push(o.join("")):n.push(s(o))),r.address=n.join(""),r}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,r=t.address;return t.zone&&(e+="%"+t.zone,r+="%25"+t.zone),{host:e,isIPV6:!0,escapedHost:r}}}e.exports={nonSimpleDomain:n,recomposeAuthority:function(e){const t=[];if(void 0!==e.userinfo&&(t.push(e.userinfo),t.push("@")),void 0!==e.host){let s=unescape(e.host);if(!r(s)){const t=o(s);s=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}t.push(s)}return"number"!=typeof e.port&&"string"!=typeof e.port||(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0},normalizeComponentEncoding:function(e,t){const r=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=r(e.scheme)),void 0!==e.userinfo&&(e.userinfo=r(e.userinfo)),void 0!==e.host&&(e.host=r(e.host)),void 0!==e.path&&(e.path=r(e.path)),void 0!==e.query&&(e.query=r(e.query)),void 0!==e.fragment&&(e.fragment=r(e.fragment)),e},removeDotSegments:function(e){let t=e;const r=[];let s=-1,n=0;for(;n=t.length;){if(1===n){if("."===t)break;if("/"===t){r.push("/");break}r.push(t);break}if(2===n){if("."===t[0]){if("."===t[1])break;if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&("."===t[1]||"/"===t[1])){r.push("/");break}}else if(3===n&&"/.."===t){0!==r.length&&r.pop(),r.push("/");break}if("."===t[0]){if("."===t[1]){if("/"===t[2]){t=t.slice(3);continue}}else if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&"."===t[1]){if("/"===t[2]){t=t.slice(2);continue}if("."===t[2]&&"/"===t[3]){t=t.slice(3),0!==r.length&&r.pop();continue}}if(-1===(s=t.indexOf("/",1))){r.push(t);break}r.push(t.slice(0,s)),t=t.slice(s)}return r.join("")},isIPv4:r,isUUID:t,normalizeIPv6:o,stringArrayToHexStripped:s}},4946:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(3697),n=r(1980),i=r(9048),a=r(2327),o={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:o,data:c,it:d}=e;"all"===d.opts.removeAdditional&&void 0===o.additionalProperties&&a.default.code(new s.KeywordCxt(d,a.default,"additionalProperties"));const u=(0,n.allSchemaProperties)(r);for(const e of u)d.definedProperties.add(e);d.opts.unevaluated&&u.length&&!0!==d.props&&(d.props=i.mergeEvaluated.props(t,(0,i.toHash)(u),d.props));const l=u.filter(e=>!(0,i.alwaysValidSchema)(d,r[e]));if(0===l.length)return;const h=t.name("valid");for(const r of l)p(r)?m(r):(t.if((0,n.propertyInData)(t,c,r,d.opts.ownProperties)),m(r),d.allErrors||t.else().var(h,!0),t.endIf()),e.it.definedProperties.add(r),e.ok(h);function p(e){return d.opts.useDefaults&&!d.compositeRule&&void 0!==r[e].default}function m(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},h)}}};t.default=o},4971:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const s=r(6596),n=r(9048),i=r(6670);function a(e,t){const r=e.const("err",t);e.if(s._`${i.default.vErrors} === null`,()=>e.assign(i.default.vErrors,s._`[${r}]`),s._`${i.default.vErrors}.push(${r})`),e.code(s._`${i.default.errors}++`)}function o(e,t){const{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw(s._`new ${e.ValidationError}(${t})`):(r.assign(s._`${n}.errors`,t),r.return(!1))}t.keywordError={message:({keyword:e})=>s.str`must pass "${e}" keyword validation`},t.keyword$DataError={message:({keyword:e,schemaType:t})=>t?s.str`"${e}" keyword must be ${t} ($data)`:s.str`"${e}" keyword is invalid ($data)`},t.reportError=function(e,r=t.keywordError,n,i){const{it:c}=e,{gen:u,compositeRule:l,allErrors:h}=c,p=d(e,r,n);(null!=i?i:l||h)?a(u,p):o(c,s._`[${p}]`)},t.reportExtraError=function(e,r=t.keywordError,s){const{it:n}=e,{gen:c,compositeRule:u,allErrors:l}=n;a(c,d(e,r,s)),u||l||o(n,i.default.vErrors)},t.resetErrorsCount=function(e,t){e.assign(i.default.errors,t),e.if(s._`${i.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(s._`${i.default.vErrors}.length`,t),()=>e.assign(i.default.vErrors,null)))},t.extendErrors=function({gen:e,keyword:t,schemaValue:r,data:n,errsCount:a,it:o}){if(void 0===a)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",a,i.default.errors,a=>{e.const(c,s._`${i.default.vErrors}[${a}]`),e.if(s._`${c}.instancePath === undefined`,()=>e.assign(s._`${c}.instancePath`,(0,s.strConcat)(i.default.instancePath,o.errorPath))),e.assign(s._`${c}.schemaPath`,s.str`${o.errSchemaPath}/${t}`),o.opts.verbose&&(e.assign(s._`${c}.schema`,r),e.assign(s._`${c}.data`,n))})};const c={keyword:new s.Name("keyword"),schemaPath:new s.Name("schemaPath"),params:new s.Name("params"),propertyName:new s.Name("propertyName"),message:new s.Name("message"),schema:new s.Name("schema"),parentSchema:new s.Name("parentSchema")};function d(e,t,r){const{createErrors:n}=e.it;return!1===n?s._`{}`:function(e,t,r={}){const{gen:n,it:a}=e,o=[u(a,r),l(e,r)];return function(e,{params:t,message:r},n){const{keyword:a,data:o,schemaValue:d,it:u}=e,{opts:l,propertyName:h,topSchemaRef:p,schemaPath:m}=u;n.push([c.keyword,a],[c.params,"function"==typeof t?t(e):t||s._`{}`]),l.messages&&n.push([c.message,"function"==typeof r?r(e):r]),l.verbose&&n.push([c.schema,d],[c.parentSchema,s._`${p}${m}`],[i.default.data,o]),h&&n.push([c.propertyName,h])}(e,t,o),n.object(...o)}(e,t,r)}function u({errorPath:e},{instancePath:t}){const r=t?s.str`${e}${(0,n.getErrorPath)(t,n.Type.Str)}`:e;return[i.default.instancePath,(0,s.strConcat)(i.default.instancePath,r)]}function l({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:i}){let a=i?t:s.str`${t}/${e}`;return r&&(a=s.str`${a}${(0,n.getErrorPath)(r,n.Type.Str)}`),[c.schemaPath,a]}},4994:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n=r(9048),i={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:e})=>s._`{passingSchemas: ${e.passing}}`},code(e){const{gen:t,schema:r,parentSchema:i,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(a.opts.discriminator&&i.discriminator)return;const o=r,c=t.let("valid",!1),d=t.let("passing",null),u=t.name("_valid");e.setParams({passing:d}),t.block(function(){o.forEach((r,i)=>{let o;(0,n.alwaysValidSchema)(a,r)?t.var(u,!0):o=e.subschema({keyword:"oneOf",schemaProp:i,compositeRule:!0},u),i>0&&t.if(s._`${u} && ${c}`).assign(c,!1).assign(d,s._`[${d}, ${i}]`).else(),t.if(u,()=>{t.assign(c,!0),t.assign(d,i),o&&e.mergeEvaluated(o,s.Name)})})}),e.result(c,()=>e.reset(),()=>e.error(!0))}};t.default=i},5105:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(8851),n=r(4076),i=r(2010),a=r(3663),o=r(6359),c=r(4560),d=r(5584),u=r(1828),l=r(1234),h=r(3144),p=[s.default,n.default,i.default,a.default,o.default,c.default,d.default,u.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,h.default];t.default=p},5143:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(323),n=r(6492),i=r(6596),a=new i.Name("fullFormats"),o=new i.Name("fastFormats"),c=(e,t={keywords:!0})=>{if(Array.isArray(t))return d(e,t,s.fullFormats,a),e;const[r,i]="fast"===t.mode?[s.fastFormats,o]:[s.fullFormats,a];return d(e,t.formats||s.formatNames,r,i),t.keywords&&(0,n.default)(e),e};function d(e,t,r,s){var n,a;null!==(n=(a=e.opts.code).formats)&&void 0!==n||(a.formats=i._`require("ajv-formats/dist/formats").${s}`);for(const s of t)e.addFormat(s,r[s])}c.get=(e,t="full")=>{const r=("fast"===t?s.fastFormats:s.fullFormats)[e];if(!r)throw new Error(`Unknown format "${e}"`);return r},e.exports=t=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c},5215:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(8592),n=r(8171),i=r(6519),a=r(7879),o=r(1070),c=r(4362),d=r(340),u=r(2327),l=r(4946),h=r(4368),p=r(1526),m=r(6972),f=r(4994),g=r(3501),_=r(4176),y=r(2149);t.default=function(e=!1){const t=[p.default,m.default,f.default,g.default,_.default,y.default,d.default,u.default,c.default,l.default,h.default];return e?t.push(n.default,a.default):t.push(s.default,i.default),t.push(o.default),t}},5311:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(2017);s.code='require("ajv/dist/runtime/equal").default',t.default=s},5584:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const r="maxItems"===e?"more":"fewer";return s.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>s._`{limit: ${e}}`},code(e){const{keyword:t,data:r,schemaCode:n}=e,i="maxItems"===t?s.operators.GT:s.operators.LT;e.fail$data(s._`${r}.length ${i} ${n}`)}};t.default=n},5870:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n=r(8451),i=r(1430),a=r(7346),o=r(9048),c={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>s._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},code(e){const{gen:t,data:r,schema:c,parentSchema:d,it:u}=e,{oneOf:l}=d;if(!u.opts.discriminator)throw new Error("discriminator: requires discriminator option");const h=c.propertyName;if("string"!=typeof h)throw new Error("discriminator: requires propertyName");if(c.mapping)throw new Error("discriminator: mapping is not supported");if(!l)throw new Error("discriminator: requires oneOf keyword");const p=t.let("valid",!1),m=t.const("tag",s._`${r}${(0,s.getProperty)(h)}`);function f(r){const n=t.name("valid"),i=e.subschema({keyword:"oneOf",schemaProp:r},n);return e.mergeEvaluated(i,s.Name),n}t.if(s._`typeof ${m} == "string"`,()=>function(){const r=function(){var e;const t={},r=n(d);let s=!0;for(let t=0;t<l.length;t++){let d=l[t];if((null==d?void 0:d.$ref)&&!(0,o.schemaHasRulesButRef)(d,u.self.RULES)){const e=d.$ref;if(d=i.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),d instanceof i.SchemaEnv&&(d=d.schema),void 0===d)throw new a.default(u.opts.uriResolver,u.baseId,e)}const p=null===(e=null==d?void 0:d.properties)||void 0===e?void 0:e[h];if("object"!=typeof p)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);s=s&&(r||n(d)),c(p,t)}if(!s)throw new Error(`discriminator: "${h}" must be required`);return t;function n({required:e}){return Array.isArray(e)&&e.includes(h)}function c(e,t){if(e.const)p(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${h}" must have "const" or "enum"`);for(const r of e.enum)p(r,t)}}function p(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${h}" values must be unique strings`);t[e]=r}}();t.if(!1);for(const e in r)t.elseIf(s._`${m} === ${e}`),t.assign(p,f(r[e]));t.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:h}),t.endIf()}(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:h})),e.ok(p)}};t.default=c},5962:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;const s=r(4971),n=r(6596),i=r(6670),a={message:"boolean schema is false"};function o(e,t){const{gen:r,data:n}=e,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,s.reportError)(i,a,void 0,t)}t.topBoolOrEmptySchema=function(e){const{gen:t,schema:r,validateName:s}=e;!1===r?o(e,!1):"object"==typeof r&&!0===r.$async?t.return(i.default.data):(t.assign(n._`${s}.errors`,null),t.return(!0))},t.boolOrEmptySchema=function(e,t){const{gen:r,schema:s}=e;!1===s?(r.var(t,!1),o(e)):r.var(t,!0)}},6158:function(e,t){function r(e){const t=e.length;let r,s=0,n=0;for(;n<t;)s++,r=e.charCodeAt(n++),r>=55296&&r<=56319&&n<t&&(r=e.charCodeAt(n),56320==(64512&r)&&n++);return s}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r,r.code='require("ajv/dist/runtime/ucs2length").default'},6359:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const r="maxProperties"===e?"more":"fewer";return s.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>s._`{limit: ${e}}`},code(e){const{keyword:t,data:r,schemaCode:n}=e,i="maxProperties"===t?s.operators.GT:s.operators.LT;e.fail$data(s._`Object.keys(${r}).length ${i} ${n}`)}};t.default=n},6492:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const s=r(647),n=r(6596),i=n.operators,a={formatMaximum:{okStr:"<=",ok:i.LTE,fail:i.GT},formatMinimum:{okStr:">=",ok:i.GTE,fail:i.LT},formatExclusiveMaximum:{okStr:"<",ok:i.LT,fail:i.GTE},formatExclusiveMinimum:{okStr:">",ok:i.GT,fail:i.LTE}},o={message:({keyword:e,schemaCode:t})=>n.str`should be ${a[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>n._`{comparison: ${a[e].okStr}, limit: ${t}}`};t.formatLimitDefinition={keyword:Object.keys(a),type:"string",schemaType:"string",$data:!0,error:o,code(e){const{gen:t,data:r,schemaCode:i,keyword:o,it:c}=e,{opts:d,self:u}=c;if(!d.validateFormats)return;const l=new s.KeywordCxt(c,u.RULES.all.format.definition,"format");function h(e){return n._`${e}.compare(${r}, ${i}) ${a[o].fail} 0`}l.$data?function(){const r=t.scopeValue("formats",{ref:u.formats,code:d.code.formats}),s=t.const("fmt",n._`${r}[${l.schemaCode}]`);e.fail$data((0,n.or)(n._`typeof ${s} != "object"`,n._`${s} instanceof RegExp`,n._`typeof ${s}.compare != "function"`,h(s)))}():function(){const r=l.schema,s=u.formats[r];if(!s||!0===s)return;if("object"!=typeof s||s instanceof RegExp||"function"!=typeof s.compare)throw new Error(`"${o}": format "${r}" does not define "compare" function`);const i=t.scopeValue("formats",{key:r,ref:s,code:d.code.formats?n._`${d.code.formats}${(0,n.getProperty)(r)}`:void 0});e.fail$data(h(i))}()},dependencies:["format"]},t.default=e=>(e.addKeyword(t.formatLimitDefinition),e)},6501:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(8343);s.code='require("ajv/dist/runtime/uri").default',t.default=s},6519:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;const s=r(6596),n=r(9048),i=r(1980),a={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return o(e,"additionalItems",t);r.items=!0,(0,n.alwaysValidSchema)(r,t)||e.ok((0,i.validateArray)(e))}};function o(e,t,r=e.schema){const{gen:i,parentSchema:a,data:o,keyword:c,it:d}=e;!function(e){const{opts:s,errSchemaPath:i}=d,a=r.length,o=a===e.minItems&&(a===e.maxItems||!1===e[t]);if(s.strictTuples&&!o){const e=`"${c}" is ${a}-tuple, but minItems or maxItems/${t} are not specified or different at path "${i}"`;(0,n.checkStrictMode)(d,e,s.strictTuples)}}(a),d.opts.unevaluated&&r.length&&!0!==d.items&&(d.items=n.mergeEvaluated.items(i,r.length,d.items));const u=i.name("valid"),l=i.const("len",s._`${o}.length`);r.forEach((t,r)=>{(0,n.alwaysValidSchema)(d,t)||(i.if(s._`${l} > ${r}`,()=>e.subschema({keyword:c,schemaProp:r,dataProp:r},u)),e.ok(u))})}t.validateTuple=o,t.default=a},6545:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=[r(4026).default];t.default=s},6596:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const s=r(3231),n=r(6692);var i=r(3231);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return i.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return i.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return i.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return i.Name}});var a=r(6692);Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return a.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return a.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return a.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return a.varKinds}}),t.operators={GT:new s._Code(">"),GTE:new s._Code(">="),LT:new s._Code("<"),LTE:new s._Code("<="),EQ:new s._Code("==="),NEQ:new s._Code("!=="),NOT:new s._Code("!"),OR:new s._Code("||"),AND:new s._Code("&&"),ADD:new s._Code("+")};class o{optimizeNodes(){return this}optimizeNames(e,t){return this}}class c extends o{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){const r=e?n.varKinds.var:this.varKind,s=void 0===this.rhs?"":` = ${this.rhs}`;return`${r} ${this.name}${s};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=O(this.rhs,e,t)),this}get names(){return this.rhs instanceof s._CodeOrName?this.rhs.names:{}}}class d extends o{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof s.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=O(this.rhs,e,t),this}get names(){return R(this.lhs instanceof s.Name?{}:{...this.lhs.names},this.rhs)}}class u extends d{constructor(e,t,r,s){super(e,r,s),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class l extends o{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class h extends o{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class p extends o{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class m extends o{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=O(this.code,e,t),this}get names(){return this.code instanceof s._CodeOrName?this.code.names:{}}}class f extends o{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:r}=this;let s=r.length;for(;s--;){const n=r[s];n.optimizeNames(e,t)||(C(e,n.names),r.splice(s,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>I(e,t.names),{})}}class g extends f{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class _ extends f{}class y extends g{}y.kind="else";class v extends g{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new y(e):e}return t?!1===e?t instanceof v?t:t.nodes:this.nodes.length?this:new v(A(e),t instanceof v?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null===(r=this.else)||void 0===r?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=O(this.condition,e,t),this}get names(){const e=super.names;return R(e,this.condition),this.else&&I(e,this.else.names),e}}v.kind="if";class w extends g{}w.kind="for";class b extends w{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=O(this.iteration,e,t),this}get names(){return I(super.names,this.iteration.names)}}class k extends w{constructor(e,t,r,s){super(),this.varKind=e,this.name=t,this.from=r,this.to=s}render(e){const t=e.es5?n.varKinds.var:this.varKind,{name:r,from:s,to:i}=this;return`for(${t} ${r}=${s}; ${r}<${i}; ${r}++)`+super.render(e)}get names(){const e=R(super.names,this.from);return R(e,this.to)}}class S extends w{constructor(e,t,r,s){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=O(this.iterable,e,t),this}get names(){return I(super.names,this.iterable.names)}}class $ extends g{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}$.kind="func";class E extends f{render(e){return"return "+super.render(e)}}E.kind="return";class T extends g{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var r,s;return super.optimizeNames(e,t),null===(r=this.catch)||void 0===r||r.optimizeNames(e,t),null===(s=this.finally)||void 0===s||s.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&I(e,this.catch.names),this.finally&&I(e,this.finally.names),e}}class x extends g{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}x.kind="catch";class P extends g{render(e){return"finally"+super.render(e)}}function I(e,t){for(const r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function R(e,t){return t instanceof s._CodeOrName?I(e,t.names):e}function O(e,t,r){return e instanceof s.Name?i(e):(n=e)instanceof s._Code&&n._items.some(e=>e instanceof s.Name&&1===t[e.str]&&void 0!==r[e.str])?new s._Code(e._items.reduce((e,t)=>(t instanceof s.Name&&(t=i(t)),t instanceof s._Code?e.push(...t._items):e.push(t),e),[])):e;var n;function i(e){const s=r[e.str];return void 0===s||1!==t[e.str]?e:(delete t[e.str],s)}}function C(e,t){for(const r in t)e[r]=(e[r]||0)-(t[r]||0)}function A(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:s._`!${M(e)}`}P.kind="finally",t.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new _]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,s){const n=this._scope.toName(t);return void 0!==r&&s&&(this._constants[n.str]=r),this._leafNode(new c(e,n,r)),n}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new d(e,t,r))}add(e,r){return this._leafNode(new u(e,t.operators.ADD,r))}code(e){return"function"==typeof e?e():e!==s.nil&&this._leafNode(new m(e)),this}object(...e){const t=["{"];for(const[r,n]of e)t.length>1&&t.push(","),t.push(r),(r!==n||this.opts.es5)&&(t.push(":"),(0,s.addCodeArg)(t,n));return t.push("}"),new s._Code(t)}if(e,t,r){if(this._blockNode(new v(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new v(e))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(v,y)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new b(e),t)}forRange(e,t,r,s,i=(this.opts.es5?n.varKinds.var:n.varKinds.let)){const a=this._scope.toName(e);return this._for(new k(i,a,t,r),()=>s(a))}forOf(e,t,r,i=n.varKinds.const){const a=this._scope.toName(e);if(this.opts.es5){const e=t instanceof s.Name?t:this.var("_arr",t);return this.forRange("_i",0,s._`${e}.length`,t=>{this.var(a,s._`${e}[${t}]`),r(a)})}return this._for(new S("of",i,a,t),()=>r(a))}forIn(e,t,r,i=(this.opts.es5?n.varKinds.var:n.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,s._`Object.keys(${t})`,r);const a=this._scope.toName(e);return this._for(new S("in",i,a,t),()=>r(a))}endFor(){return this._endBlockNode(w)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new h(e))}return(e){const t=new E;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(E)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');const s=new T;if(this._blockNode(s),this.code(e),t){const e=this.name("e");this._currNode=s.catch=new x(e),t(e)}return r&&(this._currNode=s.finally=new P,this.code(r)),this._endBlockNode(x,P)}throw(e){return this._leafNode(new p(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=s.nil,r,n){return this._blockNode(new $(e,t,r)),n&&this.code(n).endFunc(),this}endFunc(){return this._endBlockNode($)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof v))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},t.not=A;const N=z(t.operators.AND);t.and=function(...e){return e.reduce(N)};const j=z(t.operators.OR);function z(e){return(t,r)=>t===s.nil?r:r===s.nil?t:s._`${M(t)} ${e} ${M(r)}`}function M(e){return e instanceof s.Name?e:s._`(${e})`}t.or=function(...e){return e.reduce(j)}},6670:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n={data:new s.Name("data"),valCxt:new s.Name("valCxt"),instancePath:new s.Name("instancePath"),parentData:new s.Name("parentData"),parentDataProperty:new s.Name("parentDataProperty"),rootData:new s.Name("rootData"),dynamicAnchors:new s.Name("dynamicAnchors"),vErrors:new s.Name("vErrors"),errors:new s.Name("errors"),this:new s.Name("this"),self:new s.Name("self"),scope:new s.Name("scope"),json:new s.Name("json"),jsonPos:new s.Name("jsonPos"),jsonLen:new s.Name("jsonLen"),jsonPart:new s.Name("jsonPart")};t.default=n},6692:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const s=r(3231);class n extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var i;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(i||(t.UsedValueState=i={})),t.varKinds={const:new s.Name("const"),let:new s.Name("let"),var:new s.Name("var")};class a{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof s.Name?e:this.name(e)}name(e){return new s.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,r;if((null===(r=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===r?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}t.Scope=a;class o extends s.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=s._`.${new s.Name(t)}[${r}]`}}t.ValueScopeName=o;const c=s._`\n`;t.ValueScope=class extends a{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?c:s.nil}}get(){return this._scope}name(e){return new o(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const s=this.toName(e),{prefix:n}=s,i=null!==(r=t.key)&&void 0!==r?r:t.ref;let a=this._values[n];if(a){const e=a.get(i);if(e)return e}else a=this._values[n]=new Map;a.set(i,s);const o=this._scope[n]||(this._scope[n]=[]),c=o.length;return o[c]=t.ref,s.setValue(t,{property:n,itemIndex:c}),s}getValue(e,t){const r=this._values[e];if(r)return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,t=>{if(void 0===t.scopePath)throw new Error(`CodeGen: name "${t}" has no value`);return s._`${e}${t.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,r)}_reduceValues(e,r,a={},o){let c=s.nil;for(const d in e){const u=e[d];if(!u)continue;const l=a[d]=a[d]||new Map;u.forEach(e=>{if(l.has(e))return;l.set(e,i.Started);let a=r(e);if(a){const r=this.opts.es5?t.varKinds.var:t.varKinds.const;c=s._`${c}${r} ${e} = ${a};${this.opts._n}`}else{if(!(a=null==o?void 0:o(e)))throw new n(e);c=s._`${c}${a}${this.opts._n}`}l.set(e,i.Completed)})}return c}}},6836:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]},6972:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:r(1980).validateUnion,error:{message:"must match a schema in anyOf"}};t.default=s},7344:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;const s=r(6596),n=r(9048);t.getSubschema=function(e,{keyword:t,schemaProp:r,schema:i,schemaPath:a,errSchemaPath:o,topSchemaRef:c}){if(void 0!==t&&void 0!==i)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==t){const i=e.schema[t];return void 0===r?{schema:i,schemaPath:s._`${e.schemaPath}${(0,s.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:i[r],schemaPath:s._`${e.schemaPath}${(0,s.getProperty)(t)}${(0,s.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,n.escapeFragment)(r)}`}}if(void 0!==i){if(void 0===a||void 0===o||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:a,topSchemaRef:c,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')},t.extendSubschemaData=function(e,t,{dataProp:r,dataPropType:i,data:a,dataTypes:o,propertyName:c}){if(void 0!==a&&void 0!==r)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:d}=t;if(void 0!==r){const{errorPath:a,dataPathArr:o,opts:c}=t;u(d.let("data",s._`${t.data}${(0,s.getProperty)(r)}`,!0)),e.errorPath=s.str`${a}${(0,n.getErrorPath)(r,i,c.jsPropertySyntax)}`,e.parentDataProperty=s._`${r}`,e.dataPathArr=[...o,e.parentDataProperty]}function u(r){e.data=r,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,r]}void 0!==a&&(u(a instanceof s.Name?a:d.let("data",a,!0)),void 0!==c&&(e.propertyName=c)),o&&(e.dataTypes=o)},t.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:s,createErrors:n,allErrors:i}){void 0!==s&&(e.compositeRule=s),void 0!==n&&(e.createErrors=n),void 0!==i&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}},7346:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(978);class n extends Error{constructor(e,t,r,n){super(n||`can't resolve reference ${r} from id ${t}`),this.missingRef=(0,s.resolveUrl)(e,t,r),this.missingSchema=(0,s.normalizeId)((0,s.getFullPath)(e,this.missingRef))}}t.default=n},7879:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n=r(9048),i=r(1980),a=r(8592),o={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>s.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>s._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:s}=e,{prefixItems:o}=r;s.items=!0,(0,n.alwaysValidSchema)(s,t)||(o?(0,a.validateAdditionalItems)(e,o):e.ok((0,i.validateArray)(e)))}};t.default=o},8171:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6519),n={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,s.validateTuple)(e,"items")};t.default=n},8343:function(e,t,r){const{normalizeIPv6:s,removeDotSegments:n,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:c}=r(4834),{SCHEMES:d,getSchemeHandler:u}=r(343);function l(e,t,r,s){const i={};return s||(e=m(h(e,r),r),t=m(h(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(i.scheme=t.scheme,i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=n(t.path||""),i.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=n(t.path||""),i.query=t.query):(t.path?("/"===t.path[0]?i.path=n(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:i.path=t.path:i.path="/"+t.path,i.path=n(i.path)),i.query=t.query):(i.path=e.path,void 0!==t.query?i.query=t.query:i.query=e.query),i.userinfo=e.userinfo,i.host=e.host,i.port=e.port),i.scheme=e.scheme),i.fragment=t.fragment,i}function h(e,t){const r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},s=Object.assign({},t),a=[],o=u(s.scheme||r.scheme);o&&o.serialize&&o.serialize(r,s),void 0!==r.path&&(s.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),void 0!==r.scheme&&(r.path=r.path.split("%3A").join(":")))),"suffix"!==s.reference&&r.scheme&&a.push(r.scheme,":");const c=i(r);if(void 0!==c&&("suffix"!==s.reference&&a.push("//"),a.push(c),r.path&&"/"!==r.path[0]&&a.push("/")),void 0!==r.path){let e=r.path;s.absolutePath||o&&o.absolutePath||(e=n(e)),void 0===c&&"/"===e[0]&&"/"===e[1]&&(e="/%2F"+e.slice(2)),a.push(e)}return void 0!==r.query&&a.push("?",r.query),void 0!==r.fragment&&a.push("#",r.fragment),a.join("")}const p=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function m(e,t){const r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let i=!1;"suffix"===r.reference&&(e=r.scheme?r.scheme+":"+e:"//"+e);const a=e.match(p);if(a){if(n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]),n.host)if(!1===o(n.host)){const e=s(n.host);n.host=e.host.toLowerCase(),i=e.isIPV6}else i=!0;void 0!==n.scheme||void 0!==n.userinfo||void 0!==n.host||void 0!==n.port||void 0!==n.query||n.path?void 0===n.scheme?n.reference="relative":void 0===n.fragment?n.reference="absolute":n.reference="uri":n.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");const t=u(r.scheme||n.scheme);if(!(r.unicodeSupport||t&&t.unicodeSupport)&&n.host&&(r.domainHost||t&&t.domainHost)&&!1===i&&c(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(e){n.error=n.error||"Host's domain name can not be converted to ASCII: "+e}(!t||t&&!t.skipNormalize)&&(-1!==e.indexOf("%")&&(void 0!==n.scheme&&(n.scheme=unescape(n.scheme)),void 0!==n.host&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),t&&t.parse&&t.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}const f={SCHEMES:d,normalize:function(e,t){return"string"==typeof e?e=h(m(e,t),t):"object"==typeof e&&(e=m(h(e,t),t)),e},resolve:function(e,t,r){const s=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=l(m(e,s),m(t,s),s,!0);return s.skipEscape=!0,h(n,s)},resolveComponent:l,equal:function(e,t,r){return"string"==typeof e?(e=unescape(e),e=h(a(m(e,r),!0),{...r,skipEscape:!0})):"object"==typeof e&&(e=h(a(e,!0),{...r,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=h(a(m(t,r),!0),{...r,skipEscape:!0})):"object"==typeof t&&(t=h(a(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:h,parse:m};e.exports=f,e.exports.default=f,e.exports.fastUri=f},8451:function(e,t){var r;Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(r||(t.DiscrError=r={}))},8592:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;const s=r(6596),n=r(9048),i={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>s.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>s._`{limit: ${e}}`},code(e){const{parentSchema:t,it:r}=e,{items:s}=t;Array.isArray(s)?a(e,s):(0,n.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function a(e,t){const{gen:r,schema:i,data:a,keyword:o,it:c}=e;c.items=!0;const d=r.const("len",s._`${a}.length`);if(!1===i)e.setParams({len:t.length}),e.pass(s._`${d} <= ${t.length}`);else if("object"==typeof i&&!(0,n.alwaysValidSchema)(c,i)){const i=r.var("valid",s._`${d} <= ${t.length}`);r.if((0,s.not)(i),()=>function(i){r.forRange("i",t.length,d,t=>{e.subschema({keyword:o,dataProp:t,dataPropType:n.Type.Num},i),c.allErrors||r.if((0,s.not)(i),()=>r.break())})}(i)),e.ok(i)}}t.validateAdditionalItems=a,t.default=i},8851:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const s=r(6596),n=s.operators,i={maximum:{okStr:"<=",ok:n.LTE,fail:n.GT},minimum:{okStr:">=",ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},a={message:({keyword:e,schemaCode:t})=>s.str`must be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>s._`{comparison: ${i[e].okStr}, limit: ${t}}`},o={keyword:Object.keys(i),type:"number",schemaType:"number",$data:!0,error:a,code(e){const{keyword:t,data:r,schemaCode:n}=e;e.fail$data(s._`${r} ${i[t].fail} ${n} || isNaN(${r})`)}};t.default=o},9048:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.checkStrictMode=t.getErrorPath=t.Type=t.useFunc=t.setEvaluated=t.evaluatedPropsToName=t.mergeEvaluated=t.eachItem=t.unescapeJsonPointer=t.escapeJsonPointer=t.escapeFragment=t.unescapeFragment=t.schemaRefOrVal=t.schemaHasRulesButRef=t.schemaHasRules=t.checkUnknownRules=t.alwaysValidSchema=t.toHash=void 0;const s=r(6596),n=r(3231);function i(e,t=e.schema){const{opts:r,self:s}=e;if(!r.strictSchema)return;if("boolean"==typeof t)return;const n=s.RULES.keywords;for(const r in t)n[r]||m(e,`unknown keyword: "${r}"`)}function a(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function o(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function c(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function d({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,a,o,c)=>{const d=void 0===o?a:o instanceof s.Name?(a instanceof s.Name?e(i,a,o):t(i,a,o),o):a instanceof s.Name?(t(i,o,a),a):r(a,o);return c!==s.Name||d instanceof s.Name?d:n(i,d)}}function u(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",s._`{}`);return void 0!==t&&l(e,r,t),r}function l(e,t,r){Object.keys(r).forEach(r=>e.assign(s._`${t}${(0,s.getProperty)(r)}`,!0))}t.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},t.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(i(e,t),!a(t,e.self.RULES.all))},t.checkUnknownRules=i,t.schemaHasRules=a,t.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const r in e)if("$ref"!==r&&t.all[r])return!0;return!1},t.schemaRefOrVal=function({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if("number"==typeof r||"boolean"==typeof r)return r;if("string"==typeof r)return s._`${r}`}return s._`${e}${t}${(0,s.getProperty)(n)}`},t.unescapeFragment=function(e){return c(decodeURIComponent(e))},t.escapeFragment=function(e){return encodeURIComponent(o(e))},t.escapeJsonPointer=o,t.unescapeJsonPointer=c,t.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},t.mergeEvaluated={props:d({mergeNames:(e,t,r)=>e.if(s._`${r} !== true && ${t} !== undefined`,()=>{e.if(s._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,s._`${r} || {}`).code(s._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(s._`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,s._`${r} || {}`),l(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:u}),items:d({mergeNames:(e,t,r)=>e.if(s._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,s._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(s._`${r} !== true`,()=>e.assign(r,!0===t||s._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},t.evaluatedPropsToName=u,t.setEvaluated=l;const h={};var p;function m(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}t.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:h[t.code]||(h[t.code]=new n._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(p||(t.Type=p={})),t.getErrorPath=function(e,t,r){if(e instanceof s.Name){const n=t===p.Num;return r?n?s._`"[" + ${e} + "]"`:s._`"['" + ${e} + "']"`:n?s._`"/" + ${e}`:s._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,s.getProperty)(e).toString():"/"+o(e)},t.checkStrictMode=m},9877:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;const s=r(513),n=r(1140),i=r(4971),a=r(6596),o=r(9048);var c;function d(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(s.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(c||(t.DataType=c={})),t.getSchemaTypes=function(e){const t=d(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},t.getJSONTypes=d,t.coerceAndCheckDataType=function(e,t){const{gen:r,data:s,opts:i}=e,o=function(e,t){return t?e.filter(e=>u.has(e)||"array"===t&&"array"===e):[]}(t,i.coerceTypes),d=t.length>0&&!(0===o.length&&1===t.length&&(0,n.schemaHasRulesForType)(e,t[0]));if(d){const n=h(t,s,i.strictNumbers,c.Wrong);r.if(n,()=>{o.length?function(e,t,r){const{gen:s,data:n,opts:i}=e,o=s.let("dataType",a._`typeof ${n}`),c=s.let("coerced",a._`undefined`);"array"===i.coerceTypes&&s.if(a._`${o} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>s.assign(n,a._`${n}[0]`).assign(o,a._`typeof ${n}`).if(h(t,n,i.strictNumbers),()=>s.assign(c,n))),s.if(a._`${c} !== undefined`);for(const e of r)(u.has(e)||"array"===e&&"array"===i.coerceTypes)&&d(e);function d(e){switch(e){case"string":return void s.elseIf(a._`${o} == "number" || ${o} == "boolean"`).assign(c,a._`"" + ${n}`).elseIf(a._`${n} === null`).assign(c,a._`""`);case"number":return void s.elseIf(a._`${o} == "boolean" || ${n} === null || (${o} == "string" && ${n} && ${n} == +${n})`).assign(c,a._`+${n}`);case"integer":return void s.elseIf(a._`${o} === "boolean" || ${n} === null || (${o} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(c,a._`+${n}`);case"boolean":return void s.elseIf(a._`${n} === "false" || ${n} === 0 || ${n} === null`).assign(c,!1).elseIf(a._`${n} === "true" || ${n} === 1`).assign(c,!0);case"null":return s.elseIf(a._`${n} === "" || ${n} === 0 || ${n} === false`),void s.assign(c,null);case"array":s.elseIf(a._`${o} === "string" || ${o} === "number" || ${o} === "boolean" || ${n} === null`).assign(c,a._`[${n}]`)}}s.else(),m(e),s.endIf(),s.if(a._`${c} !== undefined`,()=>{s.assign(n,c),function({gen:e,parentData:t,parentDataProperty:r},s){e.if(a._`${t} !== undefined`,()=>e.assign(a._`${t}[${r}]`,s))}(e,c)})}(e,t,o):m(e)})}return d};const u=new Set(["string","number","integer","boolean","null"]);function l(e,t,r,s=c.Correct){const n=s===c.Correct?a.operators.EQ:a.operators.NEQ;let i;switch(e){case"null":return a._`${t} ${n} null`;case"array":i=a._`Array.isArray(${t})`;break;case"object":i=a._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=o(a._`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=o();break;default:return a._`typeof ${t} ${n} ${e}`}return s===c.Correct?i:(0,a.not)(i);function o(e=a.nil){return(0,a.and)(a._`typeof ${t} == "number"`,e,r?a._`isFinite(${t})`:a.nil)}}function h(e,t,r,s){if(1===e.length)return l(e[0],t,r,s);let n;const i=(0,o.toHash)(e);if(i.array&&i.object){const e=a._`typeof ${t} != "object"`;n=i.null?e:a._`!${t} || ${e}`,delete i.null,delete i.array,delete i.object}else n=a.nil;i.number&&delete i.integer;for(const e in i)n=(0,a.and)(n,l(e,t,r,s));return n}t.checkDataType=l,t.checkDataTypes=h;const p={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?a._`{type: ${e}}`:a._`{type: ${t}}`};function m(e){const t=function(e){const{gen:t,data:r,schema:s}=e,n=(0,o.schemaRefOrVal)(e,s,"type");return{gen:t,keyword:"type",data:r,schema:s.type,schemaCode:n,schemaValue:n,parentSchema:s,params:{},it:e}}(e);(0,i.reportError)(t,p)}t.reportTypeError=m},9981:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var s=r(3697);Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return s.KeywordCxt}});var n=r(6596);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const i=r(3781),a=r(7346),o=r(513),c=r(1430),d=r(6596),u=r(978),l=r(9877),h=r(9048),p=r(1808),m=r(6501),f=(e,t)=>new RegExp(e,t);f.code="new RegExp";const g=["removeAdditional","useDefaults","coerceTypes"],_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},v={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function w(e){var t,r,s,n,i,a,o,c,d,u,l,h,p,g,_,y,v,w,b,k,S,$,E,T,x;const P=e.strict,I=null===(t=e.code)||void 0===t?void 0:t.optimize,R=!0===I||void 0===I?1:I||0,O=null!==(s=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==s?s:f,C=null!==(n=e.uriResolver)&&void 0!==n?n:m.default;return{strictSchema:null===(a=null!==(i=e.strictSchema)&&void 0!==i?i:P)||void 0===a||a,strictNumbers:null===(c=null!==(o=e.strictNumbers)&&void 0!==o?o:P)||void 0===c||c,strictTypes:null!==(u=null!==(d=e.strictTypes)&&void 0!==d?d:P)&&void 0!==u?u:"log",strictTuples:null!==(h=null!==(l=e.strictTuples)&&void 0!==l?l:P)&&void 0!==h?h:"log",strictRequired:null!==(g=null!==(p=e.strictRequired)&&void 0!==p?p:P)&&void 0!==g&&g,code:e.code?{...e.code,optimize:R,regExp:O}:{optimize:R,regExp:O},loopRequired:null!==(_=e.loopRequired)&&void 0!==_?_:200,loopEnum:null!==(y=e.loopEnum)&&void 0!==y?y:200,meta:null===(v=e.meta)||void 0===v||v,messages:null===(w=e.messages)||void 0===w||w,inlineRefs:null===(b=e.inlineRefs)||void 0===b||b,schemaId:null!==(k=e.schemaId)&&void 0!==k?k:"$id",addUsedSchema:null===(S=e.addUsedSchema)||void 0===S||S,validateSchema:null===($=e.validateSchema)||void 0===$||$,validateFormats:null===(E=e.validateFormats)||void 0===E||E,unicodeRegExp:null===(T=e.unicodeRegExp)||void 0===T||T,int32range:null===(x=e.int32range)||void 0===x||x,uriResolver:C}}class b{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...w(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new d.ValueScope({scope:{},prefixes:_,es5:t,lines:r}),this.logger=function(e){if(!1===e)return P;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,o.getRules)(),k.call(this,y,e,"NOT SUPPORTED"),k.call(this,v,e,"DEPRECATED","warn"),this._metaOpts=x.call(this),e.formats&&E.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&T.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),$.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let s=p;"id"===r&&(s={...p},s.id=s.$id,delete s.$id),t&&e&&this.addMetaSchema(s,s[r],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);const s=r(t);return"$async"in r||(this.errors=r.errors),s}compile(e,t){const r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:r}=this.opts;return s.call(this,e,t);async function s(e,t){await n.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||i.call(this,r)}async function n(e){e&&!this.getSchema(e)&&await s.call(this,{$ref:e},!0)}async function i(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof a.default))throw t;return o.call(this,t),await c.call(this,t.missingSchema),i.call(this,e)}}function o({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const r=await d.call(this,e);this.refs[e]||await n.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function d(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r,s=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,s);return this}let n;if("object"==typeof e){const{schemaId:t}=this.opts;if(n=e[t],void 0!==n&&"string"!=typeof n)throw new Error(`schema ${t} must be string`)}return t=(0,u.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,s,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const s=this.validate(r,e);if(!s&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return s}getSchema(e){let t;for(;"string"==typeof(t=S.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,s=new c.SchemaEnv({schema:{},schemaId:r});if(t=c.resolveSchema.call(this,s,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=S.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,u.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(R.call(this,r,t),!t)return(0,h.eachItem)(r,e=>O.call(this,e)),this;A.call(this,t);const s={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,h.eachItem)(r,0===s.type.length?e=>O.call(this,e,s):e=>s.type.forEach(t=>O.call(this,e,s,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const r of t.rules){const t=r.rules.findIndex(t=>t.keyword===e);t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return e&&0!==e.length?e.map(e=>`${r}${e.instancePath} ${e.message}`).reduce((e,r)=>e+t+r):"No errors"}$dataMetaSchema(e,t){const r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const s of t){const t=s.split("/").slice(1);let n=e;for(const e of t)n=n[e];for(const e in r){const t=r[e];if("object"!=typeof t)continue;const{$data:s}=t.definition,i=n[e];s&&i&&(n[e]=j(i))}}return e}_removeAllSchemas(e,t){for(const r in e){const s=e[r];t&&!t.test(r)||("string"==typeof s?delete e[r]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[r]))}}_addSchema(e,t,r,s=this.opts.validateSchema,n=this.opts.addUsedSchema){let i;const{schemaId:a}=this.opts;if("object"==typeof e)i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let o=this._cache.get(e);if(void 0!==o)return o;r=(0,u.normalizeId)(i||r);const d=u.getSchemaRefs.call(this,e,r);return o=new c.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:r,localRefs:d}),this._cache.set(o.schema,o),n&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=o),s&&this.validateSchema(e,!0),o}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):c.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{c.compileSchema.call(this,e)}finally{this.opts=t}}}function k(e,t,r,s="error"){for(const n in e){const i=n;i in t&&this.logger[s](`${r}: option ${n}. ${e[i]}`)}}function S(e){return e=(0,u.normalizeId)(e),this.schemas[e]||this.refs[e]}function $(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function E(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function T(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function x(){const e={...this.opts};for(const t of g)delete e[t];return e}b.ValidationError=i.default,b.MissingRefError=a.default,t.default=b;const P={log(){},warn(){},error(){}},I=/^[a-z_$][a-z0-9_$:-]*$/i;function R(e,t){const{RULES:r}=this;if((0,h.eachItem)(e,e=>{if(r.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!I.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function O(e,t,r){var s;const n=null==t?void 0:t.post;if(r&&n)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:i}=this;let a=n?i.post:i.rules.find(({type:e})=>e===r);if(a||(a={type:r,rules:[]},i.rules.push(a)),i.keywords[e]=!0,!t)return;const o={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?C.call(this,a,o,t.before):a.rules.push(o),i.all[e]=o,null===(s=t.implements)||void 0===s||s.forEach(e=>this.addKeyword(e))}function C(e,t,r){const s=e.rules.findIndex(e=>e.keyword===r);s>=0?e.rules.splice(s,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function A(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=j(t)),e.validateSchema=this.compile(t,!0))}const N={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function j(e){return{anyOf:[e,N]}}}},t={};function r(s){var n=t[s];if(void 0!==n)return n.exports;var i=t[s]={exports:{}};return e[s](i,i.exports,r),i.exports}r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var s in t)r.o(t,s)&&!r.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};function n(e,t,r){function s(r,s){var n;Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(n=r._zod).traits??(n.traits=new Set),r._zod.traits.add(e),t(r,s);for(const e in a.prototype)e in r||Object.defineProperty(r,e,{value:a.prototype[e].bind(r)});r._zod.constr=a,r._zod.def=s}const n=r?.Parent??Object;class i extends n{}function a(e){var t;const n=r?.Parent?new i:this;s(n,e),(t=n._zod).deferred??(t.deferred=[]);for(const e of n._zod.deferred)e();return n}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(a,"init",{value:s}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}r.r(s),r.d(s,{ANGIE_MODEL_PREFERENCES:function(){return Ql},McpServer:function(){return Ul},ResourceTemplate:function(){return Dl},SamplingMessageSchema:function(){return qi},activateMcpRegistration:function(){return nh},createSampler:function(){return ph},getAngieSdk:function(){return $h},getMCPByDomain:function(){return oh},init:function(){return dh},installAngiePlugin:function(){return Sh},isAngieAvailable:function(){return ch},isAngieSidebarOpen:function(){return uh},redirectToAppAdmin:function(){return yh},redirectToInstallation:function(){return _h},registerMcp:function(){return sh},sendPromptToAngie:function(){return gh},toMCPTitle:function(){return ah},toolPrompts:function(){return fh}}),Object.freeze({status:"aborted"}),Symbol("zod_brand");class i extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const a={};function o(e){return e&&Object.assign(a,e),a}const c=/^[cC][^\s-]{8,}$/,d=/^[0-9a-z]+$/,u=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,l=/^[0-9a-vA-V]{20}$/,h=/^[A-Za-z0-9]{27}$/,p=/^[a-zA-Z0-9_-]{21}$/,m=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,f=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,g=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,y=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,v=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,w=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,b=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,k=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,S=/^[A-Za-z0-9_-]*$/,$=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,E=/^\+(?:[0-9]){6,14}[0-9]$/,T="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",x=new RegExp(`^${T}$`);function P(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const I=/^\d+$/,R=/^-?\d+(?:\.\d+)?/i,O=/true|false/i,C=/null/i,A=/^[^A-Z]*$/,N=/^[^a-z]*$/;function j(e){const t=Object.values(e).filter(e=>"number"==typeof e),r=Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t);return r}function z(e,t){return"bigint"==typeof t?t.toString():t}function M(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function q(e){return null==e}function U(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function D(e,t,r){Object.defineProperty(e,t,{get(){{const s=r();return e[t]=s,s}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function L(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Z(e){return JSON.stringify(e)}const F=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function H(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const V=M(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function K(e){if(!1===H(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!1!==H(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}const G=new Set(["string","number","symbol"]);function W(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J(e,t,r){const s=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(s._zod.parent=e),s}function B(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}new Set(["string","number","bigint","boolean","symbol","undefined"]);const Q={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Y(e,t=0){for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function X(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function ee(e){return"string"==typeof e?e:e?.message}function te(e,t,r){const s={...e,path:e.path??[]};if(!e.message){const n=ee(e.inst?._zod.def?.error?.(e))??ee(t?.error?.(e))??ee(r.customError?.(e))??ee(r.localeError?.(e))??"Invalid input";s.message=n}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}function re(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function se(...e){const[t,r,s]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:s}:{...t}}const ne=n("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),ie={number:"number",bigint:"bigint",object:"date"},ae=n("$ZodCheckLessThan",(e,t)=>{ne.init(e,t);const r=ie[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,s=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:r,code:"too_big",maximum:t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),oe=n("$ZodCheckGreaterThan",(e,t)=>{ne.init(e,t);const r=ie[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,s=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:r,code:"too_small",minimum:t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ce=n("$ZodCheckMultipleOf",(e,t)=>{ne.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===function(e,t){const r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=r>s?r:s;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),de=n("$ZodCheckNumberFormat",(e,t)=>{ne.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),s=r?"int":"number",[n,i]=Q[t.format];e._zod.onattach.push(e=>{const s=e._zod.bag;s.format=t.format,s.minimum=n,s.maximum=i,r&&(s.pattern=I)}),e._zod.check=a=>{const o=a.value;if(r){if(!Number.isInteger(o))return void a.issues.push({expected:s,format:t.format,code:"invalid_type",input:o,inst:e});if(!Number.isSafeInteger(o))return void(o>0?a.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,continue:!t.abort}):a.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,continue:!t.abort}))}o<n&&a.issues.push({origin:"number",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>i&&a.issues.push({origin:"number",input:o,code:"too_big",maximum:i,inst:e})}}),ue=n("$ZodCheckMaxLength",(e,t)=>{var r;ne.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!q(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const s=r.value;if(s.length<=t.maximum)return;const n=re(s);r.issues.push({origin:n,code:"too_big",maximum:t.maximum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),le=n("$ZodCheckMinLength",(e,t)=>{var r;ne.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!q(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const s=r.value;if(s.length>=t.minimum)return;const n=re(s);r.issues.push({origin:n,code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),he=n("$ZodCheckLengthEquals",(e,t)=>{var r;ne.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!q(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{const s=r.value,n=s.length;if(n===t.length)return;const i=re(s),a=n>t.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),pe=n("$ZodCheckStringFormat",(e,t)=>{var r,s;ne.init(e,t),e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),me=n("$ZodCheckRegex",(e,t)=>{pe.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),fe=n("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=A),pe.init(e,t)}),ge=n("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=N),pe.init(e,t)}),_e=n("$ZodCheckIncludes",(e,t)=>{ne.init(e,t);const r=W(t.includes),s=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=s,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(s)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),ye=n("$ZodCheckStartsWith",(e,t)=>{ne.init(e,t);const r=new RegExp(`^${W(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),ve=n("$ZodCheckEndsWith",(e,t)=>{ne.init(e,t);const r=new RegExp(`.*${W(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),we=n("$ZodCheckOverwrite",(e,t)=>{ne.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class be{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length)),s=t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e);for(const e of s)this.content.push(e)}compile(){const e=Function,t=this?.args,r=[...(this?.content??[""]).map(e=>` ${e}`)];return new e(...t,r.join("\n"))}}const ke=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,z,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Se=n("$ZodError",ke),$e=n("$ZodError",ke,{Parent:Error}),Ee=e=>(t,r,s,n)=>{const a=s?Object.assign(s,{async:!1}):{async:!1},c=t._zod.run({value:r,issues:[]},a);if(c instanceof Promise)throw new i;if(c.issues.length){const t=new(n?.Err??e)(c.issues.map(e=>te(e,a,o())));throw F(t,n?.callee),t}return c.value},Te=Ee($e),xe=e=>async(t,r,s,n)=>{const i=s?Object.assign(s,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(n?.Err??e)(a.issues.map(e=>te(e,i,o())));throw F(t,n?.callee),t}return a.value},Pe=xe($e),Ie=e=>(t,r,s)=>{const n=s?{...s,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},n);if(a instanceof Promise)throw new i;return a.issues.length?{success:!1,error:new(e??Se)(a.issues.map(e=>te(e,n,o())))}:{success:!0,data:a.value}},Re=Ie($e),Oe=e=>async(t,r,s)=>{const n=s?Object.assign(s,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>te(e,n,o())))}:{success:!0,data:i.value}},Ce=Oe($e),Ae={major:4,minor:0,patch:0},Ne=n("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ae;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const t of s)for(const r of t._zod.onattach)r(e);if(0===s.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,r)=>{let s,n=Y(e);for(const a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(n)continue;const t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&!1===r?.async)throw new i;if(s||o instanceof Promise)s=(s??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(n||(n=Y(e,t)))});else{if(e.issues.length===t)continue;n||(n=Y(e,t))}}return s?s.then(()=>e):e};e._zod.run=(r,n)=>{const a=e._zod.parse(r,n);if(a instanceof Promise){if(!1===n.async)throw new i;return a.then(e=>t(e,s,n))}return t(a,s,n)}}e["~standard"]={validate:t=>{try{const r=Re(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return Ce(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),je=n("$ZodString",(e,t)=>{var r;Ne.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(r=e._zod.bag,new RegExp(`^${r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=String(r.value)}catch(s){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ze=n("$ZodStringFormat",(e,t)=>{pe.init(e,t),je.init(e,t)}),Me=n("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=f),ze.init(e,t)}),qe=n("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=g(e))}else t.pattern??(t.pattern=g());ze.init(e,t)}),Ue=n("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=_),ze.init(e,t)}),De=n("$ZodURL",(e,t)=>{ze.init(e,t),e._zod.check=r=>{try{const s=r.value,n=new URL(s),i=n.href;return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:$.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),void(!s.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i)}catch(s){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Le=n("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ze.init(e,t)}),Ze=n("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=p),ze.init(e,t)}),Fe=n("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=c),ze.init(e,t)}),He=n("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=d),ze.init(e,t)}),Ve=n("$ZodULID",(e,t)=>{t.pattern??(t.pattern=u),ze.init(e,t)}),Ke=n("$ZodXID",(e,t)=>{t.pattern??(t.pattern=l),ze.init(e,t)}),Ge=n("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=h),ze.init(e,t)}),We=n("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=P({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const s=`${t}(?:${r.join("|")})`;return new RegExp(`^${T}T(?:${s})$`)}(t)),ze.init(e,t)}),Je=n("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=x),ze.init(e,t)}),Be=n("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${P(t)}$`)),ze.init(e,t)}),Qe=n("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=m),ze.init(e,t)}),Ye=n("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=y),ze.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),Xe=n("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=v),ze.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),et=n("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=w),ze.init(e,t)}),tt=n("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=b),ze.init(e,t),e._zod.check=r=>{const[s,n]=r.value.split("/");try{if(!n)throw new Error;const e=Number(n);if(`${e}`!==n)throw new Error;if(e<0||e>128)throw new Error;new URL(`http://[${s}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function rt(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const st=n("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=k),ze.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{rt(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),nt=n("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=S),ze.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{(function(e){if(!S.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return rt(t.padEnd(4*Math.ceil(t.length/4),"="))})(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),it=n("$ZodE164",(e,t)=>{t.pattern??(t.pattern=E),ze.init(e,t)}),at=n("$ZodJWT",(e,t)=>{ze.init(e,t),e._zod.check=r=>{(function(e,t=null){try{const r=e.split(".");if(3!==r.length)return!1;const[s]=r;if(!s)return!1;const n=JSON.parse(atob(s));return!("typ"in n&&"JWT"!==n?.typ||!n.alg||t&&(!("alg"in n)||n.alg!==t))}catch{return!1}})(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),ot=n("$ZodNumber",(e,t)=>{Ne.init(e,t),e._zod.pattern=e._zod.bag.pattern??R,e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}const n=r.value;if("number"==typeof n&&!Number.isNaN(n)&&Number.isFinite(n))return r;const i="number"==typeof n?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}}),ct=n("$ZodNumber",(e,t)=>{de.init(e,t),ot.init(e,t)}),dt=n("$ZodBoolean",(e,t)=>{Ne.init(e,t),e._zod.pattern=O,e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(e){}const n=r.value;return"boolean"==typeof n||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}}),ut=n("$ZodNull",(e,t)=>{Ne.init(e,t),e._zod.pattern=C,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{const s=t.value;return null===s||t.issues.push({expected:"null",code:"invalid_type",input:s,inst:e}),t}}),lt=n("$ZodUnknown",(e,t)=>{Ne.init(e,t),e._zod.parse=e=>e}),ht=n("$ZodNever",(e,t)=>{Ne.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function pt(e,t,r){e.issues.length&&t.issues.push(...X(r,e.issues)),t.value[r]=e.value}const mt=n("$ZodArray",(e,t)=>{Ne.init(e,t),e._zod.parse=(r,s)=>{const n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);const i=[];for(let e=0;e<n.length;e++){const a=n[e],o=t.element._zod.run({value:a,issues:[]},s);o instanceof Promise?i.push(o.then(t=>pt(t,r,e))):pt(o,r,e)}return i.length?Promise.all(i).then(()=>r):r}});function ft(e,t,r){e.issues.length&&t.issues.push(...X(r,e.issues)),t.value[r]=e.value}function gt(e,t,r,s){e.issues.length?void 0===s[r]?t.value[r]=r in s?void 0:e.value:t.issues.push(...X(r,e.issues)):void 0===e.value?r in s&&(t.value[r]=void 0):t.value[r]=e.value}const _t=n("$ZodObject",(e,t)=>{Ne.init(e,t);const r=M(()=>{const e=Object.keys(t.shape);for(const r of e)if(!(t.shape[r]instanceof Ne))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=(s=t.shape,Object.keys(s).filter(e=>"optional"===s[e]._zod.optin&&"optional"===s[e]._zod.optout));var s;return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});let s;D(e._zod,"propValues",()=>{const e=t.shape,r={};for(const t in e){const s=e[t]._zod;if(s.values){r[t]??(r[t]=new Set);for(const e of s.values)r[t].add(e)}}return r});const n=H,i=!a.jitless,o=i&&V.value,c=t.catchall;let d;e._zod.parse=(a,u)=>{d??(d=r.value);const l=a.value;if(!n(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),a;const h=[];if(i&&o&&!1===u?.async&&!0!==u.jitless)s||(s=(e=>{const t=new be(["shape","payload","ctx"]),s=r.value,n=e=>{const t=Z(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=Object.create(null);let a=0;for(const e of s.keys)i[e]="key_"+a++;t.write("const newResult = {}");for(const e of s.keys)if(s.optionalKeys.has(e)){const r=i[e];t.write(`const ${r} = ${n(e)};`);const s=Z(e);t.write(`\n if (${r}.issues.length) {\n if (input[${s}] === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n payload.issues = payload.issues.concat(\n ${r}.issues.map((iss) => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}],\n }))\n );\n }\n } else if (${r}.value === undefined) {\n if (${s} in input) newResult[${s}] = undefined;\n } else {\n newResult[${s}] = ${r}.value;\n }\n `)}else{const r=i[e];t.write(`const ${r} = ${n(e)};`),t.write(`\n if (${r}.issues.length) payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${Z(e)}, ...iss.path] : [${Z(e)}]\n })));`),t.write(`newResult[${Z(e)}] = ${r}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");const o=t.compile();return(t,r)=>o(e,t,r)})(t.shape)),a=s(a,u);else{a.value={};const e=d.shape;for(const t of d.keys){const r=e[t],s=r._zod.run({value:l[t],issues:[]},u),n="optional"===r._zod.optin&&"optional"===r._zod.optout;s instanceof Promise?h.push(s.then(e=>n?gt(e,a,t,l):ft(e,a,t))):n?gt(s,a,t,l):ft(s,a,t)}}if(!c)return h.length?Promise.all(h).then(()=>a):a;const p=[],m=d.keySet,f=c._zod,g=f.def.type;for(const e of Object.keys(l)){if(m.has(e))continue;if("never"===g){p.push(e);continue}const t=f.run({value:l[e],issues:[]},u);t instanceof Promise?h.push(t.then(t=>ft(t,a,e))):ft(t,a,e)}return p.length&&a.issues.push({code:"unrecognized_keys",keys:p,input:l,inst:e}),h.length?Promise.all(h).then(()=>a):a}});function yt(e,t,r,s){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>te(e,s,o())))}),t}const vt=n("$ZodUnion",(e,t)=>{Ne.init(e,t),D(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),D(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),D(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),D(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>U(e.source)).join("|")})$`)}}),e._zod.parse=(r,s)=>{let n=!1;const i=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},s);if(t instanceof Promise)i.push(t),n=!0;else{if(0===t.issues.length)return t;i.push(t)}}return n?Promise.all(i).then(t=>yt(t,r,e,s)):yt(i,r,e,s)}}),wt=n("$ZodDiscriminatedUnion",(e,t)=>{vt.init(e,t);const r=e._zod.parse;D(e._zod,"propValues",()=>{const e={};for(const r of t.options){const s=r._zod.propValues;if(!s||0===Object.keys(s).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[t,r]of Object.entries(s)){e[t]||(e[t]=new Set);for(const s of r)e[t].add(s)}}return e});const s=M(()=>{const e=t.options,r=new Map;for(const s of e){const e=s._zod.propValues[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const t of e){if(r.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,s)}}return r});e._zod.parse=(n,i)=>{const a=n.value;if(!H(a))return n.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),n;const o=s.value.get(a?.[t.discriminator]);return o?o._zod.run(n,i):t.unionFallback?r(n,i):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),n)}}),bt=n("$ZodIntersection",(e,t)=>{Ne.init(e,t),e._zod.parse=(e,r)=>{const s=e.value,n=t.left._zod.run({value:s,issues:[]},r),i=t.right._zod.run({value:s,issues:[]},r);return n instanceof Promise||i instanceof Promise?Promise.all([n,i]).then(([t,r])=>St(e,t,r)):St(e,n,i)}});function kt(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(K(e)&&K(t)){const r=Object.keys(t),s=Object.keys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const r of s){const s=kt(e[r],t[r]);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n[r]=s.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let s=0;s<e.length;s++){const n=kt(e[s],t[s]);if(!n.valid)return{valid:!1,mergeErrorPath:[s,...n.mergeErrorPath]};r.push(n.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function St(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Y(e))return e;const s=kt(t.value,r.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const $t=n("$ZodRecord",(e,t)=>{Ne.init(e,t),e._zod.parse=(r,s)=>{const n=r.value;if(!K(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;const i=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;r.value={};for(const e of a)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const a=t.valueType._zod.run({value:n[e],issues:[]},s);a instanceof Promise?i.push(a.then(t=>{t.issues.length&&r.issues.push(...X(e,t.issues)),r.value[e]=t.value})):(a.issues.length&&r.issues.push(...X(e,a.issues)),r.value[e]=a.value)}let o;for(const e in n)a.has(e)||(o=o??[],o.push(e));o&&o.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:o})}else{r.value={};for(const a of Reflect.ownKeys(n)){if("__proto__"===a)continue;const c=t.keyType._zod.run({value:a,issues:[]},s);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:c.issues.map(e=>te(e,s,o())),input:a,path:[a],inst:e}),r.value[c.value]=c.value;continue}const d=t.valueType._zod.run({value:n[a],issues:[]},s);d instanceof Promise?i.push(d.then(e=>{e.issues.length&&r.issues.push(...X(a,e.issues)),r.value[c.value]=e.value})):(d.issues.length&&r.issues.push(...X(a,d.issues)),r.value[c.value]=d.value)}}return i.length?Promise.all(i).then(()=>r):r}}),Et=n("$ZodEnum",(e,t)=>{Ne.init(e,t);const r=j(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(e=>G.has(typeof e)).map(e=>"string"==typeof e?W(e):e.toString()).join("|")})$`),e._zod.parse=(t,s)=>{const n=t.value;return e._zod.values.has(n)||t.issues.push({code:"invalid_value",values:r,input:n,inst:e}),t}}),Tt=n("$ZodLiteral",(e,t)=>{Ne.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?W(e):e?e.toString():String(e)).join("|")})$`),e._zod.parse=(r,s)=>{const n=r.value;return e._zod.values.has(n)||r.issues.push({code:"invalid_value",values:t.values,input:n,inst:e}),r}}),xt=n("$ZodTransform",(e,t)=>{Ne.init(e,t),e._zod.parse=(e,r)=>{const s=t.transform(e.value,e);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(t=>(e.value=t,e));if(s instanceof Promise)throw new i;return e.value=s,e}}),Pt=n("$ZodOptional",(e,t)=>{Ne.init(e,t),e._zod.optin="optional",e._zod.optout="optional",D(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),D(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${U(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>"optional"===t.innerType._zod.optin?t.innerType._zod.run(e,r):void 0===e.value?e:t.innerType._zod.run(e,r)}),It=n("$ZodNullable",(e,t)=>{Ne.init(e,t),D(e._zod,"optin",()=>t.innerType._zod.optin),D(e._zod,"optout",()=>t.innerType._zod.optout),D(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${U(e.source)}|null)$`):void 0}),D(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),Rt=n("$ZodDefault",(e,t)=>{Ne.init(e,t),e._zod.optin="optional",D(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;const s=t.innerType._zod.run(e,r);return s instanceof Promise?s.then(e=>Ot(e,t)):Ot(s,t)}});function Ot(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const Ct=n("$ZodPrefault",(e,t)=>{Ne.init(e,t),e._zod.optin="optional",D(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),At=n("$ZodNonOptional",(e,t)=>{Ne.init(e,t),D(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,s)=>{const n=t.innerType._zod.run(r,s);return n instanceof Promise?n.then(t=>Nt(t,e)):Nt(n,e)}});function Nt(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const jt=n("$ZodCatch",(e,t)=>{Ne.init(e,t),e._zod.optin="optional",D(e._zod,"optout",()=>t.innerType._zod.optout),D(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{const s=t.innerType._zod.run(e,r);return s instanceof Promise?s.then(s=>(e.value=s.value,s.issues.length&&(e.value=t.catchValue({...e,error:{issues:s.issues.map(e=>te(e,r,o()))},input:e.value}),e.issues=[]),e)):(e.value=s.value,s.issues.length&&(e.value=t.catchValue({...e,error:{issues:s.issues.map(e=>te(e,r,o()))},input:e.value}),e.issues=[]),e)}}),zt=n("$ZodPipe",(e,t)=>{Ne.init(e,t),D(e._zod,"values",()=>t.in._zod.values),D(e._zod,"optin",()=>t.in._zod.optin),D(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(e,r)=>{const s=t.in._zod.run(e,r);return s instanceof Promise?s.then(e=>Mt(e,t,r)):Mt(s,t,r)}});function Mt(e,t,r){return Y(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const qt=n("$ZodReadonly",(e,t)=>{Ne.init(e,t),D(e._zod,"propValues",()=>t.innerType._zod.propValues),D(e._zod,"values",()=>t.innerType._zod.values),D(e._zod,"optin",()=>t.innerType._zod.optin),D(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{const s=t.innerType._zod.run(e,r);return s instanceof Promise?s.then(Ut):Ut(s)}});function Ut(e){return e.value=Object.freeze(e.value),e}const Dt=n("$ZodCustom",(e,t)=>{ne.init(e,t),Ne.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{const s=r.value,n=t.fn(s);if(n instanceof Promise)return n.then(t=>Lt(t,r,s,e));Lt(n,r,s,e)}});function Lt(e,t,r,s){if(!e){const e={code:"custom",input:r,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(e.params=s._zod.def.params),t.issues.push(se(e))}}Symbol("ZodOutput"),Symbol("ZodInput");class Zt{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function Ft(){return new Zt}const Ht=Ft();function Vt(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...B(t)})}function Kt(e,t){return new ae({check:"less_than",...B(t),value:e,inclusive:!1})}function Gt(e,t){return new ae({check:"less_than",...B(t),value:e,inclusive:!0})}function Wt(e,t){return new oe({check:"greater_than",...B(t),value:e,inclusive:!1})}function Jt(e,t){return new oe({check:"greater_than",...B(t),value:e,inclusive:!0})}function Bt(e,t){return new ce({check:"multiple_of",...B(t),value:e})}function Qt(e,t){return new ue({check:"max_length",...B(t),maximum:e})}function Yt(e,t){return new le({check:"min_length",...B(t),minimum:e})}function Xt(e,t){return new he({check:"length_equals",...B(t),length:e})}function er(e){return new we({check:"overwrite",tx:e})}const tr=n("ZodISODateTime",(e,t)=>{We.init(e,t),gr.init(e,t)});function rr(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...B(t)})}(tr,e)}const sr=n("ZodISODate",(e,t)=>{Je.init(e,t),gr.init(e,t)});const nr=n("ZodISOTime",(e,t)=>{Be.init(e,t),gr.init(e,t)});const ir=n("ZodISODuration",(e,t)=>{Qe.init(e,t),gr.init(e,t)});const ar=(e,t)=>{Se.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t){const r=t||function(e){return e.message},s={_errors:[]},n=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>n({issues:e}));else if("invalid_key"===t.code)n({issues:t.issues});else if("invalid_element"===t.code)n({issues:t.issues});else if(0===t.path.length)s._errors.push(r(t));else{let e=s,n=0;for(;n<t.path.length;){const s=t.path[n];n===t.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(r(t))):e[s]=e[s]||{_errors:[]},e=e[s],n++}}};return n(e),s}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const r={},s=[];for(const n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):s.push(t(n));return{formErrors:s,fieldErrors:r}}(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get(){return 0===e.issues.length}}})},or=(n("ZodError",ar),n("ZodError",ar,{Parent:Error})),cr=Ee(or),dr=xe(or),ur=Ie(or),lr=Oe(or),hr=n("ZodType",(e,t)=>(Ne.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>J(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>cr(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>ur(e,t,r),e.parseAsync=async(t,r)=>dr(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>lr(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(function(e,t={}){return function(e,t,r){return new e({type:"custom",check:"custom",fn:t,...B(r)})}(Ss,e,t)}(t,r)),e.superRefine=t=>e.check(function(e){const t=function(e){const t=new ne({check:"custom"});return t._zod.check=e,t}(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(se(e,r.value,t._zod.def));else{const s=e;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=t),s.continue??(s.continue=!t._zod.def.abort),r.issues.push(se(s))}},e(r.value,r)));return t}(t)),e.overwrite=t=>e.check(er(t)),e.optional=()=>ps(e),e.nullable=()=>fs(e),e.nullish=()=>ps(fs(e)),e.nonoptional=t=>function(e,t){return new ys({type:"nonoptional",innerType:e,...B(t)})}(e,t),e.array=()=>Wr(e),e.or=t=>Xr([e,t]),e.and=t=>ss(e,t),e.transform=t=>bs(e,ls(t)),e.default=t=>{return r=t,new gs({type:"default",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.prefault=t=>{return r=t,new _s({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.catch=t=>{return new vs({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r});var r},e.pipe=t=>bs(e,t),e.readonly=()=>new ks({type:"readonly",innerType:e}),e.describe=t=>{const r=e.clone();return Ht.add(r,{description:t}),r},Object.defineProperty(e,"description",{get(){return Ht.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Ht.get(e);const r=e.clone();return Ht.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),pr=n("_ZodString",(e,t)=>{je.init(e,t),hr.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new me({check:"string_format",format:"regex",...B(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new _e({check:"string_format",format:"includes",...B(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new ye({check:"string_format",format:"starts_with",...B(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new ve({check:"string_format",format:"ends_with",...B(t),suffix:e})}(...t)),e.min=(...t)=>e.check(Yt(...t)),e.max=(...t)=>e.check(Qt(...t)),e.length=(...t)=>e.check(Xt(...t)),e.nonempty=(...t)=>e.check(Yt(1,...t)),e.lowercase=t=>e.check(function(e){return new fe({check:"string_format",format:"lowercase",...B(e)})}(t)),e.uppercase=t=>e.check(function(e){return new ge({check:"string_format",format:"uppercase",...B(e)})}(t)),e.trim=()=>e.check(er(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return er(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(er(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(er(e=>e.toUpperCase()))}),mr=n("ZodString",(e,t)=>{je.init(e,t),pr.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...B(t)})}(_r,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...B(t)})}(wr,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...B(t)})}(jr,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...B(t)})}(br,t)),e.guid=t=>e.check(Vt(yr,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...B(t)})}(vr,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...B(t)})}(vr,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...B(t)})}(vr,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...B(t)})}(vr,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...B(t)})}(kr,t)),e.guid=t=>e.check(Vt(yr,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...B(t)})}(Sr,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...B(t)})}($r,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...B(t)})}(Er,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...B(t)})}(Cr,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...B(t)})}(Ar,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...B(t)})}(Tr,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...B(t)})}(xr,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...B(t)})}(Pr,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...B(t)})}(Ir,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...B(t)})}(Rr,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...B(t)})}(Or,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...B(t)})}(Nr,t)),e.datetime=t=>e.check(rr(t)),e.date=t=>e.check(function(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...B(t)})}(sr,e)}(t)),e.time=t=>e.check(function(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...B(t)})}(nr,e)}(t)),e.duration=t=>e.check(function(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...B(t)})}(ir,e)}(t))});function fr(e){return function(e,t){return new e({type:"string",...B(t)})}(mr,e)}const gr=n("ZodStringFormat",(e,t)=>{ze.init(e,t),pr.init(e,t)}),_r=n("ZodEmail",(e,t)=>{Ue.init(e,t),gr.init(e,t)}),yr=n("ZodGUID",(e,t)=>{Me.init(e,t),gr.init(e,t)}),vr=n("ZodUUID",(e,t)=>{qe.init(e,t),gr.init(e,t)}),wr=n("ZodURL",(e,t)=>{De.init(e,t),gr.init(e,t)}),br=n("ZodEmoji",(e,t)=>{Le.init(e,t),gr.init(e,t)}),kr=n("ZodNanoID",(e,t)=>{Ze.init(e,t),gr.init(e,t)}),Sr=n("ZodCUID",(e,t)=>{Fe.init(e,t),gr.init(e,t)}),$r=n("ZodCUID2",(e,t)=>{He.init(e,t),gr.init(e,t)}),Er=n("ZodULID",(e,t)=>{Ve.init(e,t),gr.init(e,t)}),Tr=n("ZodXID",(e,t)=>{Ke.init(e,t),gr.init(e,t)}),xr=n("ZodKSUID",(e,t)=>{Ge.init(e,t),gr.init(e,t)}),Pr=n("ZodIPv4",(e,t)=>{Ye.init(e,t),gr.init(e,t)}),Ir=n("ZodIPv6",(e,t)=>{Xe.init(e,t),gr.init(e,t)}),Rr=n("ZodCIDRv4",(e,t)=>{et.init(e,t),gr.init(e,t)}),Or=n("ZodCIDRv6",(e,t)=>{tt.init(e,t),gr.init(e,t)}),Cr=n("ZodBase64",(e,t)=>{st.init(e,t),gr.init(e,t)}),Ar=n("ZodBase64URL",(e,t)=>{nt.init(e,t),gr.init(e,t)}),Nr=n("ZodE164",(e,t)=>{it.init(e,t),gr.init(e,t)}),jr=n("ZodJWT",(e,t)=>{at.init(e,t),gr.init(e,t)}),zr=n("ZodNumber",(e,t)=>{ot.init(e,t),hr.init(e,t),e.gt=(t,r)=>e.check(Wt(t,r)),e.gte=(t,r)=>e.check(Jt(t,r)),e.min=(t,r)=>e.check(Jt(t,r)),e.lt=(t,r)=>e.check(Kt(t,r)),e.lte=(t,r)=>e.check(Gt(t,r)),e.max=(t,r)=>e.check(Gt(t,r)),e.int=t=>e.check(Ur(t)),e.safe=t=>e.check(Ur(t)),e.positive=t=>e.check(Wt(0,t)),e.nonnegative=t=>e.check(Jt(0,t)),e.negative=t=>e.check(Kt(0,t)),e.nonpositive=t=>e.check(Gt(0,t)),e.multipleOf=(t,r)=>e.check(Bt(t,r)),e.step=(t,r)=>e.check(Bt(t,r)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function Mr(e){return function(e,t){return new e({type:"number",checks:[],...B(t)})}(zr,e)}const qr=n("ZodNumberFormat",(e,t)=>{ct.init(e,t),zr.init(e,t)});function Ur(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...B(t)})}(qr,e)}const Dr=n("ZodBoolean",(e,t)=>{dt.init(e,t),hr.init(e,t)});function Lr(e){return function(e,t){return new e({type:"boolean",...B(t)})}(Dr,e)}const Zr=n("ZodNull",(e,t)=>{ut.init(e,t),hr.init(e,t)});function Fr(e){return function(e,t){return new e({type:"null",...B(t)})}(Zr,e)}const Hr=n("ZodUnknown",(e,t)=>{lt.init(e,t),hr.init(e,t)});function Vr(){return new Hr({type:"unknown"})}const Kr=n("ZodNever",(e,t)=>{ht.init(e,t),hr.init(e,t)});const Gr=n("ZodArray",(e,t)=>{mt.init(e,t),hr.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(Yt(t,r)),e.nonempty=t=>e.check(Yt(1,t)),e.max=(t,r)=>e.check(Qt(t,r)),e.length=(t,r)=>e.check(Xt(t,r)),e.unwrap=()=>e.element});function Wr(e,t){return function(e,t,r){return new e({type:"array",element:t,...B(r)})}(Gr,e,t)}const Jr=n("ZodObject",(e,t)=>{_t.init(e,t),hr.init(e,t),D(e,"shape",()=>t.shape),e.keyof=()=>os(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Vr()}),e.loose=()=>e.clone({...e._zod.def,catchall:Vr()}),e.strict=()=>{return e.clone({...e._zod.def,catchall:function(e,t){return new e({type:"never",...B(t)})}(Kr,t)});var t},e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!K(t))throw new Error("Invalid input to extend: expected a plain object");const r={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return L(this,"shape",r),r},checks:[]};return J(e,r)}(e,t),e.merge=t=>function(e,t){return J(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return L(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}(e,t),e.pick=t=>function(e,t){const r={},s=e._zod.def;for(const e in t){if(!(e in s.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&(r[e]=s.shape[e])}return J(e,{...e._zod.def,shape:r,checks:[]})}(e,t),e.omit=t=>function(e,t){const r={...e._zod.def.shape},s=e._zod.def;for(const e in t){if(!(e in s.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return J(e,{...e._zod.def,shape:r,checks:[]})}(e,t),e.partial=(...t)=>function(e,t,r){const s=t._zod.def.shape,n={...s};if(r)for(const t in r){if(!(t in s))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=e?new e({type:"optional",innerType:s[t]}):s[t])}else for(const t in s)n[t]=e?new e({type:"optional",innerType:s[t]}):s[t];return J(t,{...t._zod.def,shape:n,checks:[]})}(hs,e,t[0]),e.required=(...t)=>function(e,t,r){const s=t._zod.def.shape,n={...s};if(r)for(const t in r){if(!(t in n))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=new e({type:"nonoptional",innerType:s[t]}))}else for(const t in s)n[t]=new e({type:"nonoptional",innerType:s[t]});return J(t,{...t._zod.def,shape:n,checks:[]})}(ys,e,t[0])});function Br(e,t){const r={type:"object",get shape(){return L(this,"shape",{...e}),this.shape},...B(t)};return new Jr(r)}function Qr(e,t){return new Jr({type:"object",get shape(){return L(this,"shape",{...e}),this.shape},catchall:Vr(),...B(t)})}const Yr=n("ZodUnion",(e,t)=>{vt.init(e,t),hr.init(e,t),e.options=t.options});function Xr(e,t){return new Yr({type:"union",options:e,...B(t)})}const es=n("ZodDiscriminatedUnion",(e,t)=>{Yr.init(e,t),wt.init(e,t)});function ts(e,t,r){return new es({type:"union",options:t,discriminator:e,...B(r)})}const rs=n("ZodIntersection",(e,t)=>{bt.init(e,t),hr.init(e,t)});function ss(e,t){return new rs({type:"intersection",left:e,right:t})}const ns=n("ZodRecord",(e,t)=>{$t.init(e,t),hr.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function is(e,t,r){return new ns({type:"record",keyType:e,valueType:t,...B(r)})}const as=n("ZodEnum",(e,t)=>{Et.init(e,t),hr.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(e,s)=>{const n={};for(const s of e){if(!r.has(s))throw new Error(`Key ${s} not found in enum`);n[s]=t.entries[s]}return new as({...t,checks:[],...B(s),entries:n})},e.exclude=(e,s)=>{const n={...t.entries};for(const t of e){if(!r.has(t))throw new Error(`Key ${t} not found in enum`);delete n[t]}return new as({...t,checks:[],...B(s),entries:n})}});function os(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new as({type:"enum",entries:r,...B(t)})}const cs=n("ZodLiteral",(e,t)=>{Tt.init(e,t),hr.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function ds(e,t){return new cs({type:"literal",values:Array.isArray(e)?e:[e],...B(t)})}const us=n("ZodTransform",(e,t)=>{xt.init(e,t),hr.init(e,t),e._zod.parse=(r,s)=>{r.addIssue=s=>{if("string"==typeof s)r.issues.push(se(s,r.value,t));else{const t=s;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),t.continue??(t.continue=!0),r.issues.push(se(t))}};const n=t.transform(r.value,r);return n instanceof Promise?n.then(e=>(r.value=e,r)):(r.value=n,r)}});function ls(e){return new us({type:"transform",transform:e})}const hs=n("ZodOptional",(e,t)=>{Pt.init(e,t),hr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ps(e){return new hs({type:"optional",innerType:e})}const ms=n("ZodNullable",(e,t)=>{It.init(e,t),hr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function fs(e){return new ms({type:"nullable",innerType:e})}const gs=n("ZodDefault",(e,t)=>{Rt.init(e,t),hr.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),_s=n("ZodPrefault",(e,t)=>{Ct.init(e,t),hr.init(e,t),e.unwrap=()=>e._zod.def.innerType}),ys=n("ZodNonOptional",(e,t)=>{At.init(e,t),hr.init(e,t),e.unwrap=()=>e._zod.def.innerType}),vs=n("ZodCatch",(e,t)=>{jt.init(e,t),hr.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),ws=n("ZodPipe",(e,t)=>{zt.init(e,t),hr.init(e,t),e.in=t.in,e.out=t.out});function bs(e,t){return new ws({type:"pipe",in:e,out:t})}const ks=n("ZodReadonly",(e,t)=>{qt.init(e,t),hr.init(e,t)}),Ss=n("ZodCustom",(e,t)=>{Dt.init(e,t),hr.init(e,t)});function $s(e,t){return bs(ls(e),t)}const Es="2025-11-25",Ts=[Es,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],xs="io.modelcontextprotocol/related-task",Ps="2.0",Is=(Rs=e=>null!==e&&("object"==typeof e||"function"==typeof e),function(e,t,r){const s=B(r);return s.abort??(s.abort=!0),new e({type:"custom",check:"custom",fn:t,...s})}(Ss,Rs??(()=>!0),undefined));var Rs;const Os=Xr([fr(),Mr().int()]),Cs=fr(),As=(Qr({ttl:Xr([Mr(),Fr()]).optional(),pollInterval:Mr().optional()}),Br({ttl:Mr().optional()})),Ns=Br({taskId:fr()}),js=Qr({progressToken:Os.optional(),[xs]:Ns.optional()}),zs=Br({_meta:js.optional()}),Ms=zs.extend({task:As.optional()}),qs=Br({method:fr(),params:zs.loose().optional()}),Us=Br({_meta:js.optional()}),Ds=Br({method:fr(),params:Us.loose().optional()}),Ls=Qr({_meta:js.optional()}),Zs=Xr([fr(),Mr().int()]),Fs=Br({jsonrpc:ds(Ps),id:Zs,...qs.shape}).strict(),Hs=e=>Fs.safeParse(e).success,Vs=Br({jsonrpc:ds(Ps),...Ds.shape}).strict(),Ks=Br({jsonrpc:ds(Ps),id:Zs,result:Ls}).strict(),Gs=e=>Ks.safeParse(e).success;var Ws;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"}(Ws||(Ws={}));const Js=Br({jsonrpc:ds(Ps),id:Zs.optional(),error:Br({code:Mr().int(),message:fr(),data:Vr().optional()})}).strict(),Bs=Xr([Fs,Vs,Ks,Js]),Qs=(Xr([Ks,Js]),Ls.strict()),Ys=Us.extend({requestId:Zs.optional(),reason:fr().optional()}),Xs=Ds.extend({method:ds("notifications/cancelled"),params:Ys}),en=Br({src:fr(),mimeType:fr().optional(),sizes:Wr(fr()).optional(),theme:os(["light","dark"]).optional()}),tn=Br({icons:Wr(en).optional()}),rn=Br({name:fr(),title:fr().optional()}),sn=rn.extend({...rn.shape,...tn.shape,version:fr(),websiteUrl:fr().optional(),description:fr().optional()}),nn=ss(Br({applyDefaults:Lr().optional()}),is(fr(),Vr())),an=$s(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,ss(Br({form:nn.optional(),url:Is.optional()}),is(fr(),Vr()).optional())),on=Qr({list:Is.optional(),cancel:Is.optional(),requests:Qr({sampling:Qr({createMessage:Is.optional()}).optional(),elicitation:Qr({create:Is.optional()}).optional()}).optional()}),cn=Qr({list:Is.optional(),cancel:Is.optional(),requests:Qr({tools:Qr({call:Is.optional()}).optional()}).optional()}),dn=Br({experimental:is(fr(),Is).optional(),sampling:Br({context:Is.optional(),tools:Is.optional()}).optional(),elicitation:an.optional(),roots:Br({listChanged:Lr().optional()}).optional(),tasks:on.optional()}),un=zs.extend({protocolVersion:fr(),capabilities:dn,clientInfo:sn}),ln=qs.extend({method:ds("initialize"),params:un}),hn=Br({experimental:is(fr(),Is).optional(),logging:Is.optional(),completions:Is.optional(),prompts:Br({listChanged:Lr().optional()}).optional(),resources:Br({subscribe:Lr().optional(),listChanged:Lr().optional()}).optional(),tools:Br({listChanged:Lr().optional()}).optional(),tasks:cn.optional()}),pn=Ls.extend({protocolVersion:fr(),capabilities:hn,serverInfo:sn,instructions:fr().optional()}),mn=Ds.extend({method:ds("notifications/initialized"),params:Us.optional()}),fn=qs.extend({method:ds("ping"),params:zs.optional()}),gn=Br({progress:Mr(),total:ps(Mr()),message:ps(fr())}),_n=Br({...Us.shape,...gn.shape,progressToken:Os}),yn=Ds.extend({method:ds("notifications/progress"),params:_n}),vn=zs.extend({cursor:Cs.optional()}),wn=qs.extend({params:vn.optional()}),bn=Ls.extend({nextCursor:Cs.optional()}),kn=os(["working","input_required","completed","failed","cancelled"]),Sn=Br({taskId:fr(),status:kn,ttl:Xr([Mr(),Fr()]),createdAt:fr(),lastUpdatedAt:fr(),pollInterval:ps(Mr()),statusMessage:ps(fr())}),$n=Ls.extend({task:Sn}),En=Us.merge(Sn),Tn=Ds.extend({method:ds("notifications/tasks/status"),params:En}),xn=qs.extend({method:ds("tasks/get"),params:zs.extend({taskId:fr()})}),Pn=Ls.merge(Sn),In=qs.extend({method:ds("tasks/result"),params:zs.extend({taskId:fr()})}),Rn=(Ls.loose(),wn.extend({method:ds("tasks/list")})),On=bn.extend({tasks:Wr(Sn)}),Cn=qs.extend({method:ds("tasks/cancel"),params:zs.extend({taskId:fr()})}),An=Ls.merge(Sn),Nn=Br({uri:fr(),mimeType:ps(fr()),_meta:is(fr(),Vr()).optional()}),jn=Nn.extend({text:fr()}),zn=fr().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mn=Nn.extend({blob:zn}),qn=os(["user","assistant"]),Un=Br({audience:Wr(qn).optional(),priority:Mr().min(0).max(1).optional(),lastModified:rr({offset:!0}).optional()}),Dn=Br({...rn.shape,...tn.shape,uri:fr(),description:ps(fr()),mimeType:ps(fr()),annotations:Un.optional(),_meta:ps(Qr({}))}),Ln=Br({...rn.shape,...tn.shape,uriTemplate:fr(),description:ps(fr()),mimeType:ps(fr()),annotations:Un.optional(),_meta:ps(Qr({}))}),Zn=wn.extend({method:ds("resources/list")}),Fn=bn.extend({resources:Wr(Dn)}),Hn=wn.extend({method:ds("resources/templates/list")}),Vn=bn.extend({resourceTemplates:Wr(Ln)}),Kn=zs.extend({uri:fr()}),Gn=Kn,Wn=qs.extend({method:ds("resources/read"),params:Gn}),Jn=Ls.extend({contents:Wr(Xr([jn,Mn]))}),Bn=Ds.extend({method:ds("notifications/resources/list_changed"),params:Us.optional()}),Qn=Kn,Yn=qs.extend({method:ds("resources/subscribe"),params:Qn}),Xn=Kn,ei=qs.extend({method:ds("resources/unsubscribe"),params:Xn}),ti=Us.extend({uri:fr()}),ri=Ds.extend({method:ds("notifications/resources/updated"),params:ti}),si=Br({name:fr(),description:ps(fr()),required:ps(Lr())}),ni=Br({...rn.shape,...tn.shape,description:ps(fr()),arguments:ps(Wr(si)),_meta:ps(Qr({}))}),ii=wn.extend({method:ds("prompts/list")}),ai=bn.extend({prompts:Wr(ni)}),oi=zs.extend({name:fr(),arguments:is(fr(),fr()).optional()}),ci=qs.extend({method:ds("prompts/get"),params:oi}),di=Br({type:ds("text"),text:fr(),annotations:Un.optional(),_meta:is(fr(),Vr()).optional()}),ui=Br({type:ds("image"),data:zn,mimeType:fr(),annotations:Un.optional(),_meta:is(fr(),Vr()).optional()}),li=Br({type:ds("audio"),data:zn,mimeType:fr(),annotations:Un.optional(),_meta:is(fr(),Vr()).optional()}),hi=Br({type:ds("tool_use"),name:fr(),id:fr(),input:is(fr(),Vr()),_meta:is(fr(),Vr()).optional()}),pi=Br({type:ds("resource"),resource:Xr([jn,Mn]),annotations:Un.optional(),_meta:is(fr(),Vr()).optional()}),mi=Xr([di,ui,li,Dn.extend({type:ds("resource_link")}),pi]),fi=Br({role:qn,content:mi}),gi=Ls.extend({description:fr().optional(),messages:Wr(fi)}),_i=Ds.extend({method:ds("notifications/prompts/list_changed"),params:Us.optional()}),yi=Br({title:fr().optional(),readOnlyHint:Lr().optional(),destructiveHint:Lr().optional(),idempotentHint:Lr().optional(),openWorldHint:Lr().optional()}),vi=Br({taskSupport:os(["required","optional","forbidden"]).optional()}),wi=Br({...rn.shape,...tn.shape,description:fr().optional(),inputSchema:Br({type:ds("object"),properties:is(fr(),Is).optional(),required:Wr(fr()).optional()}).catchall(Vr()),outputSchema:Br({type:ds("object"),properties:is(fr(),Is).optional(),required:Wr(fr()).optional()}).catchall(Vr()).optional(),annotations:yi.optional(),execution:vi.optional(),_meta:is(fr(),Vr()).optional()}),bi=wn.extend({method:ds("tools/list")}),ki=bn.extend({tools:Wr(wi)}),Si=Ls.extend({content:Wr(mi).default([]),structuredContent:is(fr(),Vr()).optional(),isError:Lr().optional()}),$i=(Si.or(Ls.extend({toolResult:Vr()})),Ms.extend({name:fr(),arguments:is(fr(),Vr()).optional()})),Ei=qs.extend({method:ds("tools/call"),params:$i}),Ti=Ds.extend({method:ds("notifications/tools/list_changed"),params:Us.optional()}),xi=(Br({autoRefresh:Lr().default(!0),debounceMs:Mr().int().nonnegative().default(300)}),os(["debug","info","notice","warning","error","critical","alert","emergency"])),Pi=zs.extend({level:xi}),Ii=qs.extend({method:ds("logging/setLevel"),params:Pi}),Ri=Us.extend({level:xi,logger:fr().optional(),data:Vr()}),Oi=Ds.extend({method:ds("notifications/message"),params:Ri}),Ci=Br({name:fr().optional()}),Ai=Br({hints:Wr(Ci).optional(),costPriority:Mr().min(0).max(1).optional(),speedPriority:Mr().min(0).max(1).optional(),intelligencePriority:Mr().min(0).max(1).optional()}),Ni=Br({mode:os(["auto","required","none"]).optional()}),ji=Br({type:ds("tool_result"),toolUseId:fr().describe("The unique identifier for the corresponding tool call."),content:Wr(mi).default([]),structuredContent:Br({}).loose().optional(),isError:Lr().optional(),_meta:is(fr(),Vr()).optional()}),zi=ts("type",[di,ui,li]),Mi=ts("type",[di,ui,li,hi,ji]),qi=Br({role:qn,content:Xr([Mi,Wr(Mi)]),_meta:is(fr(),Vr()).optional()}),Ui=Ms.extend({messages:Wr(qi),modelPreferences:Ai.optional(),systemPrompt:fr().optional(),includeContext:os(["none","thisServer","allServers"]).optional(),temperature:Mr().optional(),maxTokens:Mr().int(),stopSequences:Wr(fr()).optional(),metadata:Is.optional(),tools:Wr(wi).optional(),toolChoice:Ni.optional()}),Di=qs.extend({method:ds("sampling/createMessage"),params:Ui}),Li=Ls.extend({model:fr(),stopReason:ps(os(["endTurn","stopSequence","maxTokens"]).or(fr())),role:qn,content:zi}),Zi=Ls.extend({model:fr(),stopReason:ps(os(["endTurn","stopSequence","maxTokens","toolUse"]).or(fr())),role:qn,content:Xr([Mi,Wr(Mi)])}),Fi=Br({type:ds("boolean"),title:fr().optional(),description:fr().optional(),default:Lr().optional()}),Hi=Br({type:ds("string"),title:fr().optional(),description:fr().optional(),minLength:Mr().optional(),maxLength:Mr().optional(),format:os(["email","uri","date","date-time"]).optional(),default:fr().optional()}),Vi=Br({type:os(["number","integer"]),title:fr().optional(),description:fr().optional(),minimum:Mr().optional(),maximum:Mr().optional(),default:Mr().optional()}),Ki=Br({type:ds("string"),title:fr().optional(),description:fr().optional(),enum:Wr(fr()),default:fr().optional()}),Gi=Br({type:ds("string"),title:fr().optional(),description:fr().optional(),oneOf:Wr(Br({const:fr(),title:fr()})),default:fr().optional()}),Wi=Br({type:ds("string"),title:fr().optional(),description:fr().optional(),enum:Wr(fr()),enumNames:Wr(fr()).optional(),default:fr().optional()}),Ji=Xr([Ki,Gi]),Bi=Xr([Br({type:ds("array"),title:fr().optional(),description:fr().optional(),minItems:Mr().optional(),maxItems:Mr().optional(),items:Br({type:ds("string"),enum:Wr(fr())}),default:Wr(fr()).optional()}),Br({type:ds("array"),title:fr().optional(),description:fr().optional(),minItems:Mr().optional(),maxItems:Mr().optional(),items:Br({anyOf:Wr(Br({const:fr(),title:fr()}))}),default:Wr(fr()).optional()})]),Qi=Xr([Wi,Ji,Bi]),Yi=Xr([Qi,Fi,Hi,Vi]),Xi=Xr([Ms.extend({mode:ds("form").optional(),message:fr(),requestedSchema:Br({type:ds("object"),properties:is(fr(),Yi),required:Wr(fr()).optional()})}),Ms.extend({mode:ds("url"),message:fr(),elicitationId:fr(),url:fr().url()})]),ea=qs.extend({method:ds("elicitation/create"),params:Xi}),ta=Us.extend({elicitationId:fr()}),ra=Ds.extend({method:ds("notifications/elicitation/complete"),params:ta}),sa=Ls.extend({action:os(["accept","decline","cancel"]),content:$s(e=>null===e?void 0:e,is(fr(),Xr([fr(),Mr(),Lr(),Wr(fr())])).optional())}),na=Br({type:ds("ref/resource"),uri:fr()}),ia=Br({type:ds("ref/prompt"),name:fr()}),aa=zs.extend({ref:Xr([ia,na]),argument:Br({name:fr(),value:fr()}),context:Br({arguments:is(fr(),fr()).optional()}).optional()}),oa=qs.extend({method:ds("completion/complete"),params:aa}),ca=Ls.extend({completion:Qr({values:Wr(fr()).max(100),total:ps(Mr().int()),hasMore:ps(Lr())})}),da=Br({uri:fr().startsWith("file://"),name:fr().optional(),_meta:is(fr(),Vr()).optional()}),ua=qs.extend({method:ds("roots/list"),params:zs.optional()}),la=Ls.extend({roots:Wr(da)}),ha=Ds.extend({method:ds("notifications/roots/list_changed"),params:Us.optional()});Xr([fn,ln,oa,Ii,ci,ii,Zn,Hn,Wn,Yn,ei,Ei,bi,xn,In,Rn,Cn]),Xr([Xs,yn,mn,ha,Tn]),Xr([Qs,Li,Zi,sa,la,Pn,On,$n]),Xr([fn,Di,ea,ua,xn,In,Rn,Cn]),Xr([Xs,yn,Oi,ri,Bn,Ti,_i,Tn,ra]),Xr([Qs,pn,ca,gi,ai,Fn,Vn,Jn,Si,ki,Pn,On,$n]);class pa extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){if(e===Ws.UrlElicitationRequired&&r){const e=r;if(e.elicitations)return new ma(e.elicitations,t)}return new pa(e,t,r)}}class ma extends pa{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Ws.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}const fa={none:0,error:1,warn:2,info:3,debug:4},ga={error:"error",warn:"warn",info:"info",log:"info",debug:"debug"},_a=(e,t)=>fa[e]<=fa[t],ya=e=>"string"==typeof e?e:JSON.stringify(e),va=(e,t)=>{let r=`[${ya(e)}]`;return typeof window<"u"?{text:`%c${r}`,style:`color: ${t.color||"#00bcd4"}; font-weight: bold;`}:{text:r}},wa=(e,t,r,s)=>(...n)=>{if(!_a(ga[e],s()))return;if(!t)return void console[e](...n);let{text:i,style:a}=va(t,r);a?console[e](i,a,...n):console[e](i,...n)},ba=(e,t)=>{let r=t.logLevel??"debug",s=()=>r;return{log:wa("log",e,t,s),info:wa("info",e,t,s),warn:wa("warn",e,t,s),error:wa("error",e,t,s),debug:wa("debug",e,t,s),setLogLevel:e=>{r=e},extend:s=>ba(e?((e,t)=>`${ya(e)} > ${ya(t)}`)(e,s):s,{...t,logLevel:r})}},ka=(e,t)=>ba(e,{color:"#00bcd4",logLevel:"debug",...t}),Sa=ka("angie-sdk",{color:"#00BCD4",logLevel:"error"}),$a=e=>Sa.extend(e),Ea=$a("iframe-utils");let Ta=null;const xa=()=>(Ta&&document.contains(Ta)||(Ta=document.querySelector('iframe[src*="angie/"]')),Ta),Pa=(e,t)=>{Ea.log("postMessageToAngieIframe",e,t);const r=xa();if(!r?.contentWindow)return!1;const s=t||(()=>{const e=xa();if(!e)return null;try{return new URL(e.src).origin}catch(e){return Ea.error("Error parsing iframe URL:",e),null}})();return s?(r.contentWindow.postMessage(e,s),!0):(Ea.error("Could not determine target origin for Angie iframe"),!1)};var Ia,Ra,Oa,Ca,Aa,Na,ja;(Ia||(Ia={})).POST_MESSAGE="postMessage",(Ra||(Ra={})).POST_MESSAGE="postMessage",function(e){e.STREAMABLE_HTTP="streamableHttp",e.SSE="sse"}(Oa||(Oa={})),function(e){e.LOCAL="local",e.REMOTE="remote"}(Ca||(Ca={})),function(e){e.SDK_ANGIE_READY_PING="sdk-angie-ready-ping",e.SDK_ANGIE_REFRESH_PING="sdk-angie-refresh-ping",e.SDK_ANGIE_ALL_SERVERS_REGISTERED="sdk-angie-all-servers-registered",e.SDK_REQUEST_CLIENT_CREATION="sdk-request-client-creation",e.SDK_REQUEST_INIT_SERVER="sdk-request-init-server",e.SDK_TRIGGER_ANGIE="sdk-trigger-angie",e.SDK_TRIGGER_ANGIE_RESPONSE="sdk-trigger-angie-response",e.ANGIE_SIDEBAR_RESIZED="angie-sidebar-resized",e.ANGIE_SIDEBAR_TOGGLED="angie-sidebar-toggled",e.ANGIE_CHAT_TOGGLE="angie-chat-toggle",e.ANGIE_STUDIO_TOGGLE="angie-studio-toggle",e.ANGIE_NAVIGATE_TO_URL="angie/navigate-to-url",e.ANGIE_PAGE_RELOAD="angie/page-reload",e.ANGIE_DISABLE_NAVIGATION_PREVENTION="angie/disable-navigation-prevention",e.ANGIE_NAVIGATE_AFTER_RESPONSE="angie/navigate-after-response"}(Aa||(Aa={})),function(e){e.SET="ANGIE_SET_LOCALSTORAGE",e.GET="ANGIE_GET_LOCALSTORAGE"}(Na||(Na={})),function(e){e.RESET_HASH="reset-hash",e.HOST_READY="host/ready",e.ANGIE_LOADED="angie/loaded",e.ANGIE_READY="angie/ready"}(ja||(ja={}));const za=$a("angie-detector");class Ma{isAngieReady=!1;readyPromise;readyResolve;constructor(){if(this.readyPromise=new Promise(e=>{this.readyResolve=e}),"undefined"==typeof window)return;let e=0;const t=()=>{if(this.isAngieReady||e>=500)return void(!this.isAngieReady&&e>=500&&this.handleDetectionTimeout());const r=new MessageChannel;r.port1.onmessage=e=>{this.handleAngieReady(e.data),r.port1.close(),r.port2.close()};const s={type:Aa.SDK_ANGIE_READY_PING,timestamp:Date.now()};window.postMessage(s,window.location.origin,[r.port2]),e++,setTimeout(t,500)};t()}handleAngieReady(e){this.isAngieReady=!0;const t={isReady:!0,version:e.version,capabilities:e.capabilities};this.readyResolve&&this.readyResolve(t)}handleDetectionTimeout(){this.readyResolve&&this.readyResolve({isReady:!1}),za.warn("Detection timeout - Angie may not be available")}isReady(){return this.isAngieReady}async waitForReady(){return this.readyPromise}}class qa{sessionId;onmessage;onerror;onclose;_port;_started=!1;_closed=!1;constructor(e){if(!e)throw new Error("MessagePort is required");this._port=e,this._port.onmessage=e=>{try{const t=Bs.parse(e.data);this.onmessage?.(t)}catch(e){const t=new Error(`Failed to parse message: ${e}`);this.onerror?.(t)}},this._port.onmessageerror=e=>{const t=new Error(`MessagePort error: ${JSON.stringify(e)}`);this.onerror?.(t)}}async start(){if(this._started)throw new Error("BrowserContextTransport already started! If using Client or Server class, note that connect() calls start() automatically.");if(this._closed)throw new Error("Cannot start a closed BrowserContextTransport");this._started=!0,this._port.start()}async send(e){if(this._closed)throw new Error("Cannot send on a closed BrowserContextTransport");return new Promise((t,r)=>{try{this._port.postMessage(e),t()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.onerror?.(t),r(t)}})}async close(){this._closed||(this._closed=!0,this._port.close(),this.onclose?.())}}class Ua{async requestClientCreation(e){const{config:t}=e,r={serverId:e.id,serverName:t.name,serverTitle:t.title,serverVersion:t.version,description:t.description,transport:t.transport||Ra.POST_MESSAGE,capabilities:t.capabilities,instanceId:e.instanceId};return"type"in t&&"remote"===t.type&&(r.remote={url:t.url}),new Promise((e,t)=>{const s=new MessageChannel,n=setTimeout(()=>{t(new Error("Client creation request timed out after 15000ms"))},15e3);s.port1.onmessage=t=>{clearTimeout(n),e(t.data)};const i={type:Aa.SDK_REQUEST_CLIENT_CREATION,payload:r,timestamp:Date.now()};window.postMessage(i,window.location.origin,[s.port2])})}}const Da="angie-sidebar-container",La={open:!1,iframe:null,iframeUrlObject:null,containerId:Da};class Za extends Error{}Za.prototype.name="InvalidTokenError";var Fa,Ha,Va,Ka={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},Ga=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(Ga||{});(Va=Ga||(Ga={})).reset=function(){Fa=3,Ha=Ka},Va.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");Fa=e},Va.setLogger=function(e){Ha=e};var Wa=class e{constructor(e){this._name=e}debug(...t){Fa>=4&&Ha.debug(e._format(this._name,this._method),...t)}info(...t){Fa>=3&&Ha.info(e._format(this._name,this._method),...t)}warn(...t){Fa>=2&&Ha.warn(e._format(this._name,this._method),...t)}error(...t){Fa>=1&&Ha.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,r){const s=new e(`${t}.${r}`);return s.debug("begin"),s}static _format(e,t){const r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(t,...r){Fa>=4&&Ha.debug(e._format(t),...r)}static info(t,...r){Fa>=3&&Ha.info(e._format(t),...r)}static warn(t,...r){Fa>=2&&Ha.warn(e._format(t),...r)}static error(t,...r){Fa>=1&&Ha.error(e._format(t),...r)}};Ga.reset();var Ja=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new Za("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,s=e.split(".")[r];if("string"!=typeof s)throw new Za(`Invalid token specified: missing part #${r+1}`);let n;try{n=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}(t)}catch(e){return atob(t)}}(s)}catch(e){throw new Za(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(n)}catch(e){throw new Za(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}(e)}catch(e){throw Wa.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,r){const s=`${Ya.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${Ya.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,n=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,(new TextEncoder).encode(s));return`${s}.${Ya.encodeBase64Url(new Uint8Array(n))}`}static async generateSignedJwtWithHmac(e,t,r){const s=`${Ya.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${Ya.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,n=await window.crypto.subtle.sign("HMAC",r,(new TextEncoder).encode(s));return`${s}.${Ya.encodeBase64Url(new Uint8Array(n))}`}},Ba=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join("")),Qa=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^e._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Ba(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw Wa.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const r=(new TextEncoder).encode([e,t].join(":"));return Ba(r)}static async hash(e,t){const r=(new TextEncoder).encode(t),s=await crypto.subtle.digest(e,r);return new Uint8Array(s)}static async customCalculateJwkThumbprint(t){let r;switch(t.kty){case"RSA":r={e:t.e,kty:t.kty,n:t.n};break;case"EC":r={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":r={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":r={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const s=await e.hash("SHA-256",JSON.stringify(r));return e.encodeBase64Url(s)}static async generateDPoPProof({url:t,accessToken:r,httpMethod:s,keyPair:n,nonce:i}){let a,o;const c={jti:window.crypto.randomUUID(),htm:null!=s?s:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};r&&(a=await e.hash("SHA-256",r),o=e.encodeBase64Url(a),c.ath=o),i&&(c.nonce=i);try{const e=await crypto.subtle.exportKey("jwk",n.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await Ja.generateSignedJwt(t,c,n.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{const r=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(r)}catch(e){throw e instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(t,r,s,n="HS256"){const i=Math.floor(Date.now()/1e3),a={alg:n,typ:"JWT"},o={iss:t,sub:t,aud:s,jti:e.generateUUIDv4(),exp:i+300,iat:i},c={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[n];if(!c)throw new Error(`Unsupported algorithm: ${n}. Supported algorithms are: HS256, HS384, HS512`);const d=new TextEncoder,u=await crypto.subtle.importKey("raw",d.encode(r),{name:"HMAC",hash:c},!1,["sign"]);return await Ja.generateSignedJwtWithHmac(a,o,u)}};Qa.encodeBase64Url=e=>Ba(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var Ya=Qa,Xa=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new Wa(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},eo=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find(e=>e<=window.outerWidth/1.618))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter(([,e])=>null!=e).map(([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`).join(",")}},to=class e extends Xa{constructor(){super(...arguments),this._logger=new Wa(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const r=this._logger.create("init");t=Math.max(Math.floor(t),1);const s=e.getEpochTime()+t;if(this.expiration===s&&this._timerHandle)return void r.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),r.debug("using duration",t),this._expiration=s;const n=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*n)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},ro=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const r=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(r.slice(1))}},so=";",no=class extends Error{constructor(e,t){var r,s,n;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw Wa.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(r=e.error_description)?r:null,this.error_uri=null!=(s=e.error_uri)?s:null,this.state=e.userState,this.session_state=null!=(n=e.session_state)?n:null,this.url_state=e.url_state}},io=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},ao=class{constructor(e){this._logger=new Wa("AccessTokenEvents"),this._expiringTimer=new to("Access token expiring"),this._expiredTimer=new to("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const r=e.expires_in;if(t.debug("access token present, remaining duration:",r),r>0){let e=r-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const s=r+1;t.debug("registering expired timer, raising in",s,"seconds"),this._expiredTimer.init(s)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},oo=class{constructor(e,t,r,s,n){this._callback=e,this._client_id=t,this._intervalInSeconds=s,this._stopOnError=n,this._logger=new Wa("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const i=new URL(r);this._frame_origin=i.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=i.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},co=class{constructor(){this._logger=new Wa("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},uo=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},lo=class{constructor(e=[],t=null,r={}){this._jwtHandler=t,this._extraHeaders=r,this._logger=new Wa("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:r,...s}=t;if(!r)return await fetch(e,s);const n=new AbortController,i=setTimeout(()=>n.abort(),1e3*r);try{return await fetch(e,{...t,signal:n.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new io("Network timed out");throw e}finally{clearTimeout(i)}}async getJson(e,{token:t,credentials:r,timeoutInSeconds:s}={}){const n=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let a;t&&(n.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t),this._appendExtraHeaders(i);try{n.debug("url:",e),a=await this.fetchWithTimeout(e,{method:"GET",headers:i,timeoutInSeconds:s,credentials:r})}catch(e){throw n.error("Network Error"),e}n.debug("HTTP response received, status",a.status);const o=a.headers.get("Content-Type");if(o&&!this._contentTypes.find(e=>o.startsWith(e))&&n.throw(new Error(`Invalid response Content-Type: ${null!=o?o:"undefined"}, from URL: ${e}`)),a.ok&&this._jwtHandler&&(null==o?void 0:o.startsWith("application/jwt")))return await this._jwtHandler(await a.text());let c;try{c=await a.json()}catch(e){if(n.error("Error parsing JSON response",e),a.ok)throw e;throw new Error(`${a.statusText} (${a.status})`)}if(!a.ok){if(n.error("Error from server:",c),c.error)throw new no(c);throw new Error(`${a.statusText} (${a.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:r,timeoutInSeconds:s,initCredentials:n,extraHeaders:i}){const a=this._logger.create("postForm"),o={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...i};let c;void 0!==r&&(o.Authorization="Basic "+r),this._appendExtraHeaders(o);try{a.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:o,body:t,timeoutInSeconds:s,credentials:n})}catch(e){throw a.error("Network error"),e}a.debug("HTTP response received, status",c.status);const d=c.headers.get("Content-Type");if(d&&!this._contentTypes.find(e=>d.startsWith(e)))throw new Error(`Invalid response Content-Type: ${null!=d?d:"undefined"}, from URL: ${e}`);const u=await c.text();let l={};if(u)try{l=JSON.parse(u)}catch(e){if(a.error("Error parsing JSON response",e),c.ok)throw e;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(a.error("Error from server:",l),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new uo(e,`${JSON.stringify(l)}`)}if(l.error)throw new no(l,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(l)}`)}return l}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),r=Object.keys(this._extraHeaders),s=["accept","content-type"],n=["authorization"];0!==r.length&&r.forEach(r=>{if(s.includes(r.toLocaleLowerCase()))return void t.warn("Protected header could not be set",r,s);if(n.includes(r.toLocaleLowerCase())&&Object.keys(e).includes(r))return void t.warn("Header could not be overridden",r,n);const i="function"==typeof this._extraHeaders[r]?this._extraHeaders[r]():this._extraHeaders[r];i&&""!==i&&(e[r]=i)})}},ho=class{constructor(e){this._settings=e,this._logger=new Wa("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new lo(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const r=this._logger.create(`_getMetadataProperty('${e}')`),s=await this.getMetadata();if(r.debug("resolved"),void 0===s[e]){if(!0===t)return void r.warn("Metadata does not contain optional property");r.throw(new Error("Metadata does not contain property "+e))}return s[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const r=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",r),!Array.isArray(r.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=r.keys,this._signingKeys}},po=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new Wa("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let r=0;r<e;r++){const e=await this._store.key(r);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},mo=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:s,metadataSeed:n,client_id:i,client_secret:a,response_type:o="code",scope:c="openid",redirect_uri:d,post_logout_redirect_uri:u,client_authentication:l="client_secret_post",token_endpoint_auth_signing_alg:h="HS256",prompt:p,display:m,max_age:f,ui_locales:g,acr_values:_,resource:y,response_mode:v,filterProtocolClaims:w=!0,loadUserInfo:b=!1,requestTimeoutInSeconds:k,staleStateAgeInSeconds:S=900,mergeClaimsStrategy:$={array:"replace"},disablePKCE:E=!1,stateStore:T,revokeTokenAdditionalContentTypes:x,fetchRequestCredentials:P,refreshTokenAllowedScope:I,extraQueryParams:R={},extraTokenParams:O={},extraHeaders:C={},dpop:A,omitScopeWhenRequesting:N=!1}){var j;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=r,this.metadataSeed=n,this.signingKeys=s,this.client_id=i,this.client_secret=a,this.response_type=o,this.scope=c,this.redirect_uri=d,this.post_logout_redirect_uri=u,this.client_authentication=l,this.token_endpoint_auth_signing_alg=h,this.prompt=p,this.display=m,this.max_age=f,this.ui_locales=g,this.acr_values=_,this.resource=y,this.response_mode=v,this.filterProtocolClaims=null==w||w,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=S,this.mergeClaimsStrategy=$,this.omitScopeWhenRequesting=N,this.disablePKCE=!!E,this.revokeTokenAdditionalContentTypes=x,this.fetchRequestCredentials=P||"same-origin",this.requestTimeoutInSeconds=k,T)this.stateStore=T;else{const e="undefined"!=typeof window?window.localStorage:new co;this.stateStore=new po({store:e})}if(this.refreshTokenAllowedScope=I,this.extraQueryParams=R,this.extraTokenParams=O,this.extraHeaders=C,this.dpop=A,this.dpop&&!(null==(j=this.dpop)?void 0:j.store))throw new Error("A DPoPStore is required when dpop is enabled")}},fo=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new Wa("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const r=Ja.decode(e);return t.debug("JWT decoding successful"),r}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new lo(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);const s=await this._jsonService.getJson(r,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",s),s}},go=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new Wa("TokenClient"),this._jsonService=new lo(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:r=this._settings.client_id,client_secret:s=this._settings.client_secret,extraHeaders:n,...i}){const a=this._logger.create("exchangeCode");r||a.throw(new Error("A client_id is required")),t||a.throw(new Error("A redirect_uri is required")),i.code||a.throw(new Error("A code is required"));const o=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(i))null!=t&&o.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==s)throw a.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=Ya.generateBasicAuth(r,s);break;case"client_secret_post":o.append("client_id",r),s&&o.append("client_secret",s);break;case"client_secret_jwt":{const e=await Ya.generateClientAssertionJwt(r,s,d,this._settings.token_endpoint_auth_signing_alg);o.append("client_id",r),o.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),o.append("client_assertion",e);break}}a.debug("got token endpoint");const u=await this._jsonService.postForm(d,{body:o,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:n});return a.debug("got response"),u}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,scope:s=this._settings.scope,...n}){const i=this._logger.create("exchangeCredentials");t||i.throw(new Error("A client_id is required"));const a=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||a.set("scope",s);for(const[e,t]of Object.entries(n))null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==r)throw i.throw(new Error("A client_secret is required")),null;let o;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":o=Ya.generateBasicAuth(t,r);break;case"client_secret_post":a.append("client_id",t),r&&a.append("client_secret",r);break;case"client_secret_jwt":{const e=await Ya.generateClientAssertionJwt(t,r,c,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}i.debug("got token endpoint");const d=await this._jsonService.postForm(c,{body:a,basicAuth:o,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return i.debug("got response"),d}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,timeoutInSeconds:s,extraHeaders:n,...i}){const a=this._logger.create("exchangeRefreshToken");t||a.throw(new Error("A client_id is required")),i.refresh_token||a.throw(new Error("A refresh_token is required"));const o=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(i))Array.isArray(t)?t.forEach(t=>o.append(e,t)):null!=t&&o.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==r)throw a.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=Ya.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r);break;case"client_secret_jwt":{const e=await Ya.generateClientAssertionJwt(t,r,d,this._settings.token_endpoint_auth_signing_alg);o.append("client_id",t),o.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),o.append("client_assertion",e);break}}a.debug("got token endpoint");const u=await this._jsonService.postForm(d,{body:o,basicAuth:c,timeoutInSeconds:s,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:n});return a.debug("got response"),u}async revoke(e){var t;const r=this._logger.create("revoke");e.token||r.throw(new Error("A token is required"));const s=await this._metadataService.getRevocationEndpoint(!1);r.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const n=new URLSearchParams;for(const[t,r]of Object.entries(e))null!=r&&n.set(t,r);n.set("client_id",this._settings.client_id),this._settings.client_secret&&n.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(s,{body:n,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),r.debug("got response")}},_o=class{constructor(e,t,r){this._settings=e,this._metadataService=t,this._claimsService=r,this._logger=new Wa("ResponseValidator"),this._userInfoService=new fo(this._settings,this._metadataService),this._tokenClient=new go(this._settings,this._metadataService)}async validateSigninResponse(e,t,r){const s=this._logger.create("validateSigninResponse");this._processSigninState(e,t),s.debug("state processed"),await this._processCode(e,t,r),s.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),s.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),s.debug("claims processed")}async validateCredentialsResponse(e,t){const r=this._logger.create("validateCredentialsResponse"),s=e.isOpenId&&!!e.id_token;s&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t,s),r.debug("claims processed")}async validateRefreshResponse(e,t){const r=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),r.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const s=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,s),r.debug("claims processed")}validateSignoutResponse(e,t){const r=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&r.throw(new Error("State does not match")),r.debug("state validated"),e.userState=t.data,e.error)throw r.warn("Response was error",e.error),new no(e)}_processSigninState(e,t){const r=this._logger.create("_processSigninState");if(t.id!==e.state&&r.throw(new Error("State does not match")),t.client_id||r.throw(new Error("No client_id on state")),t.authority||r.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&r.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&r.throw(new Error("client_id mismatch on settings vs. signin state")),r.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw r.warn("Response was error",e.error),new no(e);t.code_verifier&&!e.code&&r.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,r=!0){const s=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void s.debug("not loading user info");s.debug("loading user info");const n=await this._userInfoService.getClaims(e.access_token);s.debug("user info claims received from user info endpoint"),r&&n.sub!==e.profile.sub&&s.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(n)),s.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,r){const s=this._logger.create("_processCode");if(e.code){s.debug("Validating code");const n=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:r,...t.extraTokenParams});Object.assign(e,n)}else s.debug("No code to process")}_validateIdTokenAttributes(e,t){var r;const s=this._logger.create("_validateIdTokenAttributes");s.debug("decoding ID Token JWT");const n=Ja.decode(null!=(r=e.id_token)?r:"");if(n.sub||s.throw(new Error("ID Token is missing a subject claim")),t){const e=Ja.decode(t);n.sub!==e.sub&&s.throw(new Error("sub in id_token does not match current sub")),n.auth_time&&n.auth_time!==e.auth_time&&s.throw(new Error("auth_time in id_token does not match original auth_time")),n.azp&&n.azp!==e.azp&&s.throw(new Error("azp in id_token does not match original azp")),!n.azp&&e.azp&&s.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=n}},yo=class e{constructor(e){this.id=e.id||Ya.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=to.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new Wa("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return Wa.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,r){const s=Wa.createStatic("State","clearStaleState"),n=to.getEpochTime()-r,i=await t.getAllKeys();s.debug("got keys",i);for(let r=0;r<i.length;r++){const a=i[r],o=await t.get(a);let c=!1;if(o)try{const t=await e.fromStorageString(o);s.debug("got item from key:",a,t.created),t.created<=n&&(c=!0)}catch(e){s.error("Error parsing state for key:",a,e),c=!0}else s.debug("no item in storage for key:",a),c=!0;c&&(s.debug("removed item for key:",a),t.remove(a))}}},vo=class e extends yo{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const r=!0===t.code_verifier?Ya.generateCodeVerifier():t.code_verifier||void 0,s=r?await Ya.generateCodeChallenge(r):void 0;return new e({...t,code_verifier:r,code_challenge:s})}toStorageString(){return new Wa("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){Wa.createStatic("SigninState","fromStorageString");const r=JSON.parse(t);return e.create(r)}},wo=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:r,client_id:s,redirect_uri:n,response_type:i,scope:a,state_data:o,response_mode:c,request_type:d,client_secret:u,nonce:l,url_state:h,resource:p,skipUserInfo:m,extraQueryParams:f,extraTokenParams:g,disablePKCE:_,dpopJkt:y,omitScopeWhenRequesting:v,...w}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!s)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!n)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!i)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!a)throw this._logger.error("create: No scope passed"),new Error("scope");if(!r)throw this._logger.error("create: No authority passed"),new Error("authority");const b=await vo.create({data:o,request_type:d,url_state:h,code_verifier:!_,client_id:s,authority:r,redirect_uri:n,response_mode:c,client_secret:u,scope:a,extraTokenParams:g,skipUserInfo:m}),k=new URL(t);k.searchParams.append("client_id",s),k.searchParams.append("redirect_uri",n),k.searchParams.append("response_type",i),v||k.searchParams.append("scope",a),l&&k.searchParams.append("nonce",l),y&&k.searchParams.append("dpop_jkt",y);let S=b.id;h&&(S=`${S}${so}${h}`),k.searchParams.append("state",S),b.code_challenge&&(k.searchParams.append("code_challenge",b.code_challenge),k.searchParams.append("code_challenge_method","S256")),p&&(Array.isArray(p)?p:[p]).forEach(e=>k.searchParams.append("resource",e));for(const[e,t]of Object.entries({response_mode:c,...w,...f}))null!=t&&k.searchParams.append(e,t.toString());return new e({url:k.href,state:b})}};wo._logger=new Wa("SigninRequest");var bo=wo,ko=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(so);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(so))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-to.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+to.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},So=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:s,extraQueryParams:n,request_type:i,client_id:a,url_state:o}){if(this._logger=new Wa("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(r&&c.searchParams.append("id_token_hint",r),a&&c.searchParams.append("client_id",a),s&&(c.searchParams.append("post_logout_redirect_uri",s),t||o)){this.state=new yo({data:t,request_type:i,url_state:o});let e=this.state.id;o&&(e=`${e}${so}${o}`),c.searchParams.append("state",e)}for(const[e,t]of Object.entries({...n}))null!=t&&c.searchParams.append(e,t.toString());this.url=c.href}},$o=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(so);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(so))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},Eo=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],To=["sub","iss","aud","exp","iat"],xo=class{constructor(e){this._settings=e,this._logger=new Wa("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:Eo;for(const r of e)To.includes(r)||delete t[r]}return t}mergeClaims(e,t){const r={...e};for(const[e,s]of Object.entries(t))if(r[e]!==s)if(Array.isArray(r[e])||Array.isArray(s))if("replace"==this._settings.mergeClaimsStrategy.array)r[e]=s;else{const t=Array.isArray(r[e])?r[e]:[r[e]];for(const e of Array.isArray(s)?s:[s])t.includes(e)||t.push(e);r[e]=t}else"object"==typeof r[e]&&"object"==typeof s?r[e]=this.mergeClaims(r[e],s):r[e]=s;return r}},Po=class{constructor(e,t){this.keys=e,this.nonce=t}},Io=class{constructor(e,t){this._logger=new Wa("OidcClient"),this.settings=e instanceof mo?e:new mo(e),this.metadataService=null!=t?t:new ho(this.settings),this._claimsService=new xo(this.settings),this._validator=new _o(this.settings,this.metadataService,this._claimsService),this._tokenClient=new go(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:r,request_type:s,id_token_hint:n,login_hint:i,skipUserInfo:a,nonce:o,url_state:c,response_type:d=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:l=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:p=this.settings.display,max_age:m=this.settings.max_age,ui_locales:f=this.settings.ui_locales,acr_values:g=this.settings.acr_values,resource:_=this.settings.resource,response_mode:y=this.settings.response_mode,extraQueryParams:v=this.settings.extraQueryParams,extraTokenParams:w=this.settings.extraTokenParams,dpopJkt:b,omitScopeWhenRequesting:k=this.settings.omitScopeWhenRequesting}){const S=this._logger.create("createSigninRequest");if("code"!==d)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const $=await this.metadataService.getAuthorizationEndpoint();S.debug("Received authorization endpoint",$);const E=await bo.create({url:$,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:l,response_type:d,scope:u,state_data:e,url_state:c,prompt:h,display:p,max_age:m,ui_locales:f,id_token_hint:n,login_hint:i,acr_values:g,dpopJkt:b,resource:_,request:t,request_uri:r,extraQueryParams:v,extraTokenParams:w,request_type:s,response_mode:y,client_secret:this.settings.client_secret,skipUserInfo:a,nonce:o,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:k});await this.clearStaleState();const T=E.state;return await this.settings.stateStore.set(T.id,T.toStorageString()),E}async readSigninResponseState(e,t=!1){const r=this._logger.create("readSigninResponseState"),s=new ko(ro.readParams(e,this.settings.response_mode));if(!s.state)throw r.throw(new Error("No state in response")),null;const n=await this.settings.stateStore[t?"remove":"get"](s.state);if(!n)throw r.throw(new Error("No matching state found in storage")),null;return{state:await vo.fromStorageString(n),response:s}}async processSigninResponse(e,t,r=!0){const s=this._logger.create("processSigninResponse"),{state:n,response:i}=await this.readSigninResponseState(e,r);if(s.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(i,n,t)}catch(e){if(!(e instanceof uo&&this.settings.dpop))throw e;{const r=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=r,await this._validator.validateSigninResponse(i,n,t)}}return i}async getDpopProof(e,t){let r,s;return(await e.getAllKeys()).includes(this.settings.client_id)?(s=await e.get(this.settings.client_id),s.nonce!==t&&t&&(s.nonce=t,await e.set(this.settings.client_id,s))):(r=await Ya.generateDPoPKeys(),s=new Po(r,t),await e.set(this.settings.client_id,s)),await Ya.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:s.keys,nonce:s.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r=!1,extraTokenParams:s={}}){const n=await this._tokenClient.exchangeCredentials({username:e,password:t,...s}),i=new ko(new URLSearchParams);return Object.assign(i,n),await this._validator.validateCredentialsResponse(i,r),i}async useRefreshToken({state:e,redirect_uri:t,resource:r,timeoutInSeconds:s,extraHeaders:n,extraTokenParams:i}){var a;const o=this._logger.create("useRefreshToken");let c,d;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(a=e.scope)?void 0:a.split(" "))||[]).filter(e=>t.includes(e)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);n={...n,DPoP:e}}try{d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:s,extraHeaders:n,...i})}catch(a){if(!(a instanceof uo&&this.settings.dpop))throw a;n.DPoP=await this.getDpopProof(this.settings.dpop.store,a.nonce),d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:s,extraHeaders:n,...i})}const u=new ko(new URLSearchParams);return Object.assign(u,d),o.debug("validating response",u),await this._validator.validateRefreshResponse(u,{...e,scope:c}),u}async createSignoutRequest({state:e,id_token_hint:t,client_id:r,request_type:s,url_state:n,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:a=this.settings.extraQueryParams}={}){const o=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw o.throw(new Error("No end session endpoint")),null;o.debug("Received end session endpoint",c),r||!i||t||(r=this.settings.client_id);const d=new So({url:c,id_token_hint:t,client_id:r,post_logout_redirect_uri:i,state_data:e,extraQueryParams:a,request_type:s,url_state:n});await this.clearStaleState();const u=d.state;return u&&(o.debug("Signout request has state to persist"),await this.settings.stateStore.set(u.id,u.toStorageString())),d}async readSignoutResponseState(e,t=!1){const r=this._logger.create("readSignoutResponseState"),s=new $o(ro.readParams(e,this.settings.response_mode));if(!s.state){if(r.debug("No state in response"),s.error)throw r.warn("Response was error:",s.error),new no(s);return{state:void 0,response:s}}const n=await this.settings.stateStore[t?"remove":"get"](s.state);if(!n)throw r.throw(new Error("No matching state found in storage")),null;return{state:await yo.fromStorageString(n),response:s}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:r,response:s}=await this.readSignoutResponseState(e,!0);return r?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(s,r)):t.debug("No state from storage; skipping response validation"),s}clearStaleState(){return this._logger.create("clearStaleState"),yo.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},Ro=class{constructor(e){this._userManager=e,this._logger=new Wa("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const r=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,r.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,r.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){r.debug("initializing check session iframe");const s=this._userManager.settings.client_id,n=this._userManager.settings.checkSessionIntervalInSeconds,i=this._userManager.settings.stopCheckSessionOnError,a=new oo(this._callback,s,e,n,i);await a.load(),this._checkSessionIFrame=a,a.start(t)}else r.warn("no check session iframe found in the metadata")}catch(e){r.error("Error from getCheckSessionIframe:",e instanceof Error?e.message:e)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval(async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(t){e.error("error from querySessionStatus",t instanceof Error?t.message:t)}},1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let r=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(r=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),r?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(e=>{this._logger.error(e)})}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},Oo=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-to.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+to.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new Wa("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return Wa.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},Co="oidc-client",Ao=class{constructor(){this._abort=new Xa("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:r,keepOpen:s}=await new Promise((r,s)=>{const n=n=>{var i;const a=n.data,o=null!=(i=e.scriptOrigin)?i:window.location.origin;if(n.origin===o&&(null==a?void 0:a.source)===Co){try{const r=ro.readParams(a.url,e.response_mode).get("state");if(r||t.warn("no state found in response url"),n.source!==this._window&&r!==e.state)return}catch{this._dispose(),s(new Error("Invalid response from window"))}r(a)}};window.addEventListener("message",n,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",n,!1));const i=new BroadcastChannel(`oidc-client-popup-${e.state}`);i.addEventListener("message",n,!1),this._disposeHandlers.add(()=>i.close()),this._disposeHandlers.add(this._abort.addHandler(e=>{this._dispose(),s(e)}))});return t.debug("got response from window"),this._dispose(),s||this.close(),{url:r}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,r=!1,s=window.location.origin){const n={source:Co,url:t,keepOpen:r},i=new Wa("_notifyParent");if(e)i.debug("With parent. Using parent.postMessage."),e.postMessage(n,s);else{i.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const r=new BroadcastChannel(`oidc-client-popup-${e}`);r.postMessage(n),r.close()}}},No={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},jo="_blank",zo=60,Mo=2,qo=class extends mo{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:r=e.post_logout_redirect_uri,popupWindowFeatures:s=No,popupWindowTarget:n=jo,redirectMethod:i="assign",redirectTarget:a="self",iframeNotifyParentOrigin:o=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:d,silent_redirect_uri:u=e.redirect_uri,silentRequestTimeoutInSeconds:l,automaticSilentRenew:h=!0,validateSubOnSilentRenew:p=!0,includeIdTokenInSilentRenew:m=!1,monitorSession:f=!1,monitorAnonymousSession:g=!1,checkSessionIntervalInSeconds:_=Mo,query_status_response_type:y="code",stopCheckSessionOnError:v=!0,revokeTokenTypes:w=["access_token","refresh_token"],revokeTokensOnSignout:b=!1,includeIdTokenInSilentSignout:k=!1,accessTokenExpiringNotificationTimeInSeconds:S=zo,userStore:$}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=r,this.popupWindowFeatures=s,this.popupWindowTarget=n,this.redirectMethod=i,this.redirectTarget=a,this.iframeNotifyParentOrigin=o,this.iframeScriptOrigin=c,this.silent_redirect_uri=u,this.silentRequestTimeoutInSeconds=l||d||10,this.automaticSilentRenew=h,this.validateSubOnSilentRenew=p,this.includeIdTokenInSilentRenew=m,this.monitorSession=f,this.monitorAnonymousSession=g,this.checkSessionIntervalInSeconds=_,this.stopCheckSessionOnError=v,this.query_status_response_type=y,this.revokeTokenTypes=w,this.revokeTokensOnSignout=b,this.includeIdTokenInSilentSignout=k,this.accessTokenExpiringNotificationTimeInSeconds=S,$)this.userStore=$;else{const e="undefined"!=typeof window?window.sessionStorage:new co;this.userStore=new po({store:e})}}},Uo=class e extends Ao{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new Wa("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout(()=>{this._abort.raise(new io("IFrame timed out without a response"))},1e3*this._timeoutInSeconds);return this._disposeHandlers.add(()=>clearTimeout(t)),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",e=>{var t;const r=e.target;null==(t=r.parentNode)||t.removeChild(r),this._abort.raise(new Error("IFrame removed from DOM"))},!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},Do=class{constructor(e){this._settings=e,this._logger=new Wa("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new Uo({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),Uo.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},Lo=class extends Ao{constructor({popupWindowTarget:e=jo,popupWindowFeatures:t={},popupSignal:r,popupAbortOnClose:s}){super(),this._logger=new Wa("PopupWindow");const n=eo.center({...No,...t});this._window=window.open(void 0,e,eo.serialize(n)),this.abortOnClose=Boolean(s),r&&r.addEventListener("abort",()=>{var e;this._abort.raise(new Error(null!=(e=r.reason)?e:"Popup aborted"))}),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))},1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const r=setInterval(()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),s(),this._disposeHandlers.delete(s),this.abortOnClose&&this._abort.raise(new Error("Popup closed by user")))},500),s=()=>clearInterval(r);return this._disposeHandlers.add(s),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},Zo=class{constructor(e){this._settings=e,this._logger=new Wa("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:r,popupAbortOnClose:s}){return new Lo({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:r,popupAbortOnClose:s})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),Lo.notifyOpener(e,t)}},Fo=class{constructor(e){this._settings=e,this._logger=new Wa("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var r;this._logger.create("prepare");let s=window.self;"top"===t&&(s=null!=(r=window.top)?r:window.self);const n=s.location[e].bind(s.location);let i;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise((t,r)=>{i=r,window.addEventListener("pageshow",()=>t(window.location.href)),n(e.url)});return await t},close:()=>{this._logger.create("close"),null==i||i(new Error("Redirect aborted")),s.stop()}}}async callback(){}},Ho=class extends ao{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new Wa("UserManagerEvents"),this._userLoaded=new Xa("User loaded"),this._userUnloaded=new Xa("User unloaded"),this._silentRenewError=new Xa("Silent renew error"),this._userSignedIn=new Xa("User signed in"),this._userSignedOut=new Xa("User signed out"),this._userSessionChanged=new Xa("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},Vo=class{constructor(e){this._userManager=e,this._logger=new Wa("SilentRenewService"),this._isStarted=!1,this._retryTimer=new to("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof io)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},Ko=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},Go=class{constructor(e,t,r,s){this._logger=new Wa("UserManager"),this.settings=new qo(e),this._client=new Io(e),this._redirectNavigator=null!=t?t:new Fo(this.settings),this._popupNavigator=null!=r?r:new Zo(this.settings),this._iframeNavigator=null!=s?s:new Do(this.settings),this._events=new Ho(this.settings),this._silentRenewService=new Vo(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new Ro(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),r=await this._loadUser();return r?(t.info("user loaded"),await this._events.load(r,e),r):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:r,...s}=e;let n;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(n=await this.generateDPoPJkt(this.settings.dpop));const i=await this._redirectNavigator.prepare({redirectMethod:r});await this._signinStart({request_type:"si:r",dpopJkt:n,...s},i)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),r=await this._signinEnd(e);return r.profile&&r.profile.sub?t.info("success, signed in subject",r.profile.sub):t.info("no subject"),r}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:r=!1}){const s=this._logger.create("signinResourceOwnerCredential"),n=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r,extraTokenParams:this.settings.extraTokenParams});s.debug("got signin response");const i=await this._buildUser(n);return i.profile&&i.profile.sub?s.info("success, signed in subject",i.profile.sub):s.info("no subject"),i}async signinPopup(e={}){var t;const r=this._logger.create("signinPopup");let s;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:n,popupWindowTarget:i,popupSignal:a,popupAbortOnClose:o,...c}=e,d=this.settings.popup_redirect_uri;d||r.throw(new Error("No popup_redirect_uri configured"));const u=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:i,popupSignal:a,popupAbortOnClose:o}),l=await this._signin({request_type:"si:p",redirect_uri:d,display:"popup",dpopJkt:s,...c},u);return l&&(l.profile&&l.profile.sub?r.info("success, signed in subject",l.profile.sub):r.info("no subject")),l}async signinPopupCallback(e=window.location.href,t=!1){const r=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async signinSilent(e={}){var t,r;const s=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:n,...i}=e;let a,o=await this._loadUser();if(!e.forceIframeAuth&&(null==o?void 0:o.refresh_token)){s.debug("using refresh token");const e=new Ko(o);return await this._useRefreshToken({state:e,redirect_uri:i.redirect_uri,resource:i.resource,extraTokenParams:i.extraTokenParams,timeoutInSeconds:n})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(a=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let d;c||s.throw(new Error("No silent_redirect_uri configured")),o&&this.settings.validateSubOnSilentRenew&&(s.debug("subject prior to silent renew:",o.profile.sub),d=o.profile.sub);const u=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n});return o=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==o?void 0:o.id_token:void 0,dpopJkt:a,...i},u,d),o&&((null==(r=o.profile)?void 0:r.sub)?s.info("success, signed in subject",o.profile.sub):s.info("no subject")),o}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),r=new Oo({...e.state,...t});return await this.storeUser(r),await this._events.load(r),r}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:r}=await this._client.readSignoutResponseState(e);if(r)switch(r.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:r,...s}=e,n=this.settings.silent_redirect_uri;n||t.throw(new Error("No silent_redirect_uri configured"));const i=await this._loadUser(),a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r}),o=await this._signinStart({request_type:"si:s",redirect_uri:n,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==i?void 0:i.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...s},a);try{const e={},r=await this._client.processSigninResponse(o.url,e);return t.debug("got signin response"),r.session_state&&r.profile.sub?(t.info("success for subject",r.profile.sub),{session_state:r.session_state,sub:r.profile.sub}):(t.info("success, user not authenticated"),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof no)switch(e.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:e.session_state}}throw e}}async _signin(e,t,r){const s=await this._signinStart(e,t);return await this._signinEnd(s.url,r)}async _signinStart(e,t){const r=this._logger.create("_signinStart");try{const s=await this._client.createSigninRequest(e);return r.debug("got signin request"),await t.navigate({url:s.url,state:s.state.id,response_mode:s.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signinEnd(e,t){const r=this._logger.create("_signinEnd"),s=await this._client.processSigninResponse(e,{});return r.debug("got signin response"),await this._buildUser(s,t)}async _buildUser(e,t){const r=this._logger.create("_buildUser"),s=new Oo(e);if(t){if(t!==s.profile.sub)throw r.debug("current user does not match user returned from signin. sub from signin:",s.profile.sub),new no({...e,error:"login_required"});r.debug("current user matches user returned from signin")}return await this.storeUser(s),r.debug("user stored"),await this._events.load(s),s}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:r,...s}=e,n=await this._redirectNavigator.prepare({redirectMethod:r});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...s},n),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),r=await this._signoutEnd(e);return t.info("success"),r}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:r,popupWindowTarget:s,popupSignal:n,...i}=e,a=this.settings.popup_post_logout_redirect_uri,o=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:s,popupSignal:n});await this._signout({request_type:"so:p",post_logout_redirect_uri:a,state:null==a?void 0:{},...i},o),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const r=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async _signout(e,t){const r=await this._signoutStart(e,t);return await this._signoutEnd(r.url)}async _signoutStart(e={},t){var r;const s=this._logger.create("_signoutStart");try{const n=await this._loadUser();s.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(n);const i=e.id_token_hint||n&&n.id_token;i&&(s.debug("setting id_token_hint in signout request"),e.id_token_hint=i),await this.removeUser(),s.debug("user removed, creating signout request");const a=await this._client.createSignoutRequest(e);return s.debug("got signout request"),await t.navigate({url:a.url,state:null==(r=a.state)?void 0:r.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw s.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),r=await this._client.processSignoutResponse(e);return t.debug("got signout response"),r}async signoutSilent(e={}){var t;const r=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:s,...n}=e,i=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,a=this.settings.popup_post_logout_redirect_uri,o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});await this._signout({request_type:"so:s",post_logout_redirect_uri:a,id_token_hint:i,...n},o),r.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const r=this._logger.create("_revokeInternal");if(!e)return;const s=t.filter(t=>"string"==typeof e[t]);if(s.length){for(const t of s)await this._client.revokeToken(e[t],t),r.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),r.debug("user stored"),await this._events.load(e)}else r.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),Oo.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const r=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,r)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,r,s){var n,i;const a=await(null==(i=null==(n=this.settings.dpop)?void 0:n.store)?void 0:i.get(this.settings.client_id));if(a)return await Ya.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:r,keyPair:a.keys,nonce:s})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const r=await Ya.generateDPoPKeys();t=new Po(r),await e.store.set(this.settings.client_id,t)}return await Ya.generateDPoPJkt(t.keys)}};const Wo="OAUTH2_LOGIN_FLOW_COMPLETE_EVENT",Jo="OAUTH_GET_TOP_URL",Bo="OAUTH_REDIRECT_TOP_WINDOW",Qo="OAUTH_UPDATE_URL",Yo="OAUTH2_CHECK_PENDING",Xo="oauth2_top_origin",ec="oauth2_login_success",tc="oauth2_state",rc=60,sc=Math.max(rc-15,20),nc=ka("oidc-auth",{color:"green"}),ic=e=>nc.extend(e);ka("oidc-auth-utils");const ac=()=>"undefined"==typeof window?"":new URLSearchParams(window.location.search).get("origin")||"";class oc{static instance=null;settings=null;constructor(){}static getInstance(){return oc.instance||(oc.instance=new oc),oc.instance}configure(e){this.settings=e}isConfigured(){return null!==this.settings}getSettings(){if(!this.settings)throw new Error("OidcAuthConfig not configured. Call configure() or pass settings to OidcAuthClient.initialize().");return this.settings}getAuthOrigin(){const{authOrigin:e,authEndpoint:t}=this.getSettings();return e||new URL(t).origin}isAccessTokenProactiveRefreshEnabled(){return this.settings?.accessTokenProactiveRefreshEnabled??!0}getOidcSettings(){const e="undefined"==typeof window?"":window.location.origin,{clientId:t,authEndpoint:r}=this.getSettings(),s=this.getAuthOrigin(),n="undefined"!=typeof window?new po({store:window.localStorage}):void 0,{accessTokenExpiringNotificationTimeInSeconds:i=rc}=this.getSettings();return{client_id:t,authority:s,redirect_uri:`${e}/login/oauth-callback`,post_logout_redirect_uri:e,response_type:"code",scope:"openid offline_access",automaticSilentRenew:!1,accessTokenExpiringNotificationTimeInSeconds:i,stateStore:n,userStore:n,metadata:{issuer:s,authorization_endpoint:r,token_endpoint:`${s}/connect/api/v1/oauth2/token`,end_session_endpoint:`${s}/logout/`}}}getAccessTokenExpiringNotificationTimeInSeconds(){return this.getSettings().accessTokenExpiringNotificationTimeInSeconds??rc}getAccessTokenFreshnessThresholdInSeconds(){return this.getSettings().accessTokenFreshnessThresholdInSeconds??sc}getAllowedParentOrigins(){return this.settings?.allowedParentOrigins}}const cc=oc.getInstance(),dc=ic("oidc-auth:host-api"),uc=async e=>new Promise((t,r)=>{const s=new MessageChannel;let n=!1;const i=()=>{n=!0,s.port1.close()},a=setTimeout(()=>{n||(i(),r(new Error(`Host message timeout: ${e.type}`)))},1e4);s.port1.onmessage=e=>{clearTimeout(a),i(),"success"!==e.data.status?r(e.data.payload):t(e.data.payload)};const o=new URLSearchParams(window.location.search).get("origin")||"";if(!function(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return!1;const t=cc.getAllowedParentOrigins();return!t||0===t.length||t.includes(e)}(o))return clearTimeout(a),i(),void r(new Error("Origin not allowed"));dc.log("posting message to host",e),window.top.postMessage({type:e.type,payload:e.payload,...e.data||{}},o,[s.port2])}),lc=ic("oidc-auth:OidcAuthTimer");class hc{timerHandle=null;expiration=null;initialized=!1;callback=()=>{};constructor(){this.timerHandle=null}init(e,t,r){const s=e-this.getEpochTime(),n=Math.max(s-t,10);this.cancel(),this.expiration=n,this.callback=r,lc.debug("OIDC: timer - using expiration",n,s,t,e,s-t),this.timerHandle=setTimeout(this.callback,1e3*n),this.initialized=!0}cancel(){this.timerHandle&&(clearTimeout(this.timerHandle),this.timerHandle=null),this.expiration=null}getEpochTime(){return Math.floor(Date.now()/1e3)}isInitialized(){return this.initialized}}const pc=ic("oidc-auth:OidcAuthClient");class mc{static instance=null;userManager=null;initialized=!1;accessTokenExpiringTimer=null;retryTimers=new Set;constructor(){}static getInstance(){return mc.instance||(mc.instance=new mc),mc.instance}isInitialized(){return this.initialized}ensureInitialized(){if(!this.userManager)throw new Error("OidcAuthClient not initialized. Call initialize() first.");return this.userManager}initialize(e){if(e&&(this.initialized=!1,cc.configure(e)),this.initialized)pc.info("OIDC: initialize() - already initialized, skipping");else if("undefined"!=typeof window)if(cc.isConfigured())try{pc.info("OIDC: initialize() - starting initialization");const e=cc.getOidcSettings();this.userManager=new Go(e),Ga.setLogger(pc),Ga.setLevel(Ga.ERROR),this.initAccessTokenExpiringTimer(),this.initialized=!0}catch(e){throw pc.error("OIDC: initialize() - FAILED:",e),e}else pc.warn("OIDC: initialize() - skipped, config not set");else pc.warn("OidcAuthClient cannot initialize on server side")}async initAccessTokenExpiringTimer(){cc.isAccessTokenProactiveRefreshEnabled()?this.getUser().then(e=>{const t=e?.expires_at;t&&(this.accessTokenExpiringTimer||(this.accessTokenExpiringTimer=new hc),this.accessTokenExpiringTimer.init(t,cc.getAccessTokenExpiringNotificationTimeInSeconds(),async()=>{pc.info("OIDC: timer proactive refresh access token expiring timer fired",t),this.proactiveRefreshWithRetry()}))}).catch(e=>{pc.error("OIDC: initAccessTokenExpiringTimer - FAILED:",e)}):pc.warn("OIDC: timer - not starting, access token proactive refresh is disabled")}async getUser(){if(!this.userManager)return null;try{return await this.userManager.getUser()}catch(e){return pc.error("OIDC: getUser - FAILED:",e),null}}async storeUser(e){const t=this.ensureInitialized();await t.storeUser(e)}async getAccessToken(){const e=await this.getUser();if(!e)return pc.info("OIDC: getAccessToken - no user found"),null;if(e.expired)try{const e=await this.signinSilent();return e?.access_token||null}catch(e){return pc.error("OIDC: getAccessToken - silent renew failed:",e),null}return this.isTokenFresh(e)||this.signinSilent().catch(e=>{pc.error("OIDC: getAccessToken - background refresh failed:",e)}),e.access_token}getUserData(){if("undefined"==typeof window)return null;try{const e=cc.getOidcSettings(),t=`oidc.user:${e.authority}:${e.client_id}`,r=localStorage.getItem(t);if(!r)return null;const s=JSON.parse(r),n=s?.profile;return n?.sub?(pc.info("OIDC: USER:",{profile:n}),{id:n.sub,email:n.email||"",first_name:n.given_name,last_name:n.family_name}):null}catch(e){return pc.error("OIDC: getUserData - FAILED:",e),null}}async isAuthenticated(){const e=await this.getUser();return null!==e&&!e.expired}async signinRedirect(e){const t=this.ensureInitialized();await t.signinRedirect({state:e?{data:e}:void 0,prompt:"login"})}async signinCallback(){const e=this.ensureInitialized(),t=await e.signinCallback();if(!t)throw pc.error("OIDC: signinCallback - FAILED: no user returned"),new Error("Signin callback failed: no user returned");return t}async signinSilent(e){return this.ensureInitialized(),"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request("oidc-token-refresh",async()=>{const t=await this.getUser();return t&&this.isTokenFresh(t,e)?t:this.doSigninSilent()}):(pc.warn("OIDC: signinSilent - navigator.locks not available, proceeding without lock"),this.doSigninSilent())}isTokenFresh(e,t){if(!e.expires_at)return!1;const r=t??cc.getAccessTokenFreshnessThresholdInSeconds(),s=Math.floor(Date.now()/1e3);return e.expires_at-s>r}async doSigninSilent(){const e=this.ensureInitialized();try{return await e.signinSilent()}catch(e){throw pc.error("OIDC: doSigninSilent - FAILED:",e),e}}proactiveRefreshWithRetry(e=1){if("undefined"!=typeof document&&"hidden"===document.visibilityState){pc.info("OIDC: tab is hidden, deferring proactive refresh until visible");const t=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",t),this.proactiveRefreshWithRetry(e))};return void document.addEventListener("visibilitychange",t)}this.signinSilent(cc.getAccessTokenExpiringNotificationTimeInSeconds()).then(()=>{this.initAccessTokenExpiringTimer()}).catch(t=>{if(pc.error(`OIDC: proactive refresh failed (attempt ${e}/2):`,t),e<2){const t=setTimeout(()=>{this.retryTimers.delete(t),this.proactiveRefreshWithRetry(e+1)},3e3);this.retryTimers.add(t)}else pc.error("OIDC: proactive refresh exhausted all retries")})}async removeUser(){const e=this.ensureInitialized();this.accessTokenExpiringTimer?.cancel(),this.retryTimers.forEach(clearTimeout),this.retryTimers.clear(),await e.removeUser()}onUserLoaded(e){this.ensureInitialized().events.addUserLoaded(e)}offUserLoaded(e){this.ensureInitialized().events.removeUserLoaded(e)}onUserUnloaded(e){this.ensureInitialized().events.addUserUnloaded(e)}offUserUnloaded(e){this.ensureInitialized().events.removeUserUnloaded(e)}onSilentRenewError(e){this.ensureInitialized().events.addSilentRenewError(e)}offSilentRenewError(e){this.ensureInitialized().events.removeSilentRenewError(e)}onAccessTokenExpiring(e){this.ensureInitialized().events.addAccessTokenExpiring(e)}offAccessTokenExpiring(e){this.ensureInitialized().events.removeAccessTokenExpiring(e)}onAccessTokenExpired(e){this.ensureInitialized().events.addAccessTokenExpired(e)}offAccessTokenExpired(e){this.ensureInitialized().events.removeAccessTokenExpired(e)}getLogoutUrl(e,t){const r=new URL(function(e){return`${cc.getAuthOrigin()}${e.logoutPath}`}(e));return t&&r.searchParams.set("redirect_to",t),r.toString()}getWindowOriginParam(){const e=new URL(window.location.href).searchParams.get("origin");if(!e)throw new Error("iframe origin param is required");return e}async getTopUrl(){return(await uc({type:Jo})).topUrl}async isOAuthFlowPending(){try{return(await uc({type:Yo})).isPending}catch(e){return pc.warn("OIDC: isOAuthFlowPending() - failed to check, assuming not pending:",e),!1}}async triggerLoginFlowViaParent({loginPath:e,windowPath:t}){pc.info("OIDC: triggerLoginFlowViaParent() - starting");const r=await this.getTopUrl(),s=new URL(r).origin,n=`${s}${t}`,i=new URL(`${window.location.origin}${e}`);i.searchParams.set(Xo,s),i.searchParams.set("oauth2_top_wp_url",n),pc.info("OIDC: triggerLoginFlowViaParent() - redirecting parent to:",i.toString()),await uc({type:Bo,payload:{url:i.toString()}})}async handleLoginFlowComplete(e,t){if(!t)throw new Error("oauthUserState is required");const r=this.getWindowOriginParam(),s=t.state,n=s?.data?.[Xo];if(r!==n)throw pc.error("OIDC: handleLoginFlowComplete - origin mismatch:",r,"!==",n),new Error("Invalid origin in OAuth state");try{const e=new Oo(t);await this.storeUser(e),this.initAccessTokenExpiringTimer(),window.dispatchEvent(new CustomEvent("oidc-auth-completed"))}catch(t){pc.error("OIDC: handleLoginFlowComplete - FAILED to store user:",t),await this.triggerLoginFlowViaParent(e)}}async triggerLogoutViaParent(e,t=!0){const r=await this.getTopUrl(),s=new URL(r).origin,n=t?`${s}${e.windowPath}`:s;await this.removeUser();const i=this.getLogoutUrl(e,n);await uc({type:Bo,payload:{url:i}})}async cleanOAuthParamsFromUrl(){try{const e=await this.getTopUrl(),t=new URL(e);t.searchParams.delete("oauth_code"),t.searchParams.delete("oauth_state"),t.searchParams.delete("start-oauth"),t.searchParams.delete(ec),t.searchParams.delete(tc),await uc({type:Qo,payload:{url:t.toString()}})}catch(e){pc.warn("Failed to clean OAuth params from URL:",e)}}setupLoginFlowMessageListener(e){let t=!1;const r=r=>{if(r.data?.type!==Wo)return;if(r.origin!==ac())return void pc.error("OIDC: origin mismatch - expected:",ac(),"received:",r.origin);if(t)return void pc.debug("OIDC: LOGIN_FLOW_COMPLETE already processed, ignoring duplicate");const s=r.data.payload;s?.oauthState?(t=!0,this.handleLoginFlowComplete(e,s.oauthState).catch(e=>{pc.error("OIDC: Failed to handle login flow complete:",e),t=!1})):pc.warn("OIDC: LOGIN_FLOW_COMPLETE but no oauthState in payload")};return window.addEventListener("message",r),()=>{window.removeEventListener("message",r)}}async getTokenExpirationInfo(){const e=await this.getUser();if(!e||!e.expires_at)return{expiresAt:null,expiresInSeconds:null,isExpired:!0};const t=new Date(1e3*e.expires_at),r=Date.now(),s=Math.floor((1e3*e.expires_at-r)/1e3);return{expiresAt:t,expiresInSeconds:s,isExpired:s<=0}}async forceTokenRefresh(){return pc.info("OIDC: forceTokenRefresh() - manually triggering token refresh"),this.signinSilent()}}const fc=mc.getInstance();"undefined"!=typeof window&&(window.oidcAuthClient=fc);const gc=ic("oidc-auth:oidc-auth-redirect");function _c(e,t){e.postMessage({status:"success",payload:t})}function yc(e,t){e.postMessage({status:"error",payload:t})}function vc({targets:e,onSuccess:t,attempt:r=1}){const s=new URLSearchParams(window.location.search);if(!s.get(ec))return void gc.warn("OIDC: No login_success param found, skipping");const n=s.get(tc);if(n){if(!e.window?.contentWindow||!e.windowURL)return gc.warn("Cannot forward OIDC state: iframe not available"),void(r<5?setTimeout(()=>{vc({targets:e,onSuccess:t,attempt:r+1})},500):gc.error("OIDC: Failed to forward login flow after",5,"attempts - iframe never became available"));try{const r=JSON.parse(n),s=r.state?.data?.[Xo];if(s&&s!==window.location.origin)return void gc.error("Origin mismatch in OIDC state:",s,"vs",window.location.origin);!function(e,t){const r=t.window?.contentWindow,s=t.windowURL?.origin;r&&s?r.postMessage({type:Wo,payload:e},s):gc.warn("Cannot send OIDC state: window or origin not available")}({oauthState:r},e);const i=new URL(window.location.href);i.searchParams.delete(ec),i.searchParams.delete(tc),history.replaceState({},"",i.toString()),t?.()}catch(e){gc.error("Failed to parse or forward OIDC state:",e)}}else gc.warn("OIDC login complete but no state found in URL")}const wc="angie_return_url",bc=$a("referrer-redirect");function kc(e){try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}function Sc(e,t){if(!kc(e))return bc.warn("Invalid redirect URL rejected:",e),!1;try{const r={url:e};return t&&(r.prompt=t),localStorage.setItem(wc,JSON.stringify(r)),!0}catch(e){return bc.warn("localStorage not available"),!1}}function $c(){try{const e=localStorage.getItem(wc);if(!e)return null;let t;try{t=JSON.parse(e)}catch{return bc.warn("Stored redirect data is not valid JSON, returning null"),null}return t.url&&"string"==typeof t.url?kc(t.url)?t:(bc.warn("Stored redirect URL is invalid, returning null:",t.url),null):(bc.warn("Stored redirect data missing url field, returning null"),null)}catch(e){return bc.warn("localStorage not available"),null}}function Ec(){try{localStorage.removeItem(wc)}catch(e){bc.warn("localStorage not available")}}function Tc(e,t){return t?`${e}#angie-prompt=${encodeURIComponent(t)}`:e}const xc=$a("oauth");function Pc(){const e=$c();if(e)return Ec(),void(window.location.href=Tc(e.url,e.prompt));try{localStorage.setItem("angie_sidebar_state","open")}catch(e){xc.warn("localStorage not available")}setTimeout(()=>{window.toggleAngieSidebar(!0)},500)}const Ic=(e,t)=>{const r=document.getElementById(La.containerId);r&&r.setAttribute("aria-hidden",t?"false":"true"),t?e.removeAttribute("tabindex"):e.setAttribute("tabindex","-1")},Rc=(e,t)=>{e.postMessage({status:"success",payload:t})},Oc=$a("sdk");var Cc;(Cc||(Cc={})).POST_MESSAGE="postMessage";const Ac=$a("sidebar");let Nc=!1;const jc="open";const zc=$a("iframe"),Mc=e=>{if(e.includes("://")||e.startsWith("//"))return!1;try{const t="https://test.com";return new URL(e,t).origin===t}catch{return!1}},qc=async()=>{if(La.iframe?.contentWindow&&La.iframeUrlObject)try{zc.log("Disabling navigation prevention in Angie iframe"),La.iframe.contentWindow.postMessage({type:Aa.ANGIE_DISABLE_NAVIGATION_PREVENTION},La.iframeUrlObject.origin),await new Promise(e=>setTimeout(e,100))}catch(e){throw zc.error("Failed to disable navigation prevention:",e),e}else zc.warn("Cannot disable navigation prevention: iframe or origin not available")},Uc=async e=>{if(window.screen.availWidth<=768)return void zc.log("Mobile detected, skipping iframe injection");let t=document.getElementById(La.containerId);if(!t){const e=performance.now();if(zc.log("⏱️ Waiting for sidebar container..."),await new Promise(e=>{let r=0;const s=setInterval(()=>{t=document.getElementById(La.containerId),r++,(t||r>20)&&(clearInterval(s),t&&e())},100);setTimeout(()=>{if(clearInterval(s),t)return void e();const r=new MutationObserver(()=>{t=document.getElementById(La.containerId),t&&(r.disconnect(),e())});r.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>{r.disconnect(),e()},8e3)},2e3)}),zc.log(`⏱️ Sidebar container detection took: ${(performance.now()-e).toFixed(2)}ms`),!t)return void zc.error("Sidebar container not found")}const{iframe:r,iframeUrlObject:s}=await(async e=>{const t=e.origin,r=new URL(e.path,t),s=r.pathname.slice(1).replace(/\//,"--")+"-"+Math.random().toString(36).substring(7);return new Promise(n=>{const i=new URL(t);i.pathname=r.pathname;const a=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";if(i.searchParams.append("colorScheme",e.uiTheme||a||"light"),i.searchParams.append("sdkVersion",e.sdkVersion),i.searchParams.append("instanceId",s),i.searchParams.append("origin",window.location.origin),e.isRTL&&i.searchParams.append("isRTL",e.isRTL?"true":"false"),"localhost"===window.location.hostname&&window.location.search.includes("debug_error")){const e=new URLSearchParams(window.location.search).get("debug_error");e&&i.searchParams.append("debug_error",e)}r.searchParams.forEach((e,t)=>{i.searchParams.set(t,e)}),i.searchParams.set("ver",(new Date).getTime().toString());const o=e.parent||document,c=o.createElement("iframe"),d={"background-color":"transparent","color-scheme":"normal",...e.css};window.addEventListener("message",async e=>{if(e.origin===i.origin)switch(e.data.type){case ja.ANGIE_READY:n({iframe:c,iframeUrlObject:i});break;case ja.ANGIE_LOADED:c.contentWindow?.postMessage({type:ja.HOST_READY,instanceId:s},i.origin)}}),c.setAttribute("src",i.href),c.id="angie-iframe",c.setAttribute("frameborder","0"),c.setAttribute("scrolling","no"),c.setAttribute("style",Object.entries(d).map(([e,t])=>`${e}: ${t}`).join("; ")),c.setAttribute("allow","clipboard-write; clipboard-read"),e.insertCallback?e.insertCallback(c):o.body.appendChild(c)})})({origin:e.origin||"https://angie.elementor.com",path:e.path&&Mc(e.path)?e.path:"angie/wp-admin",insertCallback:e=>{zc.log("Injecting Angie iframe into sidebar container"),e.setAttribute("title","Angie AI Assistant"),e.setAttribute("role","application"),e.setAttribute("aria-label","Angie AI Assistant Interface");const r=document.getElementById("angie-sidebar-loading");r&&(r.textContent=""),t?.appendChild(e),Ic(e,!0),e.addEventListener("load",()=>{e.focus()})},css:{width:"100%",height:"100%",border:"none",outline:"none"},uiTheme:e.uiTheme,isRTL:e.isRTL,sdkVersion:"1.4.5"});La.iframe=r,La.iframeUrlObject=s,window.addEventListener("message",e=>{if(e.origin===La.iframeUrlObject?.origin)switch(e.data.type){case Na.SET:window.localStorage.setItem(e.data.key,e.data.value);break;case Na.GET:{const t=e.ports[0],r=window.localStorage.getItem(e.data.key);t.postMessage({value:r});break}}}),(e=>{window.addEventListener("message",async t=>{const r=t.origin===window.location.origin,s=t.origin===e.iframeUrlObject?.origin;if(r||s)switch(t?.data?.type){case Aa.SDK_ANGIE_ALL_SERVERS_REGISTERED:break;case Aa.SDK_ANGIE_READY_PING:{const e=t.ports[0];Oc.log("Angie is ready",t),Rc(e,{message:"Angie is ready"});break}case Aa.SDK_REQUEST_CLIENT_CREATION:{const r=t.data.payload;try{const s=t.ports[0],n=new MessageChannel;n.port1.onmessage=e=>{s.postMessage({success:!0,data:e.data})};const i={type:Aa.SDK_REQUEST_CLIENT_CREATION,payload:{success:!0,...r,clientId:`dynamic-client-${r.serverName}-${r.serverVersion}-${Date.now()}`,requestId:t.data.payload.requestId},timestamp:Date.now()};if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage(i,e.iframeUrlObject?.origin||"",[n.port2])}catch(e){Oc.error(`Failed to create client for SDK server "${r.serverName}":`,e)}break}case Aa.SDK_TRIGGER_ANGIE:Oc.log("SDK Trigger Angie received",t.data);try{const{requestId:r,prompt:s,context:n}=t.data.payload;if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage({type:Aa.SDK_TRIGGER_ANGIE,payload:{requestId:r,prompt:s,context:n}},e.iframeUrlObject?.origin||""),window.postMessage({type:Aa.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!0,requestId:r,response:"Angie triggered successfully"}},window.location.origin)}catch(e){Oc.error("Failed to trigger Angie:",e),window.postMessage({type:Aa.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!1,requestId:t.data.payload?.requestId,error:e instanceof Error?e.message:"Unknown error"}},window.location.origin)}}})})(La),function({trustedOrigin:e,onOAuthParamsCleared:t}){window.addEventListener("message",r=>{if(r.origin!==e)return;const s=r.ports?.[0];switch(r.data.type){case Jo:if(!s)return;_c(s,{topUrl:window.location.href});break;case Bo:window.location.href=r.data.payload.url;break;case Qo:{if(!s)return;const e=r.data.payload.url;if(!history?.replaceState)return void yc(s,{message:"URL update not supported in this browser"});try{const r=window.location.href;history.replaceState({},"",e),function(e,t){const r=new URL(e).searchParams,s=new URL(t).searchParams,n=[ec,tc,Xo];return n.some(e=>r.has(e))&&!n.some(e=>s.has(e))}(r,e)&&t?.(),_c(s,{message:"URL updated successfully"})}catch(e){yc(s,{message:"URL update failed: "+(e instanceof Error?e.message:"Unknown error")})}break}case Yo:if(!s)return;_c(s,{isPending:"true"===new URLSearchParams(window.location.search).get(ec)})}})}({trustedOrigin:La.iframeUrlObject?.origin??"",onOAuthParamsCleared:Pc}),(()=>{const e={window:La.iframe,windowURL:La.iframeUrlObject};window.addEventListener("load",()=>{xc.log("OIDC: Window load event fired, forwarding OIDC state if present"),vc({targets:e,onSuccess:Pc})}),vc({targets:e,onSuccess:Pc})})(),new URLSearchParams(window.location.search).has("start-oauth")&&(xc.log("Post-consent flow detected, checking for referrer redirect"),function(){const e=$c();e&&(Ec(),window.location.href=Tc(e.url,e.prompt))}()),window.addEventListener("message",async t=>{if([window.location.origin,e.origin||"https://angie.elementor.com"].includes(t.origin))if(t?.data?.type===Aa.ANGIE_CHAT_TOGGLE)La.open=t.data.open,La.iframe&&Ic(La.iframe,La.open);else if(t?.data?.type===Aa.ANGIE_STUDIO_TOGGLE){const e=t.data.isStudioOpen;if(!La.iframe)return;if(e)document.documentElement.classList.add("angie-studio-active");else{const e=function(){if("undefined"==typeof window)return 370;try{const e=window.localStorage.getItem("angie_sidebar_width");if(e){const t=parseInt(e,10);if(t>=350&&t<=590)return t}}catch(e){Ac.warn("localStorage not available")}return 370}();document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`),document.documentElement.classList.remove("angie-studio-active")}}else if(t?.data?.type===Aa.ANGIE_NAVIGATE_TO_URL){const{url:e="",confirmed:r=!1}=t.data.payload||{};if(!r)return void zc.log("Navigation requires user confirmation");if(!((e,t=[])=>{const r=0===t.length&&"undefined"!=typeof window?[window.location.origin]:t;if(!e.startsWith("http"))return!1;try{const t=new URL(e);return r.includes(t.origin)}catch{return!1}})(e))return void zc.error("Navigation blocked: Invalid or unsafe URL",{url:e});await qc(),window.location.assign(e)}else if(t?.data?.type===Aa.ANGIE_PAGE_RELOAD){const{confirmed:e=!1}=t.data.payload||{};if(!e)return void zc.log("Page reload requires user confirmation");zc.log("Page reload confirmed - disabling navigation prevention and reloading"),await qc(),setTimeout(()=>{window.location.reload()},50)}else t?.data?.type===ja.RESET_HASH&&(window.location.hash="",Rc(t.ports[0],{message:"Hash reset successfully"}))})},Dc=$a("registration-queue");class Lc{queue=[];isProcessing=!1;add(e){const t={id:this.generateId(e),config:e,timestamp:Date.now(),status:"pending"};return this.queue.push(t),Dc.log(`Added server "${e.name}" to queue`),t}getAll(){return[...this.queue]}getPending(){return this.queue.filter(e=>"pending"===e.status)}updateStatus(e,t,r){const s=this.queue.find(t=>t.id===e);s&&(s.status=t,r?s.error=r:"pending"!==t&&"registered"!==t||delete s.error,Dc.log(`Updated server ${e} status to ${t}`))}async processQueue(e){if(this.isProcessing)return void Dc.log("Already processing queue");this.isProcessing=!0;const t=this.getPending();Dc.log(`Processing ${t.length} pending registrations`);try{for(const r of t)try{await e(r),this.updateStatus(r.id,"registered")}catch(e){const t=e instanceof Error?e.message:String(e);this.updateStatus(r.id,"failed",t),Dc.error(`Failed to process registration ${r.id}:`,t)}}finally{this.isProcessing=!1}}clear(){this.queue=[],Dc.log("Cleared all registrations")}resetAllToPending(){if(this.isProcessing)return Dc.log("Cannot reset to pending - processing in progress"),!1;const e=this.queue.filter(e=>"registered"===e.status).length,t=this.queue.filter(e=>"failed"===e.status).length;return this.queue.forEach(e=>{"pending"!==e.status&&(e.status="pending",delete e.error)}),Dc.log(`Reset ${e+t} registrations to pending`),!0}remove(e){const t=this.queue.findIndex(t=>t.id===e);return-1!==t&&(this.queue.splice(t,1),Dc.log(`Removed registration ${e}`),!0)}generateId(e){return`reg_${e.name}_${e.version}_${Date.now()}`}}const Zc={origin:"https://angie.elementor.com",uiTheme:"light",isRTL:!1,containerId:Da,skipDefaultCss:!1,path:"angie/wp-admin"};class Fc{angieDetector;clientManager;logger;registrationQueue;isInitialized=!1;instanceId;constructor(){this.instanceId=Math.random().toString(36).substring(2,8),this.logger=$a({instanceId:this.instanceId}),this.logger.log("Constructor called - initializing SDK"),this.angieDetector=new Ma,this.registrationQueue=new Lc,this.clientManager=new Ua,this.logger.log("Setting up event handlers"),this.setupAngieReadyHandler(),this.setupServerInitHandler(),this.setupReRegistrationHandler(),this.logger.log("SDK initialization complete")}async loadSidebar(e){const{widgetConfig:t,...r}=e||{},s={...Zc,...r};La.containerId=s.containerId,function(e){var t;e?.skipDefaultCss||function(){if("undefined"==typeof document||Nc)return;const e="angie-sidebar-styles";if(document.getElementById(e))return void(Nc=!0);const t=document.createElement("style");t.id=e,t.textContent="/* Angie Sidebar - CSS Variables */\n:root {\n --angie-sidebar-z-index: 1200; /* below MUI popups, elementor popups and media library modal */\n --angie-sidebar-width: 330px;\n --angie-sidebar-transition: margin 0.3s ease-in-out, transform 0.3s ease-in-out;\n /* Direction-aware transform values for sidebar positioning */\n --angie-sidebar-hide-transform: translateX(-100%); /* LTR: hide to the left */\n --angie-sidebar-show-transform: translateX(0);\n}\n\n/* RTL-specific transform values */\n[dir=\"rtl\"] {\n --angie-sidebar-hide-transform: translateX(100%); /* RTL: hide to the right */\n}\n\n/* Respect user's motion preferences */\n@media (prefers-reduced-motion: reduce) {\n :root {\n --angie-sidebar-transition: none;\n }\n}\n\n/* Apply transitions only when user is actively toggling */\nbody.angie-sidebar-transitioning {\n transition: var(--angie-sidebar-transition) !important;\n}\n\nbody.angie-sidebar-transitioning #angie-sidebar-container {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n/* Layout (default) - Push content */\n@media (min-width: 768px) {\n body.angie-sidebar-active {\n padding-inline-start: var(--angie-sidebar-width) !important;\n }\n\n #angie-sidebar-container {\n position: fixed;\n top: 0;\n inset-inline-start: 0;\n width: var(--angie-sidebar-width);\n height: 100vh;\n z-index: var(--angie-sidebar-z-index) !important; /* below elementor popups and media library modal */\n background: #FCFCFC;\n transform: var(--angie-sidebar-hide-transform);\n outline: none;\n overflow: hidden;\n /* No default transition - only when transitioning */\n }\n\n /* Resize handle */\n #angie-sidebar-container::after {\n content: '';\n position: absolute;\n top: 0;\n inset-inline-end: 0;\n width: 4px;\n height: 100%;\n cursor: ew-resize;\n background: transparent;\n z-index: 1000001;\n }\n\n /* Pink border during resize */\n #angie-sidebar-container.angie-resizing {\n border-inline-end-color: #ff69b4 !important;\n border-inline-end-width: 2px !important;\n }\n\n /* Disable iframe pointer events during resize */\n #angie-sidebar-container.angie-resizing iframe#angie-iframe {\n pointer-events: none !important;\n }\n}\n\n/* Active states */\nbody.angie-sidebar-active #angie-sidebar-container {\n transform: var(--angie-sidebar-show-transform);\n}\n\n/* Studio mode - sidebar takes full width */\n@media (min-width: 768px) {\n html.angie-studio-active body.angie-sidebar-active #angie-sidebar-container {\n width: 100%;\n }\n}\n\n/* High contrast mode support */\n@media (prefers-contrast: high) {\n #angie-sidebar-container {\n border-color: #000;\n box-shadow: none;\n }\n}\n\n/* Screen reader only class */\n.angie-sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n/* Plugin conflict resolution */\nbody.angie-sidebar-active {\n /* Reset common conflicting styles */\n box-sizing: border-box !important;\n position: relative !important;\n}\n\n#angie-sidebar-toggle {\n z-index: 99999 !important;\n}\n";const r=document.head||document.getElementsByTagName("head")[0];r.insertBefore(t,r.firstChild),Nc=!0}(),"undefined"!=typeof window&&(window.toggleAngieSidebar=(t=e?.onToggle,function(e,r){const s=document.body,n=document.getElementById(La.containerId);if(!n)return void Ac.warn("Required elements not found!");const i=s.classList.contains("angie-sidebar-active"),a=void 0!==e?e:!i;r||(s.classList.add("angie-sidebar-transitioning"),setTimeout(function(){s.classList.remove("angie-sidebar-transitioning")},300)),a?s.classList.add("angie-sidebar-active"):s.classList.remove("angie-sidebar-active"),a&&setTimeout(function(){Pa({type:"focusInput"})},r?0:300),t&&t(a,n,r),function(e){try{localStorage.setItem("angie_sidebar_state",e)}catch(e){Ac.warn("localStorage not available")}}(a?jc:"closed");const o=new CustomEvent("angieSidebarToggle",{detail:{isOpen:a,sidebar:n,skipTransition:r}});document.dispatchEvent(o),Pa({type:Aa.ANGIE_SIDEBAR_TOGGLED,payload:{state:a?"opened":"closed"}})}),window.addEventListener("message",function(e){if(e.data&&"toggleAngieSidebar"===e.data.type){const{force:t,skipTransition:r}=e.data.payload||{};window.toggleAngieSidebar&&window.toggleAngieSidebar(t,r)}}))}({skipDefaultCss:s.skipDefaultCss}),await Uc(s),t&&Pa({type:"sdk-widget-config",payload:t}),this.setupPromptHashDetection()}setupReRegistrationHandler(){window.addEventListener("message",e=>{if(e.data?.type===Aa.SDK_ANGIE_REFRESH_PING)if(this.logger.log("Angie refresh ping received"),this.registrationQueue.resetAllToPending()){const e=this.registrationQueue.getPending().length;this.logger.log(`Successfully reset ${e} registrations, processing queue`),this.handleAngieReady()}else this.logger.log("Skipping queue reset - processing already in progress")})}setupAngieReadyHandler(){this.angieDetector.waitForReady().then(e=>{e.isReady?this.handleAngieReady():this.logger.warn("Angie not detected - servers will remain queued")}).catch(e=>{this.logger.error("Error waiting for Angie:",e)})}async handleAngieReady(){this.logger.log("Angie is ready, processing queued registrations");try{await this.registrationQueue.processQueue(async e=>{this.logger.log(`processQueue callback called for "${e.config.name}"`),await this.processRegistration(e)}),this.isInitialized=!0,this.logger.log("Initialization complete")}catch(e){this.logger.error("Error processing registration queue:",e)}}async processRegistration(e){this.logger.log(`Processing registration for server "${e.config.name}" (ID: ${e.id})`);try{this.logger.log(`Calling clientManager.requestClientCreation for "${e.config.name}"`);const t={...e,instanceId:this.instanceId};await this.clientManager.requestClientCreation(t),this.logger.log(`Successfully registered server "${e.config.name}"`)}catch(t){throw this.logger.error(`Failed to register server "${e.config.name}":`,t),t}}registerLocalServer(e){return e.type=Ca.LOCAL,e.transport=Ra.POST_MESSAGE,this.registerServer(e)}registerRemoteServer(e){return e.type=Ca.REMOTE,this.registerServer(e)}isLocalServerConfig(e){return e.type===Ca.LOCAL||!e.type&&"server"in e}isRemoteServerConfig(e){return e.type===Ca.REMOTE&&"url"in e}async registerServer(e){if(!e.type)return this.logger.warn("For a local server, please use registerLocalServer instead of registerServer"),void this.registerLocalServer(e);if(this.logger.log(`registerServer called for "${e.name}"`),!e.name)throw new Error("Server name is required");if(!e.description)throw new Error("Server description is required");if(this.isLocalServerConfig(e)&&!e.server)throw new Error("Server instance is required for local servers");this.logger.log(`Registering server "${e.name}"`);const t=this.registrationQueue.add(e);if(this.logger.log(`Added registration to queue: ${t.id}`),this.angieDetector.isReady())try{await this.processRegistration(t),this.registrationQueue.updateStatus(t.id,"registered"),this.logger.log(`Server "${e.name}" registered successfully`)}catch(e){const r=e instanceof Error?e.message:String(e);throw this.registrationQueue.updateStatus(t.id,"failed",r),e}else this.logger.log(`Server "${e.name}" queued until Angie is ready`)}getRegistrations(){return this.registrationQueue.getAll()}getPendingRegistrations(){return this.registrationQueue.getPending()}isAngieReady(){return this.angieDetector.isReady()}isReady(){return this.isInitialized}async waitForReady(){if(!(await this.angieDetector.waitForReady()).isReady)throw new Error("Angie is not available");for(;!this.isInitialized;)await new Promise(e=>setTimeout(e,100))}async triggerAngie(e){if(!this.isAngieReady())throw new Error("Angie is not ready. Please wait for Angie to be available before triggering.");const t=this.generateRequestId(),r=e.options?.timeout||3e4;return new Promise((s,n)=>{const i=setTimeout(()=>{n(new Error("Angie trigger request timed out"))},r),a=e=>{e.data?.type===Aa.SDK_TRIGGER_ANGIE_RESPONSE&&e.data?.payload?.requestId===t&&(clearTimeout(i),window.removeEventListener("message",a),s(e.data.payload))};window.addEventListener("message",a);const o={type:Aa.SDK_TRIGGER_ANGIE,payload:{requestId:t,prompt:e.prompt,options:e.options,context:{pageUrl:window.location.href,pageTitle:document.title,...e.context}},timestamp:Date.now()};this.logger.log(`Triggering Angie with prompt (Request ID: ${t})`),window.postMessage(o,window.location.origin)})}destroy(){this.registrationQueue.clear(),this.logger.log("SDK destroyed")}setupServerInitHandler(){window.addEventListener("message",e=>{e.data?.type===Aa.SDK_REQUEST_INIT_SERVER&&(this.logger.log("Server init request received"),this.handleServerInitRequest(e))})}handleServerInitRequest(e){const{clientId:t,serverId:r,instanceId:s}=e.data.payload||{};if(t&&r)if(this.logger.log(`Server init request received - Request instanceId: ${s}, This instanceId: ${this.instanceId}`),s&&s!==this.instanceId)this.logger.log(`Ignoring server init request for different instance. Request instanceId: ${s}, this instanceId: ${this.instanceId}`);else{this.logger.log(`Handling server init request for clientId: ${t}, serverId: ${r}`);try{const t=this.registrationQueue.getAll().find(e=>e.id===r);if(!t)return void this.logger.error(`No registration found for serverId: ${r}`);if("type"in t.config&&"remote"===t.config.type)return void this.logger.log("Remote server registration detected; skipping local connect");const s=e.ports[0];if(!s)return void this.logger.error("No port provided in server init request");const n=t.config.server;this.migrateInstructionsCompat(n);const i=new qa(s);n.connect(i),this.logger.log(`Server "${t.config.name}" initialized successfully`)}catch(e){this.logger.error(`Error initializing server for clientId ${t}:`,e)}}else this.logger.error("Invalid server init request - missing clientId or serverId")}migrateInstructionsCompat(e){try{const t="server"in e&&e.server?e.server:e,r=t._serverInfo,s=t._instructions;r?.instructions&&!s&&(t._instructions=r.instructions,this.logger.log("Migrated instructions from serverInfo to serverOptions (backward compat)"))}catch{}}generateRequestId(){return`${this.instanceId}-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}async handlePromptHash(){const e=window.location.hash;if(e.startsWith("#angie-prompt="))try{const t=e.replace("#angie-prompt=",""),r=decodeURIComponent(t);if(!r)return void this.logger.warn("Empty prompt detected in hash");this.logger.log("Detected prompt in hash:",r),await this.waitForReady();const s=await this.triggerAngie({prompt:r,context:{source:"hash-parameter",pageUrl:window.location.href,timestamp:(new Date).toISOString()}});this.logger.log("Triggered successfully from hash:",s),window.location.hash=""}catch(e){this.logger.error("Failed to trigger from hash:",e)}}setupPromptHashDetection(){this.handlePromptHash(),window.addEventListener("hashchange",()=>this.handlePromptHash())}}var Hc;let Vc;$a("navigation"),function(e){e.Inline="inline",e.EndOfTurn="end-of-turn"}(Hc||(Hc={}));const Kc=()=>globalThis.__ELEMENTOR_MCP_DISABLED__?{}:(Vc||(Vc=new Fc),Vc);var Gc,Wc,Jc;(Jc=Gc||(Gc={})).assertEqual=e=>{},Jc.assertIs=function(e){},Jc.assertNever=function(e){throw new Error},Jc.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},Jc.getValidEnumValues=e=>{const t=Jc.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(const s of t)r[s]=e[s];return Jc.objectValues(r)},Jc.objectValues=e=>Jc.objectKeys(e).map(function(t){return e[t]}),Jc.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},Jc.find=(e,t)=>{for(const r of e)if(t(r))return r},Jc.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,Jc.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},Jc.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,function(e){e.mergeShapes=(e,t)=>({...e,...t})}(Wc||(Wc={}));const Bc=Gc.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Qc=e=>{switch(typeof e){case"undefined":return Bc.undefined;case"string":return Bc.string;case"number":return Number.isNaN(e)?Bc.nan:Bc.number;case"boolean":return Bc.boolean;case"function":return Bc.function;case"bigint":return Bc.bigint;case"symbol":return Bc.symbol;case"object":return Array.isArray(e)?Bc.array:null===e?Bc.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?Bc.promise:"undefined"!=typeof Map&&e instanceof Map?Bc.map:"undefined"!=typeof Set&&e instanceof Set?Bc.set:"undefined"!=typeof Date&&e instanceof Date?Bc.date:Bc.object;default:return Bc.unknown}},Yc=Gc.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Xc extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,s=0;for(;s<n.path.length;){const r=n.path[s];s===n.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(n))):e[r]=e[r]||{_errors:[]},e=e[r],s++}}};return s(this),r}static assert(e){if(!(e instanceof Xc))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Gc.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const s of this.issues)if(s.path.length>0){const r=s.path[0];t[r]=t[r]||[],t[r].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Xc.create=e=>new Xc(e);var ed=(e,t)=>{let r;switch(e.code){case Yc.invalid_type:r=e.received===Bc.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Yc.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Gc.jsonStringifyReplacer)}`;break;case Yc.unrecognized_keys:r=`Unrecognized key(s) in object: ${Gc.joinValues(e.keys,", ")}`;break;case Yc.invalid_union:r="Invalid input";break;case Yc.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Gc.joinValues(e.options)}`;break;case Yc.invalid_enum_value:r=`Invalid enum value. Expected ${Gc.joinValues(e.options)}, received '${e.received}'`;break;case Yc.invalid_arguments:r="Invalid function arguments";break;case Yc.invalid_return_type:r="Invalid function return type";break;case Yc.invalid_date:r="Invalid date";break;case Yc.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Gc.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Yc.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case Yc.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case Yc.custom:r="Invalid input";break;case Yc.invalid_intersection_types:r="Intersection results could not be merged";break;case Yc.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Yc.not_finite:r="Number must be finite";break;default:r=t.defaultError,Gc.assertNever(e)}return{message:r}};let td=ed;var rd;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(rd||(rd={}));function sd(e,t){const r=td,s=(e=>{const{data:t,path:r,errorMaps:s,issueData:n}=e,i=[...r,...n.path||[]],a={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const c=s.filter(e=>!!e).slice().reverse();for(const e of c)o=e(a,{data:t,defaultError:o}).message;return{...n,path:i,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===ed?void 0:ed].filter(e=>!!e)});e.common.issues.push(s)}class nd{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if("aborted"===s.status)return id;"dirty"===s.status&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,s=await e.value;r.push({key:t,value:s})}return nd.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return id;if("aborted"===n.status)return id;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(r[t.value]=n.value)}return{status:e.value,value:r}}}const id=Object.freeze({status:"aborted"}),ad=e=>({status:"dirty",value:e}),od=e=>({status:"valid",value:e}),cd=e=>"aborted"===e.status,dd=e=>"dirty"===e.status,ud=e=>"valid"===e.status,ld=e=>"undefined"!=typeof Promise&&e instanceof Promise;class hd{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const pd=(e,t)=>{if(ud(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Xc(e.common.issues);return this._error=t,this._error}}};function md(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:n}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:n}:{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??s??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??r??n.defaultError}},description:n}}class fd{get description(){return this._def.description}_getType(e){return Qc(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Qc(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new nd,ctx:{common:e.parent.common,data:e.data,parsedType:Qc(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ld(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Qc(e)},s=this._parseSync({data:e,path:r.path,parent:r});return pd(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Qc(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return ud(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>ud(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Qc(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(ld(s)?s:Promise.resolve(s));return pd(r,n)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const n=e(t),i=()=>s.addIssue({code:Yc.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(i(),!1)):!!n||(i(),!1)})}refinement(e,t){return this._refinement((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1))}_refinement(e){return new pu({schema:this,typeName:ku.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return mu.create(this,this._def)}nullable(){return fu.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yd.create(this)}promise(){return hu.create(this,this._def)}or(e){return tu.create([this,e],this._def)}and(e){return su.create(this,e,this._def)}transform(e){return new pu({...md(this._def),schema:this,typeName:ku.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new gu({...md(this._def),innerType:this,defaultValue:t,typeName:ku.ZodDefault})}brand(){return new vu({typeName:ku.ZodBranded,type:this,...md(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new _u({...md(this._def),innerType:this,catchValue:t,typeName:ku.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return wu.create(this,e)}readonly(){return bu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const gd=/^c[^\s-]{8,}$/i,_d=/^[0-9a-z]+$/,yd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,vd=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,wd=/^[a-z0-9_-]{21}$/i,bd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,kd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Sd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let $d;const Ed=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Td=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,xd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Pd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Id=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Rd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Od="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Cd=new RegExp(`^${Od}$`);function Ad(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function Nd(e){return new RegExp(`^${Ad(e)}$`)}function jd(e){let t=`${Od}T${Ad(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function zd(e,t){return!("v4"!==t&&t||!Ed.test(e))||!("v6"!==t&&t||!xd.test(e))}function Md(e,t){if(!bd.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return!("object"!=typeof n||null===n||"typ"in n&&"JWT"!==n?.typ||!n.alg||t&&n.alg!==t)}catch{return!1}}function qd(e,t){return!("v4"!==t&&t||!Td.test(e))||!("v6"!==t&&t||!Pd.test(e))}class Ud extends fd{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Bc.string){const t=this._getOrReturnCtx(e);return sd(t,{code:Yc.invalid_type,expected:Bc.string,received:t.parsedType}),id}const t=new nd;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),sd(r,{code:Yc.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(r=this._getOrReturnCtx(e,r),sd(r,{code:Yc.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("length"===s.kind){const n=e.data.length>s.value,i=e.data.length<s.value;(n||i)&&(r=this._getOrReturnCtx(e,r),n?sd(r,{code:Yc.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&sd(r,{code:Yc.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)Sd.test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"email",code:Yc.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)$d||($d=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),$d.test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"emoji",code:Yc.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)vd.test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"uuid",code:Yc.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)wd.test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"nanoid",code:Yc.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)gd.test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"cuid",code:Yc.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)_d.test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"cuid2",code:Yc.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)yd.test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"ulid",code:Yc.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),sd(r,{validation:"url",code:Yc.invalid_string,message:s.message}),t.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"regex",code:Yc.invalid_string,message:s.message}),t.dirty())):"trim"===s.kind?e.data=e.data.trim():"includes"===s.kind?e.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(e,r),sd(r,{code:Yc.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),t.dirty()):"toLowerCase"===s.kind?e.data=e.data.toLowerCase():"toUpperCase"===s.kind?e.data=e.data.toUpperCase():"startsWith"===s.kind?e.data.startsWith(s.value)||(r=this._getOrReturnCtx(e,r),sd(r,{code:Yc.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(r=this._getOrReturnCtx(e,r),sd(r,{code:Yc.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty()):"datetime"===s.kind?jd(s).test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{code:Yc.invalid_string,validation:"datetime",message:s.message}),t.dirty()):"date"===s.kind?Cd.test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{code:Yc.invalid_string,validation:"date",message:s.message}),t.dirty()):"time"===s.kind?Nd(s).test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{code:Yc.invalid_string,validation:"time",message:s.message}),t.dirty()):"duration"===s.kind?kd.test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"duration",code:Yc.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?zd(e.data,s.version)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"ip",code:Yc.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?Md(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"jwt",code:Yc.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?qd(e.data,s.version)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"cidr",code:Yc.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?Id.test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"base64",code:Yc.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?Rd.test(e.data)||(r=this._getOrReturnCtx(e,r),sd(r,{validation:"base64url",code:Yc.invalid_string,message:s.message}),t.dirty()):Gc.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:Yc.invalid_string,...rd.errToObj(r)})}_addCheck(e){return new Ud({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...rd.errToObj(e)})}url(e){return this._addCheck({kind:"url",...rd.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...rd.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...rd.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...rd.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...rd.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...rd.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...rd.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...rd.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...rd.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...rd.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...rd.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...rd.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...rd.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...rd.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...rd.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...rd.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...rd.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...rd.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...rd.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...rd.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...rd.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...rd.errToObj(t)})}nonempty(e){return this.min(1,rd.errToObj(e))}trim(){return new Ud({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ud({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ud({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function Dd(e,t){const r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=r>s?r:s;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}Ud.create=e=>new Ud({checks:[],typeName:ku.ZodString,coerce:e?.coerce??!1,...md(e)});class Ld extends fd{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Bc.number){const t=this._getOrReturnCtx(e);return sd(t,{code:Yc.invalid_type,expected:Bc.number,received:t.parsedType}),id}let t;const r=new nd;for(const s of this._def.checks)"int"===s.kind?Gc.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),sd(t,{code:Yc.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()):"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),sd(t,{code:Yc.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),sd(t,{code:Yc.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):"multipleOf"===s.kind?0!==Dd(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),sd(t,{code:Yc.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),sd(t,{code:Yc.not_finite,message:s.message}),r.dirty()):Gc.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,rd.toString(t))}gt(e,t){return this.setLimit("min",e,!1,rd.toString(t))}lte(e,t){return this.setLimit("max",e,!0,rd.toString(t))}lt(e,t){return this.setLimit("max",e,!1,rd.toString(t))}setLimit(e,t,r,s){return new Ld({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:rd.toString(s)}]})}_addCheck(e){return new Ld({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:rd.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:rd.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:rd.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:rd.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:rd.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:rd.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:rd.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:rd.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:rd.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&Gc.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Ld.create=e=>new Ld({checks:[],typeName:ku.ZodNumber,coerce:e?.coerce||!1,...md(e)});class Zd extends fd{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Bc.bigint)return this._getInvalidInput(e);let t;const r=new nd;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),sd(t,{code:Yc.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),sd(t,{code:Yc.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),sd(t,{code:Yc.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):Gc.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return sd(t,{code:Yc.invalid_type,expected:Bc.bigint,received:t.parsedType}),id}gte(e,t){return this.setLimit("min",e,!0,rd.toString(t))}gt(e,t){return this.setLimit("min",e,!1,rd.toString(t))}lte(e,t){return this.setLimit("max",e,!0,rd.toString(t))}lt(e,t){return this.setLimit("max",e,!1,rd.toString(t))}setLimit(e,t,r,s){return new Zd({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:rd.toString(s)}]})}_addCheck(e){return new Zd({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:rd.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:rd.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:rd.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:rd.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:rd.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Zd.create=e=>new Zd({checks:[],typeName:ku.ZodBigInt,coerce:e?.coerce??!1,...md(e)});class Fd extends fd{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==Bc.boolean){const t=this._getOrReturnCtx(e);return sd(t,{code:Yc.invalid_type,expected:Bc.boolean,received:t.parsedType}),id}return od(e.data)}}Fd.create=e=>new Fd({typeName:ku.ZodBoolean,coerce:e?.coerce||!1,...md(e)});class Hd extends fd{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Bc.date){const t=this._getOrReturnCtx(e);return sd(t,{code:Yc.invalid_type,expected:Bc.date,received:t.parsedType}),id}if(Number.isNaN(e.data.getTime()))return sd(this._getOrReturnCtx(e),{code:Yc.invalid_date}),id;const t=new nd;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),sd(r,{code:Yc.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),sd(r,{code:Yc.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):Gc.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Hd({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:rd.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:rd.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Hd.create=e=>new Hd({checks:[],coerce:e?.coerce||!1,typeName:ku.ZodDate,...md(e)});class Vd extends fd{_parse(e){if(this._getType(e)!==Bc.symbol){const t=this._getOrReturnCtx(e);return sd(t,{code:Yc.invalid_type,expected:Bc.symbol,received:t.parsedType}),id}return od(e.data)}}Vd.create=e=>new Vd({typeName:ku.ZodSymbol,...md(e)});class Kd extends fd{_parse(e){if(this._getType(e)!==Bc.undefined){const t=this._getOrReturnCtx(e);return sd(t,{code:Yc.invalid_type,expected:Bc.undefined,received:t.parsedType}),id}return od(e.data)}}Kd.create=e=>new Kd({typeName:ku.ZodUndefined,...md(e)});class Gd extends fd{_parse(e){if(this._getType(e)!==Bc.null){const t=this._getOrReturnCtx(e);return sd(t,{code:Yc.invalid_type,expected:Bc.null,received:t.parsedType}),id}return od(e.data)}}Gd.create=e=>new Gd({typeName:ku.ZodNull,...md(e)});class Wd extends fd{constructor(){super(...arguments),this._any=!0}_parse(e){return od(e.data)}}Wd.create=e=>new Wd({typeName:ku.ZodAny,...md(e)});class Jd extends fd{constructor(){super(...arguments),this._unknown=!0}_parse(e){return od(e.data)}}Jd.create=e=>new Jd({typeName:ku.ZodUnknown,...md(e)});class Bd extends fd{_parse(e){const t=this._getOrReturnCtx(e);return sd(t,{code:Yc.invalid_type,expected:Bc.never,received:t.parsedType}),id}}Bd.create=e=>new Bd({typeName:ku.ZodNever,...md(e)});class Qd extends fd{_parse(e){if(this._getType(e)!==Bc.undefined){const t=this._getOrReturnCtx(e);return sd(t,{code:Yc.invalid_type,expected:Bc.void,received:t.parsedType}),id}return od(e.data)}}Qd.create=e=>new Qd({typeName:ku.ZodVoid,...md(e)});class Yd extends fd{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==Bc.array)return sd(t,{code:Yc.invalid_type,expected:Bc.array,received:t.parsedType}),id;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(sd(t,{code:e?Yc.too_big:Yc.too_small,minimum:n?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(sd(t,{code:Yc.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(sd(t,{code:Yc.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>s.type._parseAsync(new hd(t,e,t.path,r)))).then(e=>nd.mergeArray(r,e));const n=[...t.data].map((e,r)=>s.type._parseSync(new hd(t,e,t.path,r)));return nd.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new Yd({...this._def,minLength:{value:e,message:rd.toString(t)}})}max(e,t){return new Yd({...this._def,maxLength:{value:e,message:rd.toString(t)}})}length(e,t){return new Yd({...this._def,exactLength:{value:e,message:rd.toString(t)}})}nonempty(e){return this.min(1,e)}}function Xd(e){if(e instanceof eu){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=mu.create(Xd(s))}return new eu({...e._def,shape:()=>t})}return e instanceof Yd?new Yd({...e._def,type:Xd(e.element)}):e instanceof mu?mu.create(Xd(e.unwrap())):e instanceof fu?fu.create(Xd(e.unwrap())):e instanceof nu?nu.create(e.items.map(e=>Xd(e))):e}Yd.create=(e,t)=>new Yd({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ku.ZodArray,...md(t)});class eu extends fd{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=Gc.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Bc.object){const t=this._getOrReturnCtx(e);return sd(t,{code:Yc.invalid_type,expected:Bc.object,received:t.parsedType}),id}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof Bd&&"strip"===this._def.unknownKeys))for(const e in r.data)n.includes(e)||i.push(e);const a=[];for(const e of n){const t=s[e],n=r.data[e];a.push({key:{status:"valid",value:e},value:t._parse(new hd(r,n,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof Bd){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)a.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)i.length>0&&(sd(r,{code:Yc.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const s=r.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new hd(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of a){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>nd.mergeObjectSync(t,e)):nd.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return rd.errToObj,new eu({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const s=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:rd.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new eu({...this._def,unknownKeys:"strip"})}passthrough(){return new eu({...this._def,unknownKeys:"passthrough"})}extend(e){return new eu({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new eu({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ku.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new eu({...this._def,catchall:e})}pick(e){const t={};for(const r of Gc.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new eu({...this._def,shape:()=>t})}omit(e){const t={};for(const r of Gc.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new eu({...this._def,shape:()=>t})}deepPartial(){return Xd(this)}partial(e){const t={};for(const r of Gc.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new eu({...this._def,shape:()=>t})}required(e){const t={};for(const r of Gc.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof mu;)e=e._def.innerType;t[r]=e}return new eu({...this._def,shape:()=>t})}keyof(){return du(Gc.objectKeys(this.shape))}}eu.create=(e,t)=>new eu({shape:()=>e,unknownKeys:"strip",catchall:Bd.create(),typeName:ku.ZodObject,...md(t)}),eu.strictCreate=(e,t)=>new eu({shape:()=>e,unknownKeys:"strict",catchall:Bd.create(),typeName:ku.ZodObject,...md(t)}),eu.lazycreate=(e,t)=>new eu({shape:e,unknownKeys:"strip",catchall:Bd.create(),typeName:ku.ZodObject,...md(t)});class tu extends fd{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new Xc(e.ctx.common.issues));return sd(t,{code:Yc.invalid_union,unionErrors:r}),id});{let e;const s=[];for(const n of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map(e=>new Xc(e));return sd(t,{code:Yc.invalid_union,unionErrors:n}),id}}get options(){return this._def.options}}function ru(e,t){const r=Qc(e),s=Qc(t);if(e===t)return{valid:!0,data:e};if(r===Bc.object&&s===Bc.object){const r=Gc.objectKeys(t),s=Gc.objectKeys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const r of s){const s=ru(e[r],t[r]);if(!s.valid)return{valid:!1};n[r]=s.data}return{valid:!0,data:n}}if(r===Bc.array&&s===Bc.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=ru(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===Bc.date&&s===Bc.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}tu.create=(e,t)=>new tu({options:e,typeName:ku.ZodUnion,...md(t)});class su extends fd{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(cd(e)||cd(s))return id;const n=ru(e.value,s.value);return n.valid?((dd(e)||dd(s))&&t.dirty(),{status:t.value,value:n.data}):(sd(r,{code:Yc.invalid_intersection_types}),id)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}su.create=(e,t,r)=>new su({left:e,right:t,typeName:ku.ZodIntersection,...md(r)});class nu extends fd{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Bc.array)return sd(r,{code:Yc.invalid_type,expected:Bc.array,received:r.parsedType}),id;if(r.data.length<this._def.items.length)return sd(r,{code:Yc.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),id;!this._def.rest&&r.data.length>this._def.items.length&&(sd(r,{code:Yc.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new hd(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>nd.mergeArray(t,e)):nd.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new nu({...this._def,rest:e})}}nu.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new nu({items:e,typeName:ku.ZodTuple,rest:null,...md(t)})};class iu extends fd{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Bc.map)return sd(r,{code:Yc.invalid_type,expected:Bc.map,received:r.parsedType}),id;const s=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map(([e,t],i)=>({key:s._parse(new hd(r,e,r.path,[i,"key"])),value:n._parse(new hd(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of i){const s=await r.key,n=await r.value;if("aborted"===s.status||"aborted"===n.status)return id;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of i){const s=r.key,n=r.value;if("aborted"===s.status||"aborted"===n.status)return id;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}iu.create=(e,t,r)=>new iu({valueType:t,keyType:e,typeName:ku.ZodMap,...md(r)});class au extends fd{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Bc.set)return sd(r,{code:Yc.invalid_type,expected:Bc.set,received:r.parsedType}),id;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(sd(r,{code:Yc.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&(sd(r,{code:Yc.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const r=new Set;for(const s of e){if("aborted"===s.status)return id;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const a=[...r.data.values()].map((e,t)=>n._parse(new hd(r,e,r.path,t)));return r.common.async?Promise.all(a).then(e=>i(e)):i(a)}min(e,t){return new au({...this._def,minSize:{value:e,message:rd.toString(t)}})}max(e,t){return new au({...this._def,maxSize:{value:e,message:rd.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}au.create=(e,t)=>new au({valueType:e,minSize:null,maxSize:null,typeName:ku.ZodSet,...md(t)});class ou extends fd{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ou.create=(e,t)=>new ou({getter:e,typeName:ku.ZodLazy,...md(t)});class cu extends fd{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return sd(t,{received:t.data,code:Yc.invalid_literal,expected:this._def.value}),id}return{status:"valid",value:e.data}}get value(){return this._def.value}}function du(e,t){return new uu({values:e,typeName:ku.ZodEnum,...md(t)})}cu.create=(e,t)=>new cu({value:e,typeName:ku.ZodLiteral,...md(t)});class uu extends fd{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return sd(t,{expected:Gc.joinValues(r),received:t.parsedType,code:Yc.invalid_type}),id}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return sd(t,{received:t.data,code:Yc.invalid_enum_value,options:r}),id}return od(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return uu.create(e,{...this._def,...t})}exclude(e,t=this._def){return uu.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}uu.create=du;class lu extends fd{_parse(e){const t=Gc.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Bc.string&&r.parsedType!==Bc.number){const e=Gc.objectValues(t);return sd(r,{expected:Gc.joinValues(e),received:r.parsedType,code:Yc.invalid_type}),id}if(this._cache||(this._cache=new Set(Gc.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=Gc.objectValues(t);return sd(r,{received:r.data,code:Yc.invalid_enum_value,options:e}),id}return od(e.data)}get enum(){return this._def.values}}lu.create=(e,t)=>new lu({values:e,typeName:ku.ZodNativeEnum,...md(t)});class hu extends fd{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Bc.promise&&!1===t.common.async)return sd(t,{code:Yc.invalid_type,expected:Bc.promise,received:t.parsedType}),id;const r=t.parsedType===Bc.promise?t.data:Promise.resolve(t.data);return od(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}hu.create=(e,t)=>new hu({type:e,typeName:ku.ZodPromise,...md(t)});class pu extends fd{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ku.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,n={addIssue:e=>{sd(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===s.type){const e=s.transform(r.data,n);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return id;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?id:"dirty"===s.status||"dirty"===t.value?ad(s.value):s});{if("aborted"===t.value)return id;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?id:"dirty"===s.status||"dirty"===t.value?ad(s.value):s}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,n);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===s.status?id:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?id:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===s.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ud(e))return id;const i=s.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>ud(e)?Promise.resolve(s.transform(e.value,n)).then(e=>({status:t.value,value:e})):id)}Gc.assertNever(s)}}pu.create=(e,t,r)=>new pu({schema:e,typeName:ku.ZodEffects,effect:t,...md(r)}),pu.createWithPreprocess=(e,t,r)=>new pu({schema:t,effect:{type:"preprocess",transform:e},typeName:ku.ZodEffects,...md(r)});class mu extends fd{_parse(e){return this._getType(e)===Bc.undefined?od(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}mu.create=(e,t)=>new mu({innerType:e,typeName:ku.ZodOptional,...md(t)});class fu extends fd{_parse(e){return this._getType(e)===Bc.null?od(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}fu.create=(e,t)=>new fu({innerType:e,typeName:ku.ZodNullable,...md(t)});class gu extends fd{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===Bc.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}gu.create=(e,t)=>new gu({innerType:e,typeName:ku.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...md(t)});class _u extends fd{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ld(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Xc(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new Xc(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}_u.create=(e,t)=>new _u({innerType:e,typeName:ku.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...md(t)});class yu extends fd{_parse(e){if(this._getType(e)!==Bc.nan){const t=this._getOrReturnCtx(e);return sd(t,{code:Yc.invalid_type,expected:Bc.nan,received:t.parsedType}),id}return{status:"valid",value:e.data}}}yu.create=e=>new yu({typeName:ku.ZodNaN,...md(e)}),Symbol("zod_brand");class vu extends fd{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class wu extends fd{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?id:"dirty"===e.status?(t.dirty(),ad(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?id:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new wu({in:e,out:t,typeName:ku.ZodPipeline})}}class bu extends fd{_parse(e){const t=this._def.innerType._parse(e),r=e=>(ud(e)&&(e.value=Object.freeze(e.value)),e);return ld(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}var ku;bu.create=(e,t)=>new bu({innerType:e,typeName:ku.ZodReadonly,...md(t)}),eu.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(ku||(ku={})),Ud.create,Ld.create,yu.create,Zd.create,Fd.create,Hd.create,Vd.create,Kd.create,Gd.create,Wd.create,Jd.create,Bd.create,Qd.create,Yd.create;const Su=eu.create,$u=(eu.strictCreate,tu.create,su.create,nu.create,iu.create,au.create,ou.create,cu.create,uu.create,lu.create,hu.create,pu.create,mu.create,fu.create,pu.createWithPreprocess,wu.create,n("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ne.init(e,t),e.def=t,e.parse=(t,r)=>Te(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>Re(e,t,r),e.parseAsync=async(t,r)=>Pe(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>Ce(e,t,r),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>J(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e)})),Eu=n("ZodMiniObject",(e,t)=>{_t.init(e,t),$u.init(e,t),D(e,"shape",()=>t.shape)});function Tu(e,t){const r={type:"object",get shape(){return L(this,"shape",{...e}),this.shape},...B(t)};return new Eu(r)}function xu(e){return!!e._zod}function Pu(e){const t=Object.values(e);if(0===t.length)return Tu({});const r=t.every(xu),s=t.every(e=>!xu(e));if(r)return Tu(e);if(s)return Su(e);throw new Error("Mixed Zod versions detected in object shape.")}function Iu(e,t){return xu(e)?Re(e,t):e.safeParse(t)}async function Ru(e,t){if(xu(e))return await Ce(e,t);const r=e;return await r.safeParseAsync(t)}function Ou(e){if(!e)return;let t;if(xu(e)){const r=e;t=r._zod?.def?.shape}else t=e.shape;if(t){if("function"==typeof t)try{return t()}catch{return}return t}}function Cu(e){if(e){if("object"==typeof e){const t=e;if(!e._def&&!t._zod){const t=Object.values(e);if(t.length>0&&t.every(e=>"object"==typeof e&&null!==e&&(void 0!==e._def||void 0!==e._zod||"function"==typeof e.parse)))return Pu(e)}}if(xu(e)){const t=e,r=t._zod?.def;if(r&&("object"===r.type||void 0!==r.shape))return e}else if(void 0!==e.shape)return e}}function Au(e){if(e&&"object"==typeof e){if("message"in e&&"string"==typeof e.message)return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){const t=e.issues[0];if(t&&"object"==typeof t&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function Nu(e){if(xu(e)){const t=e,r=t._zod?.def;if(r){if(void 0!==r.value)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}}const t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const r=e.value;if(void 0!==r)return r}function ju(e){return"completed"===e||"failed"===e||"cancelled"===e}class zu{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Ht,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var r;const s=e._zod.def,n={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,t.schemaPath.includes(e)&&(i.cycle=t.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,a);const o=e._zod.toJSONSchema?.();if(o)a.schema=o;else{const r={...t,schemaPath:[...t.schemaPath,e],path:t.path},i=e._zod.parent;if(i)a.ref=i,this.process(i,r),this.seen.get(i).isParent=!0;else{const t=a.schema;switch(s.type){case"string":{const r=t;r.type="string";const{minimum:s,maximum:i,format:o,patterns:c,contentEncoding:d}=e._zod.bag;if("number"==typeof s&&(r.minLength=s),"number"==typeof i&&(r.maxLength=i),o&&(r.format=n[o]??o,""===r.format&&delete r.format),d&&(r.contentEncoding=d),c&&c.size>0){const e=[...c];1===e.length?r.pattern=e[0].source:e.length>1&&(a.schema.allOf=[...e.map(e=>({..."draft-7"===this.target?{type:"string"}:{},pattern:e.source}))])}break}case"number":{const r=t,{minimum:s,maximum:n,format:i,multipleOf:a,exclusiveMaximum:o,exclusiveMinimum:c}=e._zod.bag;"string"==typeof i&&i.includes("int")?r.type="integer":r.type="number","number"==typeof c&&(r.exclusiveMinimum=c),"number"==typeof s&&(r.minimum=s,"number"==typeof c&&(c>=s?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof o&&(r.exclusiveMaximum=o),"number"==typeof n&&(r.maximum=n,"number"==typeof o&&(o<=n?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof a&&(r.multipleOf=a);break}case"boolean":case"success":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema");break;case"null":t.type="null";break;case"any":case"unknown":break;case"undefined":if("throw"===this.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema");break;case"void":if("throw"===this.unrepresentable)throw new Error("Void cannot be represented in JSON Schema");break;case"never":t.not={};break;case"date":if("throw"===this.unrepresentable)throw new Error("Date cannot be represented in JSON Schema");break;case"array":{const n=t,{minimum:i,maximum:a}=e._zod.bag;"number"==typeof i&&(n.minItems=i),"number"==typeof a&&(n.maxItems=a),n.type="array",n.items=this.process(s.element,{...r,path:[...r.path,"items"]});break}case"object":{const e=t;e.type="object",e.properties={};const n=s.shape;for(const t in n)e.properties[t]=this.process(n[t],{...r,path:[...r.path,"properties",t]});const i=new Set(Object.keys(n)),a=new Set([...i].filter(e=>{const t=s.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout}));a.size>0&&(e.required=Array.from(a)),"never"===s.catchall?._zod.def.type?e.additionalProperties=!1:s.catchall?s.catchall&&(e.additionalProperties=this.process(s.catchall,{...r,path:[...r.path,"additionalProperties"]})):"output"===this.io&&(e.additionalProperties=!1);break}case"union":t.anyOf=s.options.map((e,t)=>this.process(e,{...r,path:[...r.path,"anyOf",t]}));break;case"intersection":{const e=t,n=this.process(s.left,{...r,path:[...r.path,"allOf",0]}),i=this.process(s.right,{...r,path:[...r.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length,o=[...a(n)?n.allOf:[n],...a(i)?i.allOf:[i]];e.allOf=o;break}case"tuple":{const n=t;n.type="array";const i=s.items.map((e,t)=>this.process(e,{...r,path:[...r.path,"prefixItems",t]}));if("draft-2020-12"===this.target?n.prefixItems=i:n.items=i,s.rest){const e=this.process(s.rest,{...r,path:[...r.path,"items"]});"draft-2020-12"===this.target?n.items=e:n.additionalItems=e}s.rest&&(n.items=this.process(s.rest,{...r,path:[...r.path,"items"]}));const{minimum:a,maximum:o}=e._zod.bag;"number"==typeof a&&(n.minItems=a),"number"==typeof o&&(n.maxItems=o);break}case"record":{const e=t;e.type="object",e.propertyNames=this.process(s.keyType,{...r,path:[...r.path,"propertyNames"]}),e.additionalProperties=this.process(s.valueType,{...r,path:[...r.path,"additionalProperties"]});break}case"map":if("throw"===this.unrepresentable)throw new Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw new Error("Set cannot be represented in JSON Schema");break;case"enum":{const e=t,r=j(s.entries);r.every(e=>"number"==typeof e)&&(e.type="number"),r.every(e=>"string"==typeof e)&&(e.type="string"),e.enum=r;break}case"literal":{const e=t,r=[];for(const e of s.values)if(void 0===e){if("throw"===this.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===this.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");r.push(Number(e))}else r.push(e);if(0===r.length);else if(1===r.length){const t=r[0];e.type=null===t?"null":typeof t,e.const=t}else r.every(e=>"number"==typeof e)&&(e.type="number"),r.every(e=>"string"==typeof e)&&(e.type="string"),r.every(e=>"boolean"==typeof e)&&(e.type="string"),r.every(e=>null===e)&&(e.type="null"),e.enum=r;break}case"file":{const r=t,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:n,maximum:i,mime:a}=e._zod.bag;void 0!==n&&(s.minLength=n),void 0!==i&&(s.maxLength=i),a?1===a.length?(s.contentMediaType=a[0],Object.assign(r,s)):r.anyOf=a.map(e=>({...s,contentMediaType:e})):Object.assign(r,s);break}case"transform":if("throw"===this.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema");break;case"nullable":{const e=this.process(s.innerType,r);t.anyOf=[e,{type:"null"}];break}case"nonoptional":case"promise":case"optional":this.process(s.innerType,r),a.ref=s.innerType;break;case"default":this.process(s.innerType,r),a.ref=s.innerType,t.default=JSON.parse(JSON.stringify(s.defaultValue));break;case"prefault":this.process(s.innerType,r),a.ref=s.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break;case"catch":{let e;this.process(s.innerType,r),a.ref=s.innerType;try{e=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{const r=t,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=s.source;break}case"pipe":{const e="input"===this.io?"transform"===s.in._zod.def.type?s.out:s.in:s.out;this.process(e,r),a.ref=e;break}case"readonly":this.process(s.innerType,r),a.ref=s.innerType,t.readOnly=!0;break;case"lazy":{const t=e._zod.innerType;this.process(t,r),a.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")}}}const c=this.metadataRegistry.get(e);return c&&Object.assign(a.schema,c),"input"===this.io&&Mu(e)&&(delete a.schema.examples,delete a.schema.default),"input"===this.io&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,t){const r={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=e=>{const t="draft-2020-12"===this.target?"$defs":"definitions";if(r.external){const s=r.external.registry.get(e[0])?.id,n=r.external.uri??(e=>e);if(s)return{ref:n(s)};const i=e[1].defId??e[1].schema.id??"schema"+this.counter++;return e[1].defId=i,{defId:i,ref:`${n("__shared")}#/${t}/${i}`}}if(e[1]===s)return{ref:"#"};const n=`#/${t}/`,i=e[1].schema.id??"__schema"+this.counter++;return{defId:i,ref:n+i}},i=e=>{if(e[1].schema.$ref)return;const t=e[1],{ref:r,defId:s}=n(e);t.def={...t.schema},s&&(t.defId=s);const i=t.schema;for(const e in i)delete i[e];i.$ref=r};if("throw"===r.cycles)for(const e of this.seen.entries()){const t=e[1];if(t.cycle)throw new Error(`Cycle detected: #/${t.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const t of this.seen.entries()){const s=t[1];if(e===t[0]){i(t);continue}if(r.external){const s=r.external.registry.get(t[0])?.id;if(e!==t[0]&&s){i(t);continue}}const n=this.metadataRegistry.get(t[0])?.id;(n||s.cycle||s.count>1&&"ref"===r.reused)&&i(t)}const a=(e,t)=>{const r=this.seen.get(e),s=r.def??r.schema,n={...s};if(null===r.ref)return;const i=r.ref;if(r.ref=null,i){a(i,t);const e=this.seen.get(i).schema;e.$ref&&"draft-7"===t.target?(s.allOf=s.allOf??[],s.allOf.push(e)):(Object.assign(s,e),Object.assign(s,n))}r.isParent||this.override({zodSchema:e,jsonSchema:s,path:r.path??[]})};for(const e of[...this.seen.entries()].reverse())a(e[0],{target:this.target});const o={};if("draft-2020-12"===this.target?o.$schema="https://json-schema.org/draft/2020-12/schema":"draft-7"===this.target?o.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const t=r.external.registry.get(e)?.id;if(!t)throw new Error("Schema is missing an `id` property");o.$id=r.external.uri(t)}Object.assign(o,s.def);const c=r.external?.defs??{};for(const e of this.seen.entries()){const t=e[1];t.def&&t.defId&&(c[t.defId]=t.def)}r.external||Object.keys(c).length>0&&("draft-2020-12"===this.target?o.$defs=c:o.definitions=c);try{return JSON.parse(JSON.stringify(o))}catch(e){throw new Error("Error converting schema to JSON.")}}}function Mu(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const s=e._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":case"custom":case"success":case"catch":return!1;case"array":return Mu(s.element,r);case"object":for(const e in s.shape)if(Mu(s.shape[e],r))return!0;return!1;case"union":for(const e of s.options)if(Mu(e,r))return!0;return!1;case"intersection":return Mu(s.left,r)||Mu(s.right,r);case"tuple":for(const e of s.items)if(Mu(e,r))return!0;return!(!s.rest||!Mu(s.rest,r));case"record":case"map":return Mu(s.keyType,r)||Mu(s.valueType,r);case"set":return Mu(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return Mu(s.innerType,r);case"lazy":return Mu(s.getter(),r);case"transform":return!0;case"pipe":return Mu(s.in,r)||Mu(s.out,r)}throw new Error(`Unknown schema type: ${s.type}`)}const qu=Symbol("Let zodToJsonSchema decide on which parser to use"),Uu={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Du=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function Lu(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?Du(t,e.currentPath):t.join("/")}}function Zu(e,t,r,s){s?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Fu(e,t,r,s,n){e[t]=r,Zu(e,t,s,n)}function Hu(e,t){return gl(e.type._def,t)}function Vu(e,t,r){const s=r??t.dateStrategy;if(Array.isArray(s))return{anyOf:s.map((r,s)=>Vu(e,t,r))};switch(s){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ku(e,t)}}const Ku=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const s of e.checks)switch(s.kind){case"min":Fu(r,"minimum",s.value,s.message,t);break;case"max":Fu(r,"maximum",s.value,s.message,t)}return r};let Gu;const Wu=/^[cC][^\s-]{8,}$/,Ju=/^[0-9a-z]+$/,Bu=/^[0-9A-HJKMNP-TV-Z]{26}$/,Qu=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Yu=()=>(void 0===Gu&&(Gu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Gu),Xu=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,el=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,tl=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,sl=/^[a-zA-Z0-9_-]{21}$/,nl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function il(e,t){const r={type:"string"};if(e.checks)for(const s of e.checks)switch(s.kind){case"min":Fu(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,s.value):s.value,s.message,t);break;case"max":Fu(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,s.value):s.value,s.message,t);break;case"email":switch(t.emailStrategy){case"format:email":cl(r,"email",s.message,t);break;case"format:idn-email":cl(r,"idn-email",s.message,t);break;case"pattern:zod":dl(r,Qu,s.message,t)}break;case"url":cl(r,"uri",s.message,t);break;case"uuid":cl(r,"uuid",s.message,t);break;case"regex":dl(r,s.regex,s.message,t);break;case"cuid":dl(r,Wu,s.message,t);break;case"cuid2":dl(r,Ju,s.message,t);break;case"startsWith":dl(r,RegExp(`^${al(s.value,t)}`),s.message,t);break;case"endsWith":dl(r,RegExp(`${al(s.value,t)}$`),s.message,t);break;case"datetime":cl(r,"date-time",s.message,t);break;case"date":cl(r,"date",s.message,t);break;case"time":cl(r,"time",s.message,t);break;case"duration":cl(r,"duration",s.message,t);break;case"length":Fu(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,s.value):s.value,s.message,t),Fu(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,s.value):s.value,s.message,t);break;case"includes":dl(r,RegExp(al(s.value,t)),s.message,t);break;case"ip":"v6"!==s.version&&cl(r,"ipv4",s.message,t),"v4"!==s.version&&cl(r,"ipv6",s.message,t);break;case"base64url":dl(r,rl,s.message,t);break;case"jwt":dl(r,nl,s.message,t);break;case"cidr":"v6"!==s.version&&dl(r,Xu,s.message,t),"v4"!==s.version&&dl(r,el,s.message,t);break;case"emoji":dl(r,Yu(),s.message,t);break;case"ulid":dl(r,Bu,s.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":cl(r,"binary",s.message,t);break;case"contentEncoding:base64":Fu(r,"contentEncoding","base64",s.message,t);break;case"pattern:zod":dl(r,tl,s.message,t)}break;case"nanoid":dl(r,sl,s.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:(()=>{})()}return r}function al(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)ol.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}const ol=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function cl(e,t,r,s){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&s.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&s.errorMessages&&{errorMessage:{format:r}}})):Fu(e,"format",t,r,s)}function dl(e,t,r,s){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&s.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:ul(t,s),...r&&s.errorMessages&&{errorMessage:{pattern:r}}})):Fu(e,"pattern",ul(t,s),r,s)}function ul(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),s=e.flags.includes("m"),n=e.flags.includes("s"),i=r?e.source.toLowerCase():e.source;let a="",o=!1,c=!1,d=!1;for(let e=0;e<i.length;e++)if(o)a+=i[e],o=!1;else{if(r)if(c){if(i[e].match(/[a-z]/)){d?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),d=!1):"-"===i[e+1]&&i[e+2]?.match(/[a-z]/)?(a+=i[e],d=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}if(s){if("^"===i[e]){a+="(^|(?<=[\r\n]))";continue}if("$"===i[e]){a+="($|(?=[\r\n]))";continue}}n&&"."===i[e]?a+=c?`${i[e]}\r\n`:`[${i[e]}\r\n]`:(a+=i[e],"\\"===i[e]?o=!0:c&&"]"===i[e]?c=!1:c||"["!==i[e]||(c=!0))}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function ll(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===ku.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,s)=>({...r,[s]:gl(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",s]})??Lu(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:gl(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===ku.ZodString&&e.keyType._def.checks?.length){const{type:s,...n}=il(e.keyType._def,t);return{...r,propertyNames:n}}if(e.keyType?._def.typeName===ku.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ku.ZodBranded&&e.keyType._def.type._def.typeName===ku.ZodString&&e.keyType._def.type._def.checks?.length){const{type:s,...n}=Hu(e.keyType._def,t);return{...r,propertyNames:n}}return r}const hl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},pl=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>gl(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function ml(e){try{return e.isOptional()}catch{return!0}}const fl=(e,t,r)=>{switch(t){case ku.ZodString:return il(e,r);case ku.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const s of e.checks)switch(s.kind){case"int":r.type="integer",Zu(r,"type",s.message,t);break;case"min":"jsonSchema7"===t.target?s.inclusive?Fu(r,"minimum",s.value,s.message,t):Fu(r,"exclusiveMinimum",s.value,s.message,t):(s.inclusive||(r.exclusiveMinimum=!0),Fu(r,"minimum",s.value,s.message,t));break;case"max":"jsonSchema7"===t.target?s.inclusive?Fu(r,"maximum",s.value,s.message,t):Fu(r,"exclusiveMaximum",s.value,s.message,t):(s.inclusive||(r.exclusiveMaximum=!0),Fu(r,"maximum",s.value,s.message,t));break;case"multipleOf":Fu(r,"multipleOf",s.value,s.message,t)}return r}(e,r);case ku.ZodObject:return function(e,t){const r="openAi"===t.target,s={type:"object",properties:{}},n=[],i=e.shape();for(const e in i){let a=i[e];if(void 0===a||void 0===a._def)continue;let o=ml(a);o&&r&&("ZodOptional"===a._def.typeName&&(a=a._def.innerType),a.isNullable()||(a=a.nullable()),o=!1);const c=gl(a._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==c&&(s.properties[e]=c,o||n.push(e))}n.length&&(s.required=n);const a=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return gl(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==a&&(s.additionalProperties=a),s}(e,r);case ku.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const s of e.checks)switch(s.kind){case"min":"jsonSchema7"===t.target?s.inclusive?Fu(r,"minimum",s.value,s.message,t):Fu(r,"exclusiveMinimum",s.value,s.message,t):(s.inclusive||(r.exclusiveMinimum=!0),Fu(r,"minimum",s.value,s.message,t));break;case"max":"jsonSchema7"===t.target?s.inclusive?Fu(r,"maximum",s.value,s.message,t):Fu(r,"exclusiveMaximum",s.value,s.message,t):(s.inclusive||(r.exclusiveMaximum=!0),Fu(r,"maximum",s.value,s.message,t));break;case"multipleOf":Fu(r,"multipleOf",s.value,s.message,t)}return r}(e,r);case ku.ZodBoolean:return{type:"boolean"};case ku.ZodDate:return Vu(e,r);case ku.ZodUndefined:return function(e){return{not:Lu(e)}}(r);case ku.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case ku.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==ku.ZodAny&&(r.items=gl(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Fu(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Fu(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Fu(r,"minItems",e.exactLength.value,e.exactLength.message,t),Fu(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case ku.ZodUnion:case ku.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return pl(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e._def.typeName in hl&&(!e._def.checks||!e._def.checks.length))){const e=r.reduce((e,t)=>{const r=hl[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(r.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){const e=r.reduce((e,t)=>{const r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===r.length){const t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:r.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(r.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:r.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return pl(e,t)}(e,r);case ku.ZodIntersection:return function(e,t){const r=[gl(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),gl(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e);let s="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const n=[];return r.forEach(e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...s}=e;t=s}else s=void 0;n.push(t)}else n.push(...e.allOf),void 0===e.unevaluatedProperties&&(s=void 0);var t}),n.length?{allOf:n,...s}:void 0}(e,r);case ku.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>gl(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:gl(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>gl(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,r);case ku.ZodRecord:return ll(e,r);case ku.ZodLiteral:return function(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case ku.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case ku.ZodNativeEnum:return function(e){const t=e.values,r=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),s=Array.from(new Set(r.map(e=>typeof e)));return{type:1===s.length?"string"===s[0]?"string":"number":["string","number"],enum:r}}(e);case ku.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:hl[e.innerType._def.typeName],nullable:!0}:{type:[hl[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=gl(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=gl(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case ku.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return gl(e.innerType._def,t);const r=gl(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Lu(t)},r]}:Lu(t)})(e,r);case ku.ZodMap:return function(e,t){return"record"===t.mapStrategy?ll(e,t):{type:"array",maxItems:125,items:{type:"array",items:[gl(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Lu(t),gl(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Lu(t)],minItems:2,maxItems:2}}}(e,r);case ku.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:gl(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Fu(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Fu(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case ku.ZodLazy:return()=>e.getter()._def;case ku.ZodPromise:return function(e,t){return gl(e.type._def,t)}(e,r);case ku.ZodNaN:case ku.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:Lu({...e,currentPath:[...e.currentPath,"not"]})}}(r);case ku.ZodEffects:return function(e,t){return"input"===t.effectStrategy?gl(e.schema._def,t):Lu(t)}(e,r);case ku.ZodAny:return Lu(r);case ku.ZodUnknown:return function(e){return Lu(e)}(r);case ku.ZodDefault:return function(e,t){return{...gl(e.innerType._def,t),default:e.defaultValue()}}(e,r);case ku.ZodBranded:return Hu(e,r);case ku.ZodReadonly:case ku.ZodCatch:return((e,t)=>gl(e.innerType._def,t))(e,r);case ku.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return gl(e.in._def,t);if("output"===t.pipeStrategy)return gl(e.out._def,t);const r=gl(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,gl(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter(e=>void 0!==e)}})(e,r);case ku.ZodFunction:case ku.ZodVoid:case ku.ZodSymbol:default:return}};function gl(e,t,r=!1){const s=t.seen.get(e);if(t.override){const n=t.override?.(e,t,s,r);if(n!==qu)return n}if(s&&!r){const e=_l(s,t);if(void 0!==e)return e}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const i=fl(e,e.typeName,t),a="function"==typeof i?gl(i(),t):i;if(a&&yl(e,t,a),t.postProcess){const r=t.postProcess(a,e,t);return n.jsonSchema=a,r}return n.jsonSchema=a,a}const _l=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Du(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Lu(t)):"seen"===t.$refStrategy?Lu(t):void 0}},yl=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function vl(e){return e?"jsonSchema7"===e||"draft-7"===e?"draft-7":"jsonSchema2019-09"===e||"draft-2020-12"===e?"draft-2020-12":"draft-7":"draft-7"}function wl(e,t){return xu(e)?function(e,t){if(e instanceof Zt){const r=new zu(t),s={};for(const t of e._idmap.entries()){const[e,s]=t;r.process(s)}const n={},i={registry:e,uri:t?.uri,defs:s};for(const s of e._idmap.entries()){const[e,a]=s;n[e]=r.emit(a,{...t,external:i})}if(Object.keys(s).length>0){const e="draft-2020-12"===r.target?"$defs":"definitions";n.__shared={[e]:s}}return{schemas:n}}const r=new zu(t);return r.process(e),r.emit(e,t)}(e,{target:vl(t?.target),io:t?.pipeStrategy??"input"}):((e,t)=>{const r=(e=>{const t=(e=>"string"==typeof e?{...Uu,name:e}:{...Uu,...e})(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}})(t);let s=t.definitions?Object.entries(t.definitions).reduce((e,[t,s])=>({...e,[t]:gl(s._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??Lu(r)}),{}):void 0;const n="title"===t?.nameStrategy?void 0:t?.name,i=gl(e._def,void 0===n?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Lu(r),a=void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==a&&(i.title=a),r.flags.hasReferencedOpenAiAnyType&&(s||(s={}),s[r.openAiAnyTypeName]||(s[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===r.$refStrategy?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const o=void 0===n?s?{...i,[r.definitionPath]:s}:i:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...s,[n]:i}};return"jsonSchema7"===r.target?o.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(o.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o})(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function bl(e){const t=Ou(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const s=Nu(r);if("string"!=typeof s)throw new Error("Schema method literal must be a string");return s}function kl(e,t){const r=Iu(e,t);if(!r.success)throw r.error;return r.data}class Sl{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Xs,e=>{this._oncancel(e)}),this.setNotificationHandler(yn,e=>{this._onprogress(e)}),this.setRequestHandler(fn,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(xn,async(e,t)=>{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new pa(Ws.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(In,async(e,t)=>{const r=async()=>{const s=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(s,t.sessionId);){if("response"===e.type||"error"===e.type){const t=e.message,r=t.id,s=this._requestResolvers.get(r);if(s)if(this._requestResolvers.delete(r),"response"===e.type)s(t);else{const e=t;s(new pa(e.error.code,e.error.message,e.error.data))}else{const t="response"===e.type?"Response":"Error";this._onerror(new Error(`${t} handler missing for request ${r}`))}continue}await(this._transport?.send(e.message,{relatedRequestId:t.requestId}))}}const n=await this._taskStore.getTask(s,t.sessionId);if(!n)throw new pa(Ws.InvalidParams,`Task not found: ${s}`);if(!ju(n.status))return await this._waitForTaskUpdate(s,t.signal),await r();if(ju(n.status)){const e=await this._taskStore.getTaskResult(s,t.sessionId);return this._clearTaskQueue(s),{...e,_meta:{...e._meta,[xs]:{taskId:s}}}}return await r()};return await r()}),this.setRequestHandler(Rn,async(e,t)=>{try{const{tasks:r,nextCursor:s}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:r,nextCursor:s,_meta:{}}}catch(e){throw new pa(Ws.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Cn,async(e,t)=>{try{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new pa(Ws.InvalidParams,`Task not found: ${e.params.taskId}`);if(ju(r.status))throw new pa(Ws.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);const s=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!s)throw new pa(Ws.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...s}}catch(e){if(e instanceof pa)throw e;throw new pa(Ws.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,r,s,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:s})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),pa.fromError(Ws.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=e=>{r?.(e),this._onerror(e)};const s=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{var r;s?.(e,t),Gs(e)||(e=>Js.safeParse(e).success)(e)?this._onresponse(e):Hs(e)?this._onrequest(e,t):(r=e,Vs.safeParse(r).success?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`)))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();const t=pa.fromError(Ws.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,n=e.params?._meta?.[xs]?.taskId;if(void 0===r){const t={jsonrpc:"2.0",id:e.id,error:{code:Ws.MethodNotFound,message:"Method not found"}};return void(n&&this._taskMessageQueue?this._enqueueTaskMessage(n,{type:"error",message:t,timestamp:Date.now()},s?.sessionId).catch(e=>this._onerror(new Error(`Failed to enqueue error response: ${e}`))):s?.send(t).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))))}const i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);const a=(o=e.params,Ms.safeParse(o).success?e.params.task:void 0);var o;const c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,d={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(i.signal.aborted)return;const r={relatedRequestId:e.id};n&&(r.relatedTask={taskId:n}),await this.notification(t,r)},sendRequest:async(t,r,s)=>{if(i.signal.aborted)throw new pa(Ws.ConnectionClosed,"Request was cancelled");const a={...s,relatedRequestId:e.id};n&&!a.relatedTask&&(a.relatedTask={taskId:n});const o=a.relatedTask?.taskId??n;return o&&c&&await c.updateTaskStatus(o,"input_required"),await this.request(t,r,a)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:n,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,d)).then(async t=>{if(i.signal.aborted)return;const r={result:t,jsonrpc:"2.0",id:e.id};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"response",message:r,timestamp:Date.now()},s?.sessionId):await(s?.send(r))},async t=>{if(i.signal.aborted)return;const r={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Ws.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"error",message:r,timestamp:Date.now()},s?.sessionId):await(s?.send(r))}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,s=Number(t),n=this._progressHandlers.get(s);if(!n)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(e){return this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),void i(e)}n(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r)return this._requestResolvers.delete(t),void(Gs(e)?r(e):r(new pa(e.error.code,e.error.message,e.error.data)));const s=this._responseHandlers.get(t);if(void 0===s)return void this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let n=!1;if(Gs(e)&&e.result&&"object"==typeof e.result){const r=e.result;if(r.task&&"object"==typeof r.task){const e=r.task;"string"==typeof e.taskId&&(n=!0,this._taskProgressTokens.set(e.taskId,t))}}n||this._progressHandlers.delete(t),Gs(e)?s(e):s(pa.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await(this._transport?.close())}async*requestStream(e,t,r){const{task:s}=r??{};if(!s){try{const s=await this.request(e,t,r);yield{type:"result",result:s}}catch(e){yield{type:"error",error:e instanceof pa?e:new pa(Ws.InternalError,String(e))}}return}let n;try{const s=await this.request(e,$n,r);if(!s.task)throw new pa(Ws.InternalError,"Task creation did not return a task");for(n=s.task.taskId,yield{type:"taskCreated",task:s.task};;){const e=await this.getTask({taskId:n},r);if(yield{type:"taskStatus",task:e},ju(e.status)){if("completed"===e.status){const e=await this.getTaskResult({taskId:n},t,r);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new pa(Ws.InternalError,`Task ${n} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new pa(Ws.InternalError,`Task ${n} was cancelled`)});return}if("input_required"===e.status){const e=await this.getTaskResult({taskId:n},t,r);return void(yield{type:"result",result:e})}const s=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,s)),r?.signal?.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof pa?e:new pa(Ws.InternalError,String(e))}}}request(e,t,r){const{relatedRequestId:s,resumptionToken:n,onresumptiontoken:i,task:a,relatedTask:o}=r??{};return new Promise((c,d)=>{const u=e=>{d(e)};if(!this._transport)return void u(new Error("Not connected"));if(!0===this._options?.enforceStrictCapabilities)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(e){return void u(e)}r?.signal?.throwIfAborted();const l=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:l};r?.onprogress&&(this._progressHandlers.set(l,r.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:l}}),a&&(h.params={...h.params,task:a}),o&&(h.params={...h.params,_meta:{...h.params?._meta||{},[xs]:o}});const p=e=>{this._responseHandlers.delete(l),this._progressHandlers.delete(l),this._cleanupTimeout(l),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:l,reason:String(e)}},{relatedRequestId:s,resumptionToken:n,onresumptiontoken:i}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)));const t=e instanceof pa?e:new pa(Ws.RequestTimeout,String(e));d(t)};this._responseHandlers.set(l,e=>{if(!r?.signal?.aborted){if(e instanceof Error)return d(e);try{const r=Iu(t,e.result);r.success?c(r.data):d(r.error)}catch(e){d(e)}}}),r?.signal?.addEventListener("abort",()=>{p(r?.signal?.reason)});const m=r?.timeout??6e4;this._setupTimeout(l,m,r?.maxTotalTimeout,()=>p(pa.fromError(Ws.RequestTimeout,"Request timed out",{timeout:m})),r?.resetTimeoutOnProgress??!1);const f=o?.taskId;if(f){const e=e=>{const t=this._responseHandlers.get(l);t?t(e):this._onerror(new Error(`Response handler missing for side-channeled request ${l}`))};this._requestResolvers.set(l,e),this._enqueueTaskMessage(f,{type:"request",message:h,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(l),d(e)})}else this._transport.send(h,{relatedRequestId:s,resumptionToken:n,onresumptiontoken:i}).catch(e=>{this._cleanupTimeout(l),d(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Pn,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},On,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},An,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[xs]:t.relatedTask}}};return void await this._enqueueTaskMessage(r,{type:"notification",message:s,timestamp:Date.now()})}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let r={...e,jsonrpc:"2.0"};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[xs]:t.relatedTask}}}),this._transport?.send(r,t).catch(e=>this._onerror(e))})}let s={...e,jsonrpc:"2.0"};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[xs]:t.relatedTask}}}),await this._transport.send(s,t)}setRequestHandler(e,t){const r=bl(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,s)=>{const n=kl(e,r);return Promise.resolve(t(n,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){const r=bl(e);this._notificationHandlers.set(r,r=>{const s=kl(e,r);return Promise.resolve(t(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,s)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const t of r)if("request"===t.type&&Hs(t.message)){const r=t.message.id,s=this._requestResolvers.get(r);s?(s(new pa(Ws.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(r)):this._onerror(new Error(`Resolver missing for request ${r} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1e3;try{const t=await(this._taskStore?.getTask(e));t?.pollInterval&&(r=t.pollInterval)}catch{}return new Promise((e,s)=>{if(t.aborted)return void s(new pa(Ws.InvalidRequest,"Request cancelled"));const n=setTimeout(e,r);t.addEventListener("abort",()=>{clearTimeout(n),s(new pa(Ws.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await r.createTask(s,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{const s=await r.getTask(e,t);if(!s)throw new pa(Ws.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(e,s,n)=>{await r.storeTaskResult(e,s,n,t);const i=await r.getTask(e,t);if(i){const t=Tn.parse({method:"notifications/tasks/status",params:i});await this.notification(t),ju(i.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>r.getTaskResult(e,t),updateTaskStatus:async(e,s,n)=>{const i=await r.getTask(e,t);if(!i)throw new pa(Ws.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(ju(i.status))throw new pa(Ws.InvalidParams,`Cannot update task "${e}" from terminal status "${i.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(e,s,n,t);const a=await r.getTask(e,t);if(a){const t=Tn.parse({method:"notifications/tasks/status",params:a});await this.notification(t),ju(a.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>r.listTasks(e,t)}}}function $l(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}var El=r(647),Tl=r(5143);class xl{constructor(e){this._ajv=e??function(){const e=new El({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Tl(e),e}()}getValidator(e){const t="$id"in e&&"string"==typeof e.$id?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}class Pl{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){const r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],s=r.some(e=>"tool_result"===e.type),n=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=n?Array.isArray(n.content)?n.content:[n.content]:[],a=i.some(e=>"tool_use"===e.type);if(s){if(r.some(e=>"tool_result"!==e.type))throw new Error("The last message must contain only tool_result content if any is present");if(!a)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){const e=new Set(i.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Li,t)}elicitInputStream(e,t){const r=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break;case"form":if(!r?.elicitation?.form)throw new Error("Client does not support form elicitation.")}const n="form"===s&&void 0===e.mode?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:n},sa,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class Il extends Sl{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(xi.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{const r=this._loggingLevels.get(t);return!!r&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r)},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new xl,this.setRequestHandler(ln,e=>this._oninitialize(e)),this.setNotificationHandler(mn,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ii,async(e,t)=>{const r=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=e.params,n=xi.safeParse(s);return n.success&&this._loggingLevels.set(r,n.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Pl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){const r={...e};for(const e in t){const s=e,n=t[s];if(void 0===n)continue;const i=r[s];$l(i)&&$l(n)?r[s]={...i,...n}:r[s]=n}return r}(this._capabilities,e)}setRequestHandler(e,t){const r=Ou(e),s=r?.method;if(!s)throw new Error("Schema is missing a method literal");let n;if(xu(s)){const e=s,t=e._zod?.def;n=t?.value??e.value}else{const e=s,t=e._def;n=t?.value??e.value}if("string"!=typeof n)throw new Error("Schema method literal must be a string");if("tools/call"===n){const r=async(e,r)=>{const s=Iu(Ei,e);if(!s.success){const e=s.error instanceof Error?s.error.message:String(s.error);throw new pa(Ws.InvalidParams,`Invalid tools/call request: ${e}`)}const{params:n}=s.data,i=await Promise.resolve(t(e,r));if(n.task){const e=Iu($n,i);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new pa(Ws.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const a=Iu(Si,i);if(!a.success){const e=a.error instanceof Error?a.error.message:String(a.error);throw new pa(Ws.InvalidParams,`Invalid tools/call result: ${e}`)}return a.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){!function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`)}}(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`)}(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Ts.includes(t)?t:Es,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Qs)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],s=r.some(e=>"tool_result"===e.type),n=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=n?Array.isArray(n.content)?n.content:[n.content]:[],a=i.some(e=>"tool_use"===e.type);if(s){if(r.some(e=>"tool_result"!==e.type))throw new Error("The last message must contain only tool_result content if any is present");if(!a)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){const e=new Set(i.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Zi,t):this.request({method:"sampling/createMessage",params:e},Li,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const r=e;return this.request({method:"elicitation/create",params:r},sa,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const r="form"===e.mode?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:r},sa,t);if("accept"===s.action&&s.content&&r.requestedSchema)try{const e=this._jsonSchemaValidator.getValidator(r.requestedSchema)(s.content);if(!e.valid)throw new pa(Ws.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof pa)throw e;throw new pa(Ws.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return s}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},la,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const Rl=Symbol.for("mcp.completable");function Ol(e){return!!e&&"object"==typeof e&&Rl in e}var Cl;!function(e){e.Completable="McpCompletable"}(Cl||(Cl={}));const Al=1e6,Nl=1e6;class jl{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,r){if(e.length>t)throw new Error(`${r} exceeds maximum length of ${t} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>"string"==typeof e?[]:e.names)}constructor(e){jl.validateLength(e,Al,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){const t=[];let r="",s=0,n=0;for(;s<e.length;)if("{"===e[s]){r&&(t.push(r),r="");const i=e.indexOf("}",s);if(-1===i)throw new Error("Unclosed template expression");if(n++,n>1e4)throw new Error("Template contains too many expressions (max 10000)");const a=e.slice(s+1,i),o=this.getOperator(a),c=a.includes("*"),d=this.getNames(a),u=d[0];for(const e of d)jl.validateLength(e,Nl,"Variable name");t.push({name:u,operator:o,names:d,exploded:c}),s=i+1}else r+=e[s],s++;return r&&t.push(r),t}getOperator(e){return["+","#",".","/","?","&"].find(t=>e.startsWith(t))||""}getNames(e){const t=this.getOperator(e);return e.slice(t.length).split(",").map(e=>e.replace("*","").trim()).filter(e=>e.length>0)}encodeValue(e,t){return jl.validateLength(e,Nl,"Variable value"),"+"===t||"#"===t?encodeURI(e):encodeURIComponent(e)}expandPart(e,t){if("?"===e.operator||"&"===e.operator){const r=e.names.map(r=>{const s=t[r];if(void 0===s)return"";const n=Array.isArray(s)?s.map(t=>this.encodeValue(t,e.operator)).join(","):this.encodeValue(s.toString(),e.operator);return`${r}=${n}`}).filter(e=>e.length>0);return 0===r.length?"":("?"===e.operator?"?":"&")+r.join("&")}if(e.names.length>1){const r=e.names.map(e=>t[e]).filter(e=>void 0!==e);return 0===r.length?"":r.map(e=>Array.isArray(e)?e[0]:e).join(",")}const r=t[e.name];if(void 0===r)return"";const s=(Array.isArray(r)?r:[r]).map(t=>this.encodeValue(t,e.operator));switch(e.operator){case"":case"+":default:return s.join(",");case"#":return"#"+s.join(",");case".":return"."+s.join(".");case"/":return"/"+s.join("/")}}expand(e){let t="",r=!1;for(const s of this.parts){if("string"==typeof s){t+=s;continue}const n=this.expandPart(s,e);n&&("?"!==s.operator&&"&"!==s.operator||!r?t+=n:t+=n.replace("?","&"),"?"!==s.operator&&"&"!==s.operator||(r=!0))}return t}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){const t=[];for(const t of e.names)jl.validateLength(t,Nl,"Variable name");if("?"===e.operator||"&"===e.operator){for(let r=0;r<e.names.length;r++){const s=e.names[r],n=0===r?"\\"+e.operator:"&";t.push({pattern:n+this.escapeRegExp(s)+"=([^&]+)",name:s})}return t}let r;const s=e.name;switch(e.operator){case"":r=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":r="(.+)";break;case".":r="\\.([^/,]+)";break;case"/":r="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:r="([^/]+)"}return t.push({pattern:r,name:s}),t}match(e){jl.validateLength(e,Al,"URI");let t="^";const r=[];for(const e of this.parts)if("string"==typeof e)t+=this.escapeRegExp(e);else{const s=this.partToRegExp(e);for(const{pattern:n,name:i}of s)t+=n,r.push({name:i,exploded:e.exploded})}t+="$",jl.validateLength(t,1e6,"Generated regex pattern");const s=new RegExp(t),n=e.match(s);if(!n)return null;const i={};for(let e=0;e<r.length;e++){const{name:t,exploded:s}=r[e],a=n[e+1],o=t.replace("*","");s&&a.includes(",")?i[o]=a.split(","):i[o]=a}return i}}const zl=/^[A-Za-z0-9._-]{1,128}$/;function Ml(e){const t=function(e){const t=[];if(0===e.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!zl.test(e)){const r=e.split("").filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,r)=>r.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${r.map(e=>`"${e}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}(e);return function(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const e of t)console.warn(` - ${e}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}(e,t.warnings),t.isValid}class ql{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){const s={taskSupport:"required",...t.execution};if("forbidden"===s.taskSupport)throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,s,t._meta,r)}}class Ul{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Il(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new ql(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Kl(bi)),this.server.assertCanSetRequestHandler(Kl(Ei)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(bi,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{const r={name:e,title:t.title,description:t.description,inputSchema:(()=>{const e=Cu(t.inputSchema);return e?wl(e,{strictUnions:!0,pipeStrategy:"input"}):Ll})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){const e=Cu(t.outputSchema);e&&(r.outputSchema=wl(e,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Ei,async(e,t)=>{try{const r=this._registeredTools[e.params.name];if(!r)throw new pa(Ws.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new pa(Ws.InvalidParams,`Tool ${e.params.name} disabled`);const s=!!e.params.task,n=r.execution?.taskSupport,i="createTask"in r.handler;if(("required"===n||"optional"===n)&&!i)throw new pa(Ws.InternalError,`Tool ${e.params.name} has taskSupport '${n}' but was not registered with registerToolTask`);if("required"===n&&!s)throw new pa(Ws.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===n&&!s&&i)return await this.handleAutomaticTaskPolling(r,e,t);const a=await this.validateToolInput(r,e.params.arguments,e.params.name),o=await this.executeToolHandler(r,a,t);return s||await this.validateToolOutput(r,o,e.params.name),o}catch(e){if(e instanceof pa&&e.code===Ws.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;const s=Cu(e.inputSchema)??e.inputSchema,n=await Ru(s,t);if(!n.success){const e=Au("error"in n?n.error:"Unknown error");throw new pa(Ws.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${e}`)}return n.data}async validateToolOutput(e,t,r){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new pa(Ws.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);const s=Cu(e.outputSchema),n=await Ru(s,t.structuredContent);if(!n.success){const e=Au("error"in n?n.error:"Unknown error");throw new pa(Ws.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${e}`)}}async executeToolHandler(e,t,r){const s=e.handler;if("createTask"in s){if(!r.taskStore)throw new Error("No task store provided.");const n={...r,taskStore:r.taskStore};if(e.inputSchema){const e=s;return await Promise.resolve(e.createTask(t,n))}{const e=s;return await Promise.resolve(e.createTask(n))}}if(e.inputSchema){const e=s;return await Promise.resolve(e(t,r))}{const e=s;return await Promise.resolve(e(r))}}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");const s=await this.validateToolInput(e,t.params.arguments,t.params.name),n=e.handler,i={...r,taskStore:r.taskStore},a=s?await Promise.resolve(n.createTask(s,i)):await Promise.resolve(n.createTask(i)),o=a.task.taskId;let c=a.task;const d=c.pollInterval??5e3;for(;"completed"!==c.status&&"failed"!==c.status&&"cancelled"!==c.status;){await new Promise(e=>setTimeout(e,d));const e=await r.taskStore.getTask(o);if(!e)throw new pa(Ws.InternalError,`Task ${o} not found during polling`);c=e}return await r.taskStore.getTaskResult(o)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Kl(oa)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(oa,async e=>{switch(e.params.ref.type){case"ref/prompt":return function(e){if("ref/prompt"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return function(e){if("ref/resource"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}(e),this.handleResourceCompletion(e,e.params.ref);default:throw new pa(Ws.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){const r=this._registeredPrompts[t.name];if(!r)throw new pa(Ws.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new pa(Ws.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return Wl;const s=Ou(r.argsSchema),n=s?.[e.params.argument.name];if(!Ol(n))return Wl;const i=function(e){const t=e[Rl];return t?.complete}(n);return i?Gl(await i(e.params.argument.value,e.params.context)):Wl}async handleResourceCompletion(e,t){const r=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return Wl;throw new pa(Ws.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const s=r.resourceTemplate.completeCallback(e.params.argument.name);return s?Gl(await s(e.params.argument.value,e.params.context)):Wl}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Kl(Zn)),this.server.assertCanSetRequestHandler(Kl(Hn)),this.server.assertCanSetRequestHandler(Kl(Wn)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Zn,async(e,t)=>{const r=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),s=[];for(const e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;const r=await e.resourceTemplate.listCallback(t);for(const t of r.resources)s.push({...e.metadata,...t})}return{resources:[...r,...s]}}),this.server.setRequestHandler(Hn,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(Wn,async(e,t)=>{const r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new pa(Ws.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,t)}for(const e of Object.values(this._registeredResourceTemplates)){const s=e.resourceTemplate.uriTemplate.match(r.toString());if(s)return e.readCallback(r,s,t)}throw new pa(Ws.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Kl(ii)),this.server.assertCanSetRequestHandler(Kl(ci)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ii,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Vl(t.argsSchema):void 0}))})),this.server.setRequestHandler(ci,async(e,t)=>{const r=this._registeredPrompts[e.params.name];if(!r)throw new pa(Ws.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new pa(Ws.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){const s=Cu(r.argsSchema),n=await Ru(s,e.params.arguments);if(!n.success){const t=Au("error"in n?n.error:"Unknown error");throw new pa(Ws.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}const i=n.data,a=r.callback;return await Promise.resolve(a(i,t))}{const e=r.callback;return await Promise.resolve(e(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...r){let s;"object"==typeof r[0]&&(s=r.shift());const n=r[0];if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const r=this._createRegisteredResource(e,void 0,t,s,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const r=this._createRegisteredResourceTemplate(e,void 0,t,s,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}}registerResource(e,t,r,s){if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const n=this._createRegisteredResource(e,r.title,t,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const n=this._createRegisteredResourceTemplate(e,r.title,t,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}_createRegisteredResource(e,t,r,s,n){const i={name:e,title:t,metadata:s,readCallback:n,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==r&&(delete this._registeredResources[r],e.uri&&(this._registeredResources[e.uri]=i)),void 0!==e.name&&(i.name=e.name),void 0!==e.title&&(i.title=e.title),void 0!==e.metadata&&(i.metadata=e.metadata),void 0!==e.callback&&(i.readCallback=e.callback),void 0!==e.enabled&&(i.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,t,r,s,n){const i={resourceTemplate:r,title:t,metadata:s,readCallback:n,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=i)),void 0!==t.title&&(i.title=t.title),void 0!==t.template&&(i.resourceTemplate=t.template),void 0!==t.metadata&&(i.metadata=t.metadata),void 0!==t.callback&&(i.readCallback=t.callback),void 0!==t.enabled&&(i.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;const a=r.uriTemplate.variableNames,o=Array.isArray(a)&&a.some(e=>!!r.completeCallback(e));return o&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,t,r,s,n){const i={title:t,description:r,argsSchema:void 0===s?void 0:Pu(s),callback:n,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=i)),void 0!==t.title&&(i.title=t.title),void 0!==t.description&&(i.description=t.description),void 0!==t.argsSchema&&(i.argsSchema=Pu(t.argsSchema)),void 0!==t.callback&&(i.callback=t.callback),void 0!==t.enabled&&(i.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,s&&Object.values(s).some(e=>Ol(e instanceof mu?e._def?.innerType:e))&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,t,r,s,n,i,a,o,c){Ml(e);const d={title:t,description:r,inputSchema:Hl(s),outputSchema:Hl(n),annotations:i,execution:a,_meta:o,handler:c,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&("string"==typeof t.name&&Ml(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=d)),void 0!==t.title&&(d.title=t.title),void 0!==t.description&&(d.description=t.description),void 0!==t.paramsSchema&&(d.inputSchema=Pu(t.paramsSchema)),void 0!==t.outputSchema&&(d.outputSchema=Pu(t.outputSchema)),void 0!==t.callback&&(d.handler=t.callback),void 0!==t.annotations&&(d.annotations=t.annotations),void 0!==t._meta&&(d._meta=t._meta),void 0!==t.enabled&&(d.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,s,n;if("string"==typeof t[0]&&(r=t.shift()),t.length>1){const e=t[0];Fl(e)?(s=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!Fl(t[0])&&(n=t.shift())):"object"==typeof e&&null!==e&&(n=t.shift())}const i=t[0];return this._createRegisteredTool(e,void 0,r,s,void 0,n,{taskSupport:"forbidden"},void 0,i)}registerTool(e,t,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:s,description:n,inputSchema:i,outputSchema:a,annotations:o,_meta:c}=t;return this._createRegisteredTool(e,s,n,i,a,o,{taskSupport:"forbidden"},c,r)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r,s;"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(s=t.shift());const n=t[0],i=this._createRegisteredPrompt(e,void 0,r,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:s,description:n,argsSchema:i}=t,a=this._createRegisteredPrompt(e,s,n,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class Dl{constructor(e,t){this._callbacks=t,this._uriTemplate="string"==typeof e?new jl(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}}const Ll={type:"object",properties:{}};function Zl(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function Fl(e){return"object"==typeof e&&null!==e&&!function(e){return"_def"in e||"_zod"in e||Zl(e)}(e)&&(0===Object.keys(e).length||Object.values(e).some(Zl))}function Hl(e){if(e)return Fl(e)?Pu(e):e}function Vl(e){const t=Ou(e);return t?Object.entries(t).map(([e,t])=>{const r=function(e){return e.description}(t),s=function(e){if(xu(e)){const t=e;return"optional"===t._zod?.def?.type}const t=e;return"function"==typeof e.isOptional?e.isOptional():"ZodOptional"===t._def?.typeName}(t);return{name:e,description:r,required:!s}}):[]}function Kl(e){const t=Ou(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const s=Nu(r);if("string"==typeof s)return s;throw new Error("Schema method literal must be a string")}function Gl(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Wl={completion:{values:[],hasMore:!1}};var Jl=window.elementorV2.editorV1Adapters,Bl=window.elementorV2.schema;const Ql="angie/modelPreferences",Yl="angie/requiredResources",Xl=new Proxy({},{get:()=>function(...e){}}),eh={},th={},rh=void 0!==globalThis.jest,sh=(e,t)=>{const r=ih(t);eh[r]=e};async function nh(e,t=Object.entries(eh),r=3){if(0===r)return void console.error("Failed to register MCP after 3 retries. failed entries: ",t);if(0===t.length)return;const s=[];for await(const r of t){const[t,n]=r;try{await e.registerLocalServer({title:ah(t),name:`editor-${t}`,server:n,version:"1.0.0",description:th[t]||t})}catch{s.push(r)}}return s.length>0?nh(e,s,r-1):void 0}const ih=e=>{if(!e||!/^[a-z_]+$/.test(e))throw new Error("Not alphabet");return e},ah=e=>`Editor ${e.charAt(0).toUpperCase()+e.slice(1)}`,oh=(e,t)=>{const r=`editor-${ih(e)}`,s=ah(e);if(void 0!==globalThis.jest)return{resource:async()=>{},sendResourceUpdated:()=>{},addTool:()=>{},setMCPDescription:()=>{},getActiveChatInfo(){return{sessionId:"mock-session-id",expiresAt:Date.now()+36e5}},mcpServer:Xl};eh[e]||(eh[e]=new Ul({name:r,title:s,version:"1.0.0"},{instructions:t?.instructions}));const n=eh[e],{addTool:i}=(a=n,{addTool:function(e){const t=e.outputSchema;t&&Object.assign(t,t.errors??{errors:Bl.z.string().optional().describe("Error message if the tool failed")});const r=e.schema?e.schema:{},s={destructiveHint:e.isDestructive,readOnlyHint:!e.isDestructive&&void 0,title:e.name},n={[Ql]:e.modelPreferences??{hints:[{name:"claude-sonnet-4-5"}],intelligencePriority:.8,speedPriority:.7},[Yl]:e.requiredResources??void 0};a.registerTool(e.name,{description:e.description,inputSchema:r,title:e.name,annotations:s,_meta:n},async function(t,r){try{const s=await e.handler(e.schema?t:{},r);return{content:[{type:"text",text:"string"==typeof s?s:JSON.stringify(s)}]}}catch(e){return{isError:!0,structuredContent:{errors:e.message||"Unknown error"},content:[{type:"text",text:e.message||"Unknown error"}]}}}),rh&&a.sendToolListChanged()}});var a;return{waitForReady:()=>Kc().waitForReady(),resource:async(...e)=>(await Kc().waitForReady(),n.registerResource(...e)),sendResourceUpdated:(...e)=>Kc().waitForReady().then(()=>n.server.sendResourceUpdated(...e)).catch(e=>{if(!e?.message?.includes("Not connected"))throw e}),mcpServer:n,addTool:i,setMCPDescription:t=>{th[e]=t},getActiveChatInfo:()=>{const e=localStorage.getItem("angie_active_chat_id");if(!e)return{expiresAt:0,sessionId:""};const t=JSON.parse(e);return{expiresAt:t.expiresAt,sessionId:t.sessionId}}}},ch=()=>!!xa();function dh(){return(0,Jl.isExperimentActive)("editor_mcp")&&ch()?Kc().waitForReady():Promise.resolve()}document.addEventListener("DOMContentLoaded",()=>{!function(){if((0,Jl.isExperimentActive)("editor_mcp")&&ch()){const e=Kc();e.waitForReady().then(()=>nh(e))}Promise.resolve()}()},{once:!0});const uh=()=>("undefined"==typeof window?null:localStorage.getItem("angie_sidebar_state"))===jc,lh={maxTokens:1e4,modelPreferences:"openai",model:"gpt-4o"},hh={type:"object",properties:{content:{type:"string",description:"Result"}},required:["content"],additionalProperties:!1},ph=(e,t=lh)=>{const{maxTokens:r=1e3,modelPreferences:s="openai",model:n="gpt-4o"}=t;return async t=>{const i={...t.systemPrompt?{systemPrompt:t.systemPrompt}:{}},a=t.requestParams||{};return(await e.sendRequest({method:"sampling/createMessage",params:{...a,maxTokens:r,modelPreferences:{hints:[{name:s}]},metadata:{model:n,...i,structured_output:t.structuredOutput||hh},messages:t.messages}},qi)).content}};class mh{_description="";_parameters={};_examples=[];_furtherInstructions=[];constructor(e){this.name=e}description(e){return void 0===e?this._description:(this._description=e,this)}parameter(e,t){return void 0===t?this._parameters[e]:(this._parameters[e]=`**${e}**:\n${t}`,this)}instruction(e){return this._furtherInstructions.push(e),this}example(e){return this._examples.push(e),this}get examples(){return this._examples.join("\n\n")}prompt(){return`# ${this.name}\n# Description\n${this._description}\n\n${this._parameters.length?"# Parameters":""}\n${Object.values(this._parameters).join("\n\n")}\n\n${this._examples.length?"# Examples":""}\n${this.examples}\n\n${this._furtherInstructions.length?"# Further Instructions":""}\n${this._furtherInstructions.join("\n\n")}\n`.trim()}}const fh=e=>new mh(e),gh=e=>{const t=xa();t&&(Ic(t,!0),e&&(window.location.hash=`angie-prompt=${encodeURIComponent(e)}`))},_h=e=>{Sc(window.location.href,e)&&(window.location.href="/wp-admin/plugin-install.php?s=angie&tab=search&type=term")},yh=e=>{Sc(window.location.href,e)&&(window.location.href="/wp-admin/admin.php?page=angie-app")};var vh=window.wp.apiFetch,wh=r.n(vh);const bh="angie",kh=e=>"object"==typeof e&&null!==e&&"code"in e&&"message"in e,Sh=async()=>{try{return await(async()=>{try{return await wh()({path:"/wp/v2/plugins",method:"POST",data:{slug:bh,status:"active"}})}catch(e){if(kh(e)&&"folder_exists"===e.code)return(async e=>wh()({path:`/wp/v2/plugins/${e}`,method:"POST",data:{status:"active"}}))(`${bh}/${bh}`);throw e}})(),{success:!0}}catch(e){return kh(e)?{success:!1,error:e.message,code:e.code}:{success:!1,error:"Unknown error occurred"}}},$h=()=>Kc();(window.elementorV2=window.elementorV2||{}).editorMcp=s}(),window.elementorV2.editorMcp?.init?.();