@barndoor-ai/sdk 0.4.3 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -10,4 +10,4 @@ import e from"os";import t,{dirname as r,join as o}from"path";import n from"fs/p
10
10
  || ${a} === "boolean" || ${n} === null`).assign(i,Vf._`[${n}]`)}}o.else(),Jf(e),o.endIf(),o.if(Vf._`${i} !== undefined`,()=>{o.assign(n,i),function({gen:e,parentData:t,parentDataProperty:r},o){e.if(Vf._`${t} !== undefined`,()=>e.assign(Vf._`${t}[${r}]`,o))}(e,i)})}(e,t,s):Jf(e)})}return a};const Kf=new Set(["string","number","integer","boolean","null"]);function Zf(e,t,r,o=Lf.Correct){const n=o===Lf.Correct?Vf.operators.EQ:Vf.operators.NEQ;let s;switch(e){case"null":return Vf._`${t} ${n} null`;case"array":s=Vf._`Array.isArray(${t})`;break;case"object":s=Vf._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=a(Vf._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=a();break;default:return Vf._`typeof ${t} ${n} ${e}`}return o===Lf.Correct?s:(0,Vf.not)(s);function a(e=Vf.nil){return(0,Vf.and)(Vf._`typeof ${t} == "number"`,e,r?Vf._`isFinite(${t})`:Vf.nil)}}function Gf(e,t,r,o){if(1===e.length)return Zf(e[0],t,r,o);let n;const s=(0,Ff.toHash)(e);if(s.array&&s.object){const e=Vf._`typeof ${t} != "object"`;n=s.null?e:Vf._`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else n=Vf.nil;s.number&&delete s.integer;for(const e in s)n=(0,Vf.and)(n,Zf(e,t,r,o));return n}jf.checkDataType=Zf,jf.checkDataTypes=Gf;const Bf={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?Vf._`{type: ${e}}`:Vf._`{type: ${t}}`};function Jf(e){const t=function(e){const{gen:t,data:r,schema:o}=e,n=(0,Ff.schemaRefOrVal)(e,o,"type");return{gen:t,keyword:"type",data:r,schema:o.type,schemaCode:n,schemaValue:n,parentSchema:o,params:{},it:e}}(e);(0,qf.reportError)(t,Bf)}jf.reportTypeError=Jf;var Wf,Qf={};var Yf,Xf,em={},tm={};function rm(){if(Yf)return tm;Yf=1,Object.defineProperty(tm,"__esModule",{value:!0}),tm.validateUnion=tm.validateArray=tm.usePattern=tm.callValidateCode=tm.schemaProperties=tm.allSchemaProperties=tm.noPropertyInData=tm.propertyInData=tm.isOwnProperty=tm.hasPropFunc=tm.reportMissingProp=tm.checkMissingProp=tm.checkReportMissingProp=void 0;const e=lf,t=pf,r=Nf(),o=pf;function n(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function s(t,r,o){return e._`${n(t)}.call(${r}, ${o})`}function a(t,r,o,n){const a=e._`${r}${(0,e.getProperty)(o)} === undefined`;return n?(0,e.or)(a,(0,e.not)(s(t,r,o))):a}function i(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}tm.checkReportMissingProp=function(t,r){const{gen:o,data:n,it:s}=t;o.if(a(o,n,r,s.opts.ownProperties),()=>{t.setParams({missingProperty:e._`${r}`},!0),t.error()})},tm.checkMissingProp=function({gen:t,data:r,it:{opts:o}},n,s){return(0,e.or)(...n.map(n=>(0,e.and)(a(t,r,n,o.ownProperties),e._`${s} = ${n}`)))},tm.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},tm.hasPropFunc=n,tm.isOwnProperty=s,tm.propertyInData=function(t,r,o,n){const a=e._`${r}${(0,e.getProperty)(o)} !== undefined`;return n?e._`${a} && ${s(t,r,o)}`:a},tm.noPropertyInData=a,tm.allSchemaProperties=i,tm.schemaProperties=function(e,r){return i(r).filter(o=>!(0,t.alwaysValidSchema)(e,r[o]))},tm.callValidateCode=function({schemaCode:t,data:o,it:{gen:n,topSchemaRef:s,schemaPath:a,errorPath:i},it:c},u,l,d){const h=d?e._`${t}, ${o}, ${s}${a}`:o,p=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,i)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const f=e._`${h}, ${n.object(...p)}`;return l!==e.nil?e._`${u}.call(${l}, ${f})`:e._`${u}(${f})`};const c=e._`new RegExp`;return tm.usePattern=function({gen:t,it:{opts:r}},n){const s=r.unicodeRegExp?"u":"",{regExp:a}=r.code,i=a(n,s);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:e._`${"new RegExp"===a.code?c:(0,o.useFunc)(t,a)}(${n}, ${s})`})},tm.validateArray=function(r){const{gen:o,data:n,keyword:s,it:a}=r,i=o.name("valid");if(a.allErrors){const e=o.let("valid",!0);return c(()=>o.assign(e,!1)),e}return o.var(i,!0),c(()=>o.break()),i;function c(a){const c=o.const("len",e._`${n}.length`);o.forRange("i",0,c,n=>{r.subschema({keyword:s,dataProp:n,dataPropType:t.Type.Num},i),o.if((0,e.not)(i),a)})}},tm.validateUnion=function(r){const{gen:o,schema:n,keyword:s,it:a}=r;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(e=>(0,t.alwaysValidSchema)(a,e))&&!a.opts.unevaluated)return;const i=o.let("valid",!1),c=o.name("_valid");o.block(()=>n.forEach((t,n)=>{const a=r.subschema({keyword:s,schemaProp:n,compositeRule:!0},c);o.assign(i,e._`${i} || ${c}`);r.mergeValidEvaluated(a,c)||o.if((0,e.not)(i))})),r.result(i,()=>r.reset(),()=>r.error(!0))},tm}function om(){if(Xf)return em;Xf=1,Object.defineProperty(em,"__esModule",{value:!0}),em.validateKeywordUsage=em.validSchemaType=em.funcKeywordCode=em.macroKeywordCode=void 0;const e=lf,t=Nf(),r=rm(),o=Cf();function n(t){const{gen:r,data:o,it:n}=t;r.if(n.parentData,()=>r.assign(o,e._`${n.parentData}[${n.parentDataProperty}]`))}function s(t,r,o){if(void 0===o)throw new Error(`keyword "${r}" failed to compile`);return t.scopeValue("keyword","function"==typeof o?{ref:o}:{ref:o,code:(0,e.stringify)(o)})}return em.macroKeywordCode=function(t,r){const{gen:o,keyword:n,schema:a,parentSchema:i,it:c}=t,u=r.macro.call(c.self,a,i,c),l=s(o,n,u);!1!==c.opts.validateSchema&&c.self.validateSchema(u,!0);const d=o.name("valid");t.subschema({schema:u,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},d),t.pass(d,()=>t.error(!0))},em.funcKeywordCode=function(a,i){var c;const{gen:u,keyword:l,schema:d,parentSchema:h,$data:p,it:f}=a;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(f,i);const m=!p&&i.compile?i.compile.call(f.self,d,h,f):i.validate,y=s(u,l,m),g=u.let("valid");function v(o=(i.async?e._`await `:e.nil)){const n=f.opts.passContext?t.default.this:t.default.self,s=!("compile"in i&&!p||!1===i.schema);u.assign(g,e._`${o}${(0,r.callValidateCode)(a,y,n,s)}`,i.modifying)}function _(t){var r;u.if((0,e.not)(null!==(r=i.valid)&&void 0!==r?r:g),t)}a.block$data(g,function(){if(!1===i.errors)v(),i.modifying&&n(a),_(()=>a.error());else{const r=i.async?function(){const t=u.let("ruleErrs",null);return u.try(()=>v(e._`await `),r=>u.assign(g,!1).if(e._`${r} instanceof ${f.ValidationError}`,()=>u.assign(t,e._`${r}.errors`),()=>u.throw(r))),t}():function(){const t=e._`${y}.errors`;return u.assign(t,null),v(e.nil),t}();i.modifying&&n(a),_(()=>function(r,n){const{gen:s}=r;s.if(e._`Array.isArray(${n})`,()=>{s.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${n} : ${t.default.vErrors}.concat(${n})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,o.extendErrors)(r)},()=>r.error())}(a,r))}}),a.ok(null!==(c=i.valid)&&void 0!==c?c:g)},em.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)},em.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:o},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)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 ${s}: ${a.join(",")}`);if(n.validateSchema){if(!n.validateSchema(e[s])){const e=`keyword "${s}" value is invalid at path "${o}": `+r.errorsText(n.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);r.logger.error(e)}}},em}var nm,sm={};var am={},im={exports:{}},cm=im.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),um(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function um(e,t,r,o,n,s,a,i,c,u){if(o&&"object"==typeof o&&!Array.isArray(o)){for(var l in t(o,n,s,a,i,c,u),o){var d=o[l];if(Array.isArray(d)){if(l in cm.arrayKeywords)for(var h=0;h<d.length;h++)um(e,t,r,d[h],n+"/"+l+"/"+h,s,n,l,o,h)}else if(l in cm.propsKeywords){if(d&&"object"==typeof d)for(var p in d)um(e,t,r,d[p],n+"/"+l+"/"+lm(p),s,n,l,o,p)}else(l in cm.keywords||e.allKeys&&!(l in cm.skipKeywords))&&um(e,t,r,d,n+"/"+l,s,n,l,o)}r(o,n,s,a,i,c,u)}}function lm(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}cm.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},cm.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},cm.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},cm.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};var dm=im.exports;Object.defineProperty(am,"__esModule",{value:!0}),am.getSchemaRefs=am.resolveUrl=am.normalizeId=am._getFullPath=am.getFullPath=am.inlineRef=void 0;const hm=pf,pm=nu,fm=dm,mm=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);am.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!gm(e):!!t&&vm(e)<=t)};const ym=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function gm(e){for(const t in e){if(ym.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(gm))return!0;if("object"==typeof r&&gm(r))return!0}return!1}function vm(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!mm.has(r)&&("object"==typeof e[r]&&(0,hm.eachItem)(e[r],e=>t+=vm(e)),t===1/0))return 1/0}return t}function _m(e,t="",r){!1!==r&&(t=bm(t));const o=e.parse(t);return wm(e,o)}function wm(e,t){return e.serialize(t).split("#")[0]+"#"}am.getFullPath=_m,am._getFullPath=wm;const $m=/#\/?$/;function bm(e){return e?e.replace($m,""):""}am.normalizeId=bm,am.resolveUrl=function(e,t,r){return r=bm(r),e.resolve(t,r)};const km=/^[a-z_][-a-z0-9._]*$/i;var Em;function Sm(){if(Em)return af;Em=1,Object.defineProperty(af,"__esModule",{value:!0}),af.getData=af.KeywordCxt=af.validateFunctionCode=void 0;const e=function(){if(If)return cf;If=1,Object.defineProperty(cf,"__esModule",{value:!0}),cf.boolOrEmptySchema=cf.topBoolOrEmptySchema=void 0;const e=Cf(),t=lf,r=Nf(),o={message:"boolean schema is false"};function n(t,r){const{gen:n,data:s}=t,a={gen:n,keyword:"false schema",data:s,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,e.reportError)(a,o,void 0,r)}return cf.topBoolOrEmptySchema=function(e){const{gen:o,schema:s,validateName:a}=e;!1===s?n(e,!1):"object"==typeof s&&!0===s.$async?o.return(r.default.data):(o.assign(t._`${a}.errors`,null),o.return(!0))},cf.boolOrEmptySchema=function(e,t){const{gen:r,schema:o}=e;!1===o?(r.var(t,!1),n(e)):r.var(t,!0)},cf}(),t=jf,r=Mf(),o=jf,n=function(){if(Wf)return Qf;Wf=1,Object.defineProperty(Qf,"__esModule",{value:!0}),Qf.assignDefaults=void 0;const e=lf,t=pf;function r(r,o,n){const{gen:s,compositeRule:a,data:i,opts:c}=r;if(void 0===n)return;const u=e._`${i}${(0,e.getProperty)(o)}`;if(a)return void(0,t.checkStrictMode)(r,`default is ignored for: ${u}`);let l=e._`${u} === undefined`;"empty"===c.useDefaults&&(l=e._`${l} || ${u} === null || ${u} === ""`),s.if(l,e._`${u} = ${(0,e.stringify)(n)}`)}return Qf.assignDefaults=function(e,t){const{properties:o,items:n}=e.schema;if("object"===t&&o)for(const t in o)r(e,t,o[t].default);else"array"===t&&Array.isArray(n)&&n.forEach((t,o)=>r(e,o,t.default))},Qf}(),s=om(),a=function(){if(nm)return sm;nm=1,Object.defineProperty(sm,"__esModule",{value:!0}),sm.extendSubschemaMode=sm.extendSubschemaData=sm.getSubschema=void 0;const e=lf,t=pf;return sm.getSubschema=function(r,{keyword:o,schemaProp:n,schema:s,schemaPath:a,errSchemaPath:i,topSchemaRef:c}){if(void 0!==o&&void 0!==s)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==o){const s=r.schema[o];return void 0===n?{schema:s,schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(o)}`,errSchemaPath:`${r.errSchemaPath}/${o}`}:{schema:s[n],schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(o)}${(0,e.getProperty)(n)}`,errSchemaPath:`${r.errSchemaPath}/${o}/${(0,t.escapeFragment)(n)}`}}if(void 0!==s){if(void 0===a||void 0===i||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:s,schemaPath:a,topSchemaRef:c,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')},sm.extendSubschemaData=function(r,o,{dataProp:n,dataPropType:s,data:a,dataTypes:i,propertyName:c}){if(void 0!==a&&void 0!==n)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:u}=o;if(void 0!==n){const{errorPath:a,dataPathArr:i,opts:c}=o;l(u.let("data",e._`${o.data}${(0,e.getProperty)(n)}`,!0)),r.errorPath=e.str`${a}${(0,t.getErrorPath)(n,s,c.jsPropertySyntax)}`,r.parentDataProperty=e._`${n}`,r.dataPathArr=[...i,r.parentDataProperty]}function l(e){r.data=e,r.dataLevel=o.dataLevel+1,r.dataTypes=[],o.definedProperties=new Set,r.parentData=o.data,r.dataNames=[...o.dataNames,e]}void 0!==a&&(l(a instanceof e.Name?a:u.let("data",a,!0)),void 0!==c&&(r.propertyName=c)),i&&(r.dataTypes=i)},sm.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:o,createErrors:n,allErrors:s}){void 0!==o&&(e.compositeRule=o),void 0!==n&&(e.createErrors=n),void 0!==s&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r},sm}(),i=lf,c=Nf(),u=am,l=pf,d=Cf();function h({gen:e,validateName:t,schema:r,schemaEnv:o,opts:n},s){n.code.es5?e.func(t,i._`${c.default.data}, ${c.default.valCxt}`,o.$async,()=>{e.code(i._`"use strict"; ${p(r,n)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,i._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,i._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,i._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,i._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,i._`""`),e.var(c.default.parentData,i._`undefined`),e.var(c.default.parentDataProperty,i._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`{}`)})}(e,n),e.code(s)}):e.func(t,i._`${c.default.data}, ${function(e){return i._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?i._`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}(n)}`,o.$async,()=>e.code(p(r,n)).code(s))}function p(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?i._`/*# sourceURL=${r} */`:i.nil}function f(t,r){y(t)&&(g(t),m(t))?function(e,t){const{schema:r,gen:o,opts:n}=e;n.$comment&&r.$comment&&_(e);(function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.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 s=o.const("_errs",c.default.errors);v(e,s),o.var(t,i._`${s} === ${c.default.errors}`)}(t,r):(0,e.boolOrEmptySchema)(t,r)}function m({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 g(e){(0,l.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:o,self:n}=e;t.$ref&&o.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(t,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function v(e,r){if(e.opts.jtd)return w(e,[],!1,r);const o=(0,t.getSchemaTypes)(e.schema);w(e,o,!(0,t.coerceAndCheckDataType)(e,o),r)}function _({gen:e,schemaEnv:t,schema:r,errSchemaPath:o,opts:n}){const s=r.$comment;if(!0===n.$comment)e.code(i._`${c.default.self}.logger.log(${s})`);else if("function"==typeof n.$comment){const r=i.str`${o}/$comment`,n=e.scopeValue("root",{ref:t.root});e.code(i._`${c.default.self}.opts.$comment(${s}, ${r}, ${n}.schema)`)}}function w(e,t,n,s){const{gen:a,schema:u,data:d,allErrors:h,opts:p,self:f}=e,{RULES:m}=f;function y(l){(0,r.shouldUseGroup)(u,l)&&(l.type?(a.if((0,o.checkDataType)(l.type,d,p.strictNumbers)),$(e,l),1===t.length&&t[0]===l.type&&n&&(a.else(),(0,o.reportTypeError)(e)),a.endIf()):$(e,l),h||a.if(i._`${c.default.errors} === ${s||0}`))}!u.$ref||!p.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(u,m)?(p.jtd||function(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;(function(e,t){if(!t.length)return;if(!e.dataTypes.length)return void(e.dataTypes=t);t.forEach(t=>{k(e.dataTypes,t)||E(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const r=[];for(const o of e.dataTypes)k(t,o)?r.push(o):t.includes("integer")&&"number"===o&&r.push("integer");e.dataTypes=r}(e,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 o=e.self.RULES.all;for(const n in o){const s=o[n];if("object"==typeof s&&(0,r.shouldUseRule)(e.schema,s)){const{type:r}=s.definition;r.length&&!r.some(e=>b(t,e))&&E(e,`missing type "${r.join(",")}" for keyword "${n}"`)}}}(e,e.dataTypes)}(e,t),a.block(()=>{for(const e of m.rules)y(e);y(m.post)})):a.block(()=>P(e,"$ref",m.all.$ref.definition))}function $(e,t){const{gen:o,schema:s,opts:{useDefaults:a}}=e;a&&(0,n.assignDefaults)(e,t.type),o.block(()=>{for(const o of t.rules)(0,r.shouldUseRule)(s,o)&&P(e,o.keyword,o.definition,t.type)})}function b(e,t){return e.includes(t)||"number"===t&&e.includes("integer")}function k(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function E(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,l.checkStrictMode)(e,t,e.opts.strictTypes)}af.validateFunctionCode=function(t){y(t)&&(g(t),m(t))?function(e){const{schema:t,opts:r,gen:o}=e;h(e,()=>{r.$comment&&t.$comment&&_(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,l.checkStrictMode)(e,"default is ignored in the schema root")}(e),o.let(c.default.vErrors,null),o.let(c.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",i._`${r}.evaluated`),t.if(i._`${e.evaluated}.dynamicProps`,()=>t.assign(i._`${e.evaluated}.props`,i._`undefined`)),t.if(i._`${e.evaluated}.dynamicItems`,()=>t.assign(i._`${e.evaluated}.items`,i._`undefined`))}(e),v(e),function(e){const{gen:t,schemaEnv:r,validateName:o,ValidationError:n,opts:s}=e;r.$async?t.if(i._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(i._`new ${n}(${c.default.vErrors})`)):(t.assign(i._`${o}.errors`,c.default.vErrors),s.unevaluated&&function({gen:e,evaluated:t,props:r,items:o}){r instanceof i.Name&&e.assign(i._`${t}.props`,r);o instanceof i.Name&&e.assign(i._`${t}.items`,o)}(e),t.return(i._`${c.default.errors} === 0`))}(e)})}(t):h(t,()=>(0,e.topBoolOrEmptySchema)(t))};class S{constructor(e,t,r){if((0,s.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,l.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",x(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,s.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",c.default.errors))}result(e,t,r){this.failResult((0,i.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,i.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(i._`${t} !== undefined && (${(0,i.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?d.reportExtraError:d.reportError)(this,this.def.error,t)}$dataError(){(0,d.reportError)(this,this.def.$dataError||d.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,d.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=i.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=i.nil,t=i.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:n,def:s}=this;r.if((0,i.or)(i._`${o} === undefined`,t)),e!==i.nil&&r.assign(e,!0),(n.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==i.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:n,it:s}=this;return(0,i.or)(function(){if(r.length){if(!(t instanceof i.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return i._`${(0,o.checkDataTypes)(e,t,s.opts.strictNumbers,o.DataType.Wrong)}`}return i.nil}(),function(){if(n.validateSchema){const r=e.scopeValue("validate$data",{ref:n.validateSchema});return i._`!${r}(${t})`}return i.nil}())}subschema(e,t){const r=(0,a.getSubschema)(this.it,e);(0,a.extendSubschemaData)(r,this.it,e),(0,a.extendSubschemaMode)(r,e);const o={...this.it,...r,items:void 0,props:void 0};return f(o,t),o}mergeEvaluated(e,t){const{it:r,gen:o}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=l.mergeEvaluated.props(o,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=l.mergeEvaluated.items(o,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return o.if(t,()=>this.mergeEvaluated(e,i.Name)),!0}}function P(e,t,r,o){const n=new S(e,r,t);"code"in r?r.code(n,o):n.$data&&r.validate?(0,s.funcKeywordCode)(n,r):"macro"in r?(0,s.macroKeywordCode)(n,r):(r.compile||r.validate)&&(0,s.funcKeywordCode)(n,r)}af.KeywordCxt=S;const T=/^\/(?:[^~]|~0|~1)*$/,I=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function x(e,{dataLevel:t,dataNames:r,dataPathArr:o}){let n,s;if(""===e)return c.default.rootData;if("/"===e[0]){if(!T.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);n=e,s=c.default.rootData}else{const a=I.exec(e);if(!a)throw new Error(`Invalid JSON-pointer: ${e}`);const i=+a[1];if(n=a[2],"#"===n){if(i>=t)throw new Error(d("property/index",i));return o[t-i]}if(i>t)throw new Error(d("data",i));if(s=r[t-i],!n)return s}let a=s;const u=n.split("/");for(const e of u)e&&(s=i._`${s}${(0,i.getProperty)((0,l.unescapeJsonPointer)(e))}`,a=i._`${a} && ${s}`);return a;function d(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}return af.getData=x,af}am.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:o}=this.opts,n=bm(e[r]||t),s={"":n},a=_m(o,n,!1),i={},c=new Set;return fm(e,{allKeys:!0},(e,t,o,n)=>{if(void 0===n)return;const d=a+t;let h=s[n];function p(t){const r=this.opts.uriResolver.resolve;if(t=bm(h?r(h,t):t),c.has(t))throw l(t);c.add(t);let o=this.refs[t];return"string"==typeof o&&(o=this.refs[o]),"object"==typeof o?u(e,o.schema,t):t!==bm(d)&&("#"===t[0]?(u(e,i[t],t),i[t]=e):this.refs[t]=d),t}function f(e){if("string"==typeof e){if(!km.test(e))throw new Error(`invalid anchor "${e}"`);p.call(this,`#${e}`)}}"string"==typeof e[r]&&(h=p.call(this,e[r])),f.call(this,e.$anchor),f.call(this,e.$dynamicAnchor),s[t]=h}),i;function u(e,t,r){if(void 0!==t&&!pm(e,t))throw l(r)}function l(e){return new Error(`reference "${e}" resolves to more than one schema`)}};var Pm,Tm={};function Im(){if(Pm)return Tm;Pm=1,Object.defineProperty(Tm,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return Tm.default=e,Tm}var xm,Nm={};function Cm(){if(xm)return Nm;xm=1,Object.defineProperty(Nm,"__esModule",{value:!0});const e=am;class t extends Error{constructor(t,r,o,n){super(n||`can't resolve reference ${o} from id ${r}`),this.missingRef=(0,e.resolveUrl)(t,r,o),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(t,this.missingRef))}}return Nm.default=t,Nm}var jm={};Object.defineProperty(jm,"__esModule",{value:!0}),jm.resolveSchema=jm.getCompilingSchema=jm.resolveRef=jm.compileSchema=jm.SchemaEnv=void 0;const Rm=lf,Om=Im(),zm=Nf(),Am=am,Mm=pf,Dm=Sm();class Um{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,Am.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 qm(e){const t=Fm.call(this,e);if(t)return t;const r=(0,Am.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:o,lines:n}=this.opts.code,{ownProperties:s}=this.opts,a=new Rm.CodeGen(this.scope,{es5:o,lines:n,ownProperties:s});let i;e.$async&&(i=a.scopeValue("Error",{ref:Om.default,code:Rm._`require("ajv/dist/runtime/validation_error").default`}));const c=a.scopeName("validate");e.validateName=c;const u={gen:a,allErrors:this.opts.allErrors,data:zm.default.data,parentData:zm.default.parentData,parentDataProperty:zm.default.parentDataProperty,dataNames:[zm.default.data],dataPathArr:[Rm.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,Rm.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:i,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Rm.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:Rm._`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,Dm.validateFunctionCode)(u),a.optimize(this.opts.code.optimize);const t=a.toString();l=`${a.scopeRefs(zm.default.scope)}return ${t}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const r=new Function(`${zm.default.self}`,`${zm.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{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:c,validateCode:t,scopeValues:a._values}),this.opts.unevaluated){const{props:e,items:t}=u;r.evaluated={props:e instanceof Rm.Name?void 0:e,items:t instanceof Rm.Name?void 0:t,dynamicProps:e instanceof Rm.Name,dynamicItems:t instanceof Rm.Name},r.source&&(r.source.evaluated=(0,Rm.stringify)(r.evaluated))}return e.validate=r,e}catch(t){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),t}finally{this._compilations.delete(e)}}function Vm(e){return(0,Am.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:qm.call(this,e)}function Fm(e){for(const t of this._compilations)if(Lm(t,e))return t}function Lm(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Hm(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||Km.call(this,e,t)}function Km(e,t){const r=this.opts.uriResolver.parse(t),o=(0,Am._getFullPath)(this.opts.uriResolver,r);let n=(0,Am.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&o===n)return Gm.call(this,r,e);const s=(0,Am.normalizeId)(o),a=this.refs[s]||this.schemas[s];if("string"==typeof a){const t=Km.call(this,e,a);if("object"!=typeof(null==t?void 0:t.schema))return;return Gm.call(this,r,t)}if("object"==typeof(null==a?void 0:a.schema)){if(a.validate||qm.call(this,a),s===(0,Am.normalizeId)(t)){const{schema:t}=a,{schemaId:r}=this.opts,o=t[r];return o&&(n=(0,Am.resolveUrl)(this.opts.uriResolver,n,o)),new Um({schema:t,schemaId:r,root:e,baseId:n})}return Gm.call(this,r,a)}}jm.SchemaEnv=Um,jm.compileSchema=qm,jm.resolveRef=function(e,t,r){var o;r=(0,Am.resolveUrl)(this.opts.uriResolver,t,r);const n=e.refs[r];if(n)return n;let s=Hm.call(this,e,r);if(void 0===s){const n=null===(o=e.localRefs)||void 0===o?void 0:o[r],{schemaId:a}=this.opts;n&&(s=new Um({schema:n,schemaId:a,root:e,baseId:t}))}return void 0!==s?e.refs[r]=Vm.call(this,s):void 0},jm.getCompilingSchema=Fm,jm.resolveSchema=Km;const Zm=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Gm(e,{baseId:t,schema:r,root:o}){var n;if("/"!==(null===(n=e.fragment)||void 0===n?void 0:n[0]))return;for(const o of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;const e=r[(0,Mm.unescapeFragment)(o)];if(void 0===e)return;const n="object"==typeof(r=e)&&r[this.opts.schemaId];!Zm.has(o)&&n&&(t=(0,Am.resolveUrl)(this.opts.uriResolver,t,n))}let s;if("boolean"!=typeof r&&r.$ref&&!(0,Mm.schemaHasRulesButRef)(r,this.RULES)){const e=(0,Am.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=Km.call(this,o,e)}const{schemaId:a}=this.opts;return s=s||new Um({schema:r,schemaId:a,root:o,baseId:t}),s.schema!==s.root.schema?s:void 0}var Bm={$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:!1},Jm={};Object.defineProperty(Jm,"__esModule",{value:!0});const Wm=Pl;Wm.code='require("ajv/dist/runtime/uri").default',Jm.default=Wm,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Sm();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=lf;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const o=Im(),n=Cm(),s=Rf,a=jm,i=lf,c=am,u=jf,l=pf,d=Bm,h=Jm,p=(e,t)=>new RegExp(e,t);p.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],m=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."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function v(e){var t,r,o,n,s,a,i,c,u,l,d,f,m,y,g,v,_,w,$,b,k,E,S,P,T;const I=e.strict,x=null===(t=e.code)||void 0===t?void 0:t.optimize,N=!0===x||void 0===x?1:x||0,C=null!==(o=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==o?o:p,j=null!==(n=e.uriResolver)&&void 0!==n?n:h.default;return{strictSchema:null===(a=null!==(s=e.strictSchema)&&void 0!==s?s:I)||void 0===a||a,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:I)||void 0===c||c,strictTypes:null!==(l=null!==(u=e.strictTypes)&&void 0!==u?u:I)&&void 0!==l?l:"log",strictTuples:null!==(f=null!==(d=e.strictTuples)&&void 0!==d?d:I)&&void 0!==f?f:"log",strictRequired:null!==(y=null!==(m=e.strictRequired)&&void 0!==m?m:I)&&void 0!==y&&y,code:e.code?{...e.code,optimize:N,regExp:C}:{optimize:N,regExp:C},loopRequired:null!==(g=e.loopRequired)&&void 0!==g?g:200,loopEnum:null!==(v=e.loopEnum)&&void 0!==v?v:200,meta:null===(_=e.meta)||void 0===_||_,messages:null===(w=e.messages)||void 0===w||w,inlineRefs:null===($=e.inlineRefs)||void 0===$||$,schemaId:null!==(b=e.schemaId)&&void 0!==b?b:"$id",addUsedSchema:null===(k=e.addUsedSchema)||void 0===k||k,validateSchema:null===(E=e.validateSchema)||void 0===E||E,validateFormats:null===(S=e.validateFormats)||void 0===S||S,unicodeRegExp:null===(P=e.unicodeRegExp)||void 0===P||P,int32range:null===(T=e.int32range)||void 0===T||T,uriResolver:j}}class _{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:m,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 o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,s.getRules)(),w.call(this,y,e,"NOT SUPPORTED"),w.call(this,g,e,"DEPRECATED","warn"),this._metaOpts=S.call(this),e.formats&&k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&E.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),b.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let o=d;"id"===r&&(o={...d},o.id=o.$id,delete o.$id),t&&e&&this.addMetaSchema(o,o[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 o=r(t);return"$async"in r||(this.errors=r.errors),o}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 o.call(this,e,t);async function o(e,t){await s.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||a.call(this,r)}async function s(e){e&&!this.getSchema(e)&&await o.call(this,{$ref:e},!0)}async function a(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof n.default))throw t;return i.call(this,t),await c.call(this,t.missingSchema),a.call(this,e)}}function i({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 u.call(this,e);this.refs[e]||await s.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function u(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,o=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,o);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,c.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,o,!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 o=this.validate(r,e);if(!o&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return o}getSchema(e){let t;for(;"string"==typeof(t=$.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,o=new a.SchemaEnv({schema:{},schemaId:r});if(t=a.resolveSchema.call(this,o,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=$.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,c.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(I.call(this,r,t),!t)return(0,l.eachItem)(r,e=>x.call(this,e)),this;C.call(this,t);const o={...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)};return(0,l.eachItem)(r,0===o.type.length?e=>x.call(this,e,o):e=>o.type.forEach(t=>x.call(this,e,o,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 o of t){const t=o.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:o}=t.definition,s=n[e];o&&s&&(n[e]=R(s))}}return e}_removeAllSchemas(e,t){for(const r in e){const o=e[r];t&&!t.test(r)||("string"==typeof o?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,t,r,o=this.opts.validateSchema,n=this.opts.addUsedSchema){let s;const{schemaId:i}=this.opts;if("object"==typeof e)s=e[i];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 u=this._cache.get(e);if(void 0!==u)return u;r=(0,c.normalizeId)(s||r);const l=c.getSchemaRefs.call(this,e,r);return u=new a.SchemaEnv({schema:e,schemaId:i,meta:t,baseId:r,localRefs:l}),this._cache.set(u.schema,u),n&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=u),o&&this.validateSchema(e,!0),u}_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):a.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{a.compileSchema.call(this,e)}finally{this.opts=t}}}function w(e,t,r,o="error"){for(const n in e){const s=n;s in t&&this.logger[o](`${r}: option ${n}. ${e[s]}`)}}function $(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function b(){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 k(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E(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 S(){const e={...this.opts};for(const t of f)delete e[t];return e}_.ValidationError=o.default,_.MissingRefError=n.default,e.default=_;const P={log(){},warn(){},error(){}};const T=/^[a-z_$][a-z0-9_$:-]*$/i;function I(e,t){const{RULES:r}=this;if((0,l.eachItem)(e,e=>{if(r.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!T.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 x(e,t,r){var o;const n=null==t?void 0:t.post;if(r&&n)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:s}=this;let a=n?s.post:s.rules.find(({type:e})=>e===r);if(a||(a={type:r,rules:[]},s.rules.push(a)),s.keywords[e]=!0,!t)return;const i={keyword:e,definition:{...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)}};t.before?N.call(this,a,i,t.before):a.rules.push(i),s.all[e]=i,null===(o=t.implements)||void 0===o||o.forEach(e=>this.addKeyword(e))}function N(e,t,r){const o=e.rules.findIndex(e=>e.keyword===r);o>=0?e.rules.splice(o,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function C(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=R(t)),e.validateSchema=this.compile(t,!0))}const j={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function R(e){return{anyOf:[e,j]}}}(sf);var Qm={},Ym={},Xm={};Object.defineProperty(Xm,"__esModule",{value:!0});const ey={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Xm.default=ey;var ty={};Object.defineProperty(ty,"__esModule",{value:!0}),ty.callRef=ty.getValidate=void 0;const ry=Cm(),oy=rm(),ny=lf,sy=Nf(),ay=jm,iy=pf,cy={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:r,it:o}=e,{baseId:n,schemaEnv:s,validateName:a,opts:i,self:c}=o,{root:u}=s;if(("#"===r||"#/"===r)&&n===u.baseId)return function(){if(s===u)return ly(e,a,s,s.$async);const r=t.scopeValue("root",{ref:u});return ly(e,ny._`${r}.validate`,u,u.$async)}();const l=ay.resolveRef.call(c,u,n,r);if(void 0===l)throw new ry.default(o.opts.uriResolver,n,r);return l instanceof ay.SchemaEnv?function(t){const r=uy(e,t);ly(e,r,t,t.$async)}(l):function(o){const n=t.scopeValue("schema",!0===i.code.source?{ref:o,code:(0,ny.stringify)(o)}:{ref:o}),s=t.name("valid"),a=e.subschema({schema:o,dataTypes:[],schemaPath:ny.nil,topSchemaRef:n,errSchemaPath:r},s);e.mergeEvaluated(a),e.ok(s)}(l)}};function uy(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):ny._`${r.scopeValue("wrapper",{ref:t})}.validate`}function ly(e,t,r,o){const{gen:n,it:s}=e,{allErrors:a,schemaEnv:i,opts:c}=s,u=c.passContext?sy.default.this:ny.nil;function l(e){const t=ny._`${e}.errors`;n.assign(sy.default.vErrors,ny._`${sy.default.vErrors} === null ? ${t} : ${sy.default.vErrors}.concat(${t})`),n.assign(sy.default.errors,ny._`${sy.default.vErrors}.length`)}function d(e){var t;if(!s.opts.unevaluated)return;const o=null===(t=null==r?void 0:r.validate)||void 0===t?void 0:t.evaluated;if(!0!==s.props)if(o&&!o.dynamicProps)void 0!==o.props&&(s.props=iy.mergeEvaluated.props(n,o.props,s.props));else{const t=n.var("props",ny._`${e}.evaluated.props`);s.props=iy.mergeEvaluated.props(n,t,s.props,ny.Name)}if(!0!==s.items)if(o&&!o.dynamicItems)void 0!==o.items&&(s.items=iy.mergeEvaluated.items(n,o.items,s.items));else{const t=n.var("items",ny._`${e}.evaluated.items`);s.items=iy.mergeEvaluated.items(n,t,s.items,ny.Name)}}o?function(){if(!i.$async)throw new Error("async schema referenced by sync schema");const r=n.let("valid");n.try(()=>{n.code(ny._`await ${(0,oy.callValidateCode)(e,t,u)}`),d(t),a||n.assign(r,!0)},e=>{n.if(ny._`!(${e} instanceof ${s.ValidationError})`,()=>n.throw(e)),l(e),a||n.assign(r,!1)}),e.ok(r)}():e.result((0,oy.callValidateCode)(e,t,u),()=>d(t),()=>l(t))}ty.getValidate=uy,ty.callRef=ly,ty.default=cy,Object.defineProperty(Ym,"__esModule",{value:!0});const dy=ty,hy=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Xm.default,dy.default];Ym.default=hy;var py={},fy={};Object.defineProperty(fy,"__esModule",{value:!0});const my=lf,yy=my.operators,gy={maximum:{okStr:"<=",ok:yy.LTE,fail:yy.GT},minimum:{okStr:">=",ok:yy.GTE,fail:yy.LT},exclusiveMaximum:{okStr:"<",ok:yy.LT,fail:yy.GTE},exclusiveMinimum:{okStr:">",ok:yy.GT,fail:yy.LTE}},vy={message:({keyword:e,schemaCode:t})=>my.str`must be ${gy[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>my._`{comparison: ${gy[e].okStr}, limit: ${t}}`},_y={keyword:Object.keys(gy),type:"number",schemaType:"number",$data:!0,error:vy,code(e){const{keyword:t,data:r,schemaCode:o}=e;e.fail$data(my._`${r} ${gy[t].fail} ${o} || isNaN(${r})`)}};fy.default=_y;var wy={};Object.defineProperty(wy,"__esModule",{value:!0});const $y=lf,by={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>$y.str`must be multiple of ${e}`,params:({schemaCode:e})=>$y._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:o,it:n}=e,s=n.opts.multipleOfPrecision,a=t.let("res"),i=s?$y._`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:$y._`${a} !== parseInt(${a})`;e.fail$data($y._`(${o} === 0 || (${a} = ${r}/${o}, ${i}))`)}};wy.default=by;var ky={},Ey={};function Sy(e){const t=e.length;let r,o=0,n=0;for(;n<t;)o++,r=e.charCodeAt(n++),r>=55296&&r<=56319&&n<t&&(r=e.charCodeAt(n),56320==(64512&r)&&n++);return o}Object.defineProperty(Ey,"__esModule",{value:!0}),Ey.default=Sy,Sy.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(ky,"__esModule",{value:!0});const Py=lf,Ty=pf,Iy=Ey,xy={message:({keyword:e,schemaCode:t})=>Py.str`must NOT have ${"maxLength"===e?"more":"fewer"} than ${t} characters`,params:({schemaCode:e})=>Py._`{limit: ${e}}`},Ny={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:xy,code(e){const{keyword:t,data:r,schemaCode:o,it:n}=e,s="maxLength"===t?Py.operators.GT:Py.operators.LT,a=!1===n.opts.unicode?Py._`${r}.length`:Py._`${(0,Ty.useFunc)(e.gen,Iy.default)}(${r})`;e.fail$data(Py._`${a} ${s} ${o}`)}};ky.default=Ny;var Cy={};Object.defineProperty(Cy,"__esModule",{value:!0});const jy=rm(),Ry=lf,Oy={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>Ry.str`must match pattern "${e}"`,params:({schemaCode:e})=>Ry._`{pattern: ${e}}`},code(e){const{data:t,$data:r,schema:o,schemaCode:n,it:s}=e,a=s.opts.unicodeRegExp?"u":"",i=r?Ry._`(new RegExp(${n}, ${a}))`:(0,jy.usePattern)(e,o);e.fail$data(Ry._`!${i}.test(${t})`)}};Cy.default=Oy;var zy={};Object.defineProperty(zy,"__esModule",{value:!0});const Ay=lf,My={message:({keyword:e,schemaCode:t})=>Ay.str`must NOT have ${"maxProperties"===e?"more":"fewer"} than ${t} properties`,params:({schemaCode:e})=>Ay._`{limit: ${e}}`},Dy={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:My,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxProperties"===t?Ay.operators.GT:Ay.operators.LT;e.fail$data(Ay._`Object.keys(${r}).length ${n} ${o}`)}};zy.default=Dy;var Uy={};Object.defineProperty(Uy,"__esModule",{value:!0});const qy=rm(),Vy=lf,Fy=pf,Ly={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>Vy.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>Vy._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:r,schemaCode:o,data:n,$data:s,it:a}=e,{opts:i}=a;if(!s&&0===r.length)return;const c=r.length>=i.loopRequired;if(a.allErrors?function(){if(c||s)e.block$data(Vy.nil,u);else for(const t of r)(0,qy.checkReportMissingProp)(e,t)}():function(){const a=t.let("missing");if(c||s){const r=t.let("valid",!0);e.block$data(r,()=>function(r,s){e.setParams({missingProperty:r}),t.forOf(r,o,()=>{t.assign(s,(0,qy.propertyInData)(t,n,r,i.ownProperties)),t.if((0,Vy.not)(s),()=>{e.error(),t.break()})},Vy.nil)}(a,r)),e.ok(r)}else t.if((0,qy.checkMissingProp)(e,r,a)),(0,qy.reportMissingProp)(e,a),t.else()}(),i.strictRequired){const t=e.parentSchema.properties,{definedProperties:o}=e.it;for(const e of r)if(void 0===(null==t?void 0:t[e])&&!o.has(e)){const t=`required property "${e}" is not defined at "${a.schemaEnv.baseId+a.errSchemaPath}" (strictRequired)`;(0,Fy.checkStrictMode)(a,t,a.opts.strictRequired)}}function u(){t.forOf("prop",o,r=>{e.setParams({missingProperty:r}),t.if((0,qy.noPropertyInData)(t,n,r,i.ownProperties),()=>e.error())})}}};Uy.default=Ly;var Hy={};Object.defineProperty(Hy,"__esModule",{value:!0});const Ky=lf,Zy={message:({keyword:e,schemaCode:t})=>Ky.str`must NOT have ${"maxItems"===e?"more":"fewer"} than ${t} items`,params:({schemaCode:e})=>Ky._`{limit: ${e}}`},Gy={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Zy,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxItems"===t?Ky.operators.GT:Ky.operators.LT;e.fail$data(Ky._`${r}.length ${n} ${o}`)}};Hy.default=Gy;var By={},Jy={};Object.defineProperty(Jy,"__esModule",{value:!0});const Wy=nu;Wy.code='require("ajv/dist/runtime/equal").default',Jy.default=Wy,Object.defineProperty(By,"__esModule",{value:!0});const Qy=jf,Yy=lf,Xy=pf,eg=Jy,tg={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>Yy.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>Yy._`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:r,$data:o,schema:n,parentSchema:s,schemaCode:a,it:i}=e;if(!o&&!n)return;const c=t.let("valid"),u=s.items?(0,Qy.getSchemaTypes)(s.items):[];function l(o,n){const s=t.name("item"),a=(0,Qy.checkDataTypes)(u,s,i.opts.strictNumbers,Qy.DataType.Wrong),l=t.const("indices",Yy._`{}`);t.for(Yy._`;${o}--;`,()=>{t.let(s,Yy._`${r}[${o}]`),t.if(a,Yy._`continue`),u.length>1&&t.if(Yy._`typeof ${s} == "string"`,Yy._`${s} += "_"`),t.if(Yy._`typeof ${l}[${s}] == "number"`,()=>{t.assign(n,Yy._`${l}[${s}]`),e.error(),t.assign(c,!1).break()}).code(Yy._`${l}[${s}] = ${o}`)})}function d(o,n){const s=(0,Xy.useFunc)(t,eg.default),a=t.name("outer");t.label(a).for(Yy._`;${o}--;`,()=>t.for(Yy._`${n} = ${o}; ${n}--;`,()=>t.if(Yy._`${s}(${r}[${o}], ${r}[${n}])`,()=>{e.error(),t.assign(c,!1).break(a)})))}e.block$data(c,function(){const o=t.let("i",Yy._`${r}.length`),n=t.let("j");e.setParams({i:o,j:n}),t.assign(c,!0),t.if(Yy._`${o} > 1`,()=>(u.length>0&&!u.some(e=>"object"===e||"array"===e)?l:d)(o,n))},Yy._`${a} === false`),e.ok(c)}};By.default=tg;var rg={};Object.defineProperty(rg,"__esModule",{value:!0});const og=lf,ng=pf,sg=Jy,ag={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>og._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:o,schemaCode:n,schema:s}=e;o||s&&"object"==typeof s?e.fail$data(og._`!${(0,ng.useFunc)(t,sg.default)}(${r}, ${n})`):e.fail(og._`${s} !== ${r}`)}};rg.default=ag;var ig={};Object.defineProperty(ig,"__esModule",{value:!0});const cg=lf,ug=pf,lg=Jy,dg={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>cg._`{allowedValues: ${e}}`},code(e){const{gen:t,data:r,$data:o,schema:n,schemaCode:s,it:a}=e;if(!o&&0===n.length)throw new Error("enum must have non-empty array");const i=n.length>=a.opts.loopEnum;let c;const u=()=>null!=c?c:c=(0,ug.useFunc)(t,lg.default);let l;if(i||o)l=t.let("valid"),e.block$data(l,function(){t.assign(l,!1),t.forOf("v",s,e=>t.if(cg._`${u()}(${r}, ${e})`,()=>t.assign(l,!0).break()))});else{if(!Array.isArray(n))throw new Error("ajv implementation error");const e=t.const("vSchema",s);l=(0,cg.or)(...n.map((t,o)=>function(e,t){const o=n[t];return"object"==typeof o&&null!==o?cg._`${u()}(${r}, ${e}[${t}])`:cg._`${r} === ${o}`}(e,o)))}e.pass(l)}};ig.default=dg,Object.defineProperty(py,"__esModule",{value:!0});const hg=wy,pg=ky,fg=Cy,mg=zy,yg=Uy,gg=Hy,vg=By,_g=rg,wg=ig,$g=[fy.default,hg.default,pg.default,fg.default,mg.default,yg.default,gg.default,vg.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},_g.default,wg.default];py.default=$g;var bg={},kg={};Object.defineProperty(kg,"__esModule",{value:!0}),kg.validateAdditionalItems=void 0;const Eg=lf,Sg=pf,Pg={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>Eg.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Eg._`{limit: ${e}}`},code(e){const{parentSchema:t,it:r}=e,{items:o}=t;Array.isArray(o)?Tg(e,o):(0,Sg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function Tg(e,t){const{gen:r,schema:o,data:n,keyword:s,it:a}=e;a.items=!0;const i=r.const("len",Eg._`${n}.length`);if(!1===o)e.setParams({len:t.length}),e.pass(Eg._`${i} <= ${t.length}`);else if("object"==typeof o&&!(0,Sg.alwaysValidSchema)(a,o)){const o=r.var("valid",Eg._`${i} <= ${t.length}`);r.if((0,Eg.not)(o),()=>function(o){r.forRange("i",t.length,i,t=>{e.subschema({keyword:s,dataProp:t,dataPropType:Sg.Type.Num},o),a.allErrors||r.if((0,Eg.not)(o),()=>r.break())})}(o)),e.ok(o)}}kg.validateAdditionalItems=Tg,kg.default=Pg;var Ig={},xg={};Object.defineProperty(xg,"__esModule",{value:!0}),xg.validateTuple=void 0;const Ng=lf,Cg=pf,jg=rm(),Rg={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return Og(e,"additionalItems",t);r.items=!0,(0,Cg.alwaysValidSchema)(r,t)||e.ok((0,jg.validateArray)(e))}};function Og(e,t,r=e.schema){const{gen:o,parentSchema:n,data:s,keyword:a,it:i}=e;!function(e){const{opts:o,errSchemaPath:n}=i,s=r.length,c=s===e.minItems&&(s===e.maxItems||!1===e[t]);if(o.strictTuples&&!c){const e=`"${a}" is ${s}-tuple, but minItems or maxItems/${t} are not specified or different at path "${n}"`;(0,Cg.checkStrictMode)(i,e,o.strictTuples)}}(n),i.opts.unevaluated&&r.length&&!0!==i.items&&(i.items=Cg.mergeEvaluated.items(o,r.length,i.items));const c=o.name("valid"),u=o.const("len",Ng._`${s}.length`);r.forEach((t,r)=>{(0,Cg.alwaysValidSchema)(i,t)||(o.if(Ng._`${u} > ${r}`,()=>e.subschema({keyword:a,schemaProp:r,dataProp:r},c)),e.ok(c))})}xg.validateTuple=Og,xg.default=Rg,Object.defineProperty(Ig,"__esModule",{value:!0});const zg=xg,Ag={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,zg.validateTuple)(e,"items")};Ig.default=Ag;var Mg={};Object.defineProperty(Mg,"__esModule",{value:!0});const Dg=lf,Ug=pf,qg=rm(),Vg=kg,Fg={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>Dg.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Dg._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:o}=e,{prefixItems:n}=r;o.items=!0,(0,Ug.alwaysValidSchema)(o,t)||(n?(0,Vg.validateAdditionalItems)(e,n):e.ok((0,qg.validateArray)(e)))}};Mg.default=Fg;var Lg={};Object.defineProperty(Lg,"__esModule",{value:!0});const Hg=lf,Kg=pf,Zg={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?Hg.str`must contain at least ${e} valid item(s)`:Hg.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?Hg._`{minContains: ${e}}`:Hg._`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:r,parentSchema:o,data:n,it:s}=e;let a,i;const{minContains:c,maxContains:u}=o;s.opts.next?(a=void 0===c?1:c,i=u):a=1;const l=t.const("len",Hg._`${n}.length`);if(e.setParams({min:a,max:i}),void 0===i&&0===a)return void(0,Kg.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==i&&a>i)return(0,Kg.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,Kg.alwaysValidSchema)(s,r)){let t=Hg._`${l} >= ${a}`;return void 0!==i&&(t=Hg._`${t} && ${l} <= ${i}`),void e.pass(t)}s.items=!0;const d=t.name("valid");function h(){const e=t.name("_valid"),r=t.let("count",0);p(e,()=>t.if(e,()=>function(e){t.code(Hg._`${e}++`),void 0===i?t.if(Hg._`${e} >= ${a}`,()=>t.assign(d,!0).break()):(t.if(Hg._`${e} > ${i}`,()=>t.assign(d,!1).break()),1===a?t.assign(d,!0):t.if(Hg._`${e} >= ${a}`,()=>t.assign(d,!0)))}(r)))}function p(r,o){t.forRange("i",0,l,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:Kg.Type.Num,compositeRule:!0},r),o()})}void 0===i&&1===a?p(d,()=>t.if(d,()=>t.break())):0===a?(t.let(d,!0),void 0!==i&&t.if(Hg._`${n}.length > 0`,h)):(t.let(d,!1),h()),e.result(d,()=>e.reset())}};Lg.default=Zg;var Gg={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=lf,r=pf,o=rm();e.error={message:({params:{property:e,depsCount:r,deps:o}})=>t.str`must have ${1===r?"property":"properties"} ${o} when property ${e} is present`,params:({params:{property:e,depsCount:r,deps:o,missingProperty:n}})=>t._`{property: ${e},
11
11
  missingProperty: ${n},
12
12
  depsCount: ${r},
13
- deps: ${o}}`};const n={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const o in e){if("__proto__"===o)continue;(Array.isArray(e[o])?t:r)[o]=e[o]}return[t,r]}(e);s(e,t),a(e,r)}};function s(e,r=e.schema){const{gen:n,data:s,it:a}=e;if(0===Object.keys(r).length)return;const i=n.let("missing");for(const c in r){const u=r[c];if(0===u.length)continue;const l=(0,o.propertyInData)(n,s,c,a.opts.ownProperties);e.setParams({property:c,depsCount:u.length,deps:u.join(", ")}),a.allErrors?n.if(l,()=>{for(const t of u)(0,o.checkReportMissingProp)(e,t)}):(n.if(t._`${l} && (${(0,o.checkMissingProp)(e,u,i)})`),(0,o.reportMissingProp)(e,i),n.else())}}function a(e,t=e.schema){const{gen:n,data:s,keyword:a,it:i}=e,c=n.name("valid");for(const u in t)(0,r.alwaysValidSchema)(i,t[u])||(n.if((0,o.propertyInData)(n,s,u,i.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:u},c);e.mergeValidEvaluated(t,c)},()=>n.var(c,!0)),e.ok(c))}e.validatePropertyDeps=s,e.validateSchemaDeps=a,e.default=n}(Gg);var Bg={};Object.defineProperty(Bg,"__esModule",{value:!0});const Jg=lf,Wg=pf,Qg={message:"property name must be valid",params:({params:e})=>Jg._`{propertyName: ${e.propertyName}}`},Yg={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Qg,code(e){const{gen:t,schema:r,data:o,it:n}=e;if((0,Wg.alwaysValidSchema)(n,r))return;const s=t.name("valid");t.forIn("key",o,r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},s),t.if((0,Jg.not)(s),()=>{e.error(!0),n.allErrors||t.break()})}),e.ok(s)}};Bg.default=Yg;var Xg={};Object.defineProperty(Xg,"__esModule",{value:!0});const ev=rm(),tv=lf,rv=Nf(),ov=pf,nv={message:"must NOT have additional properties",params:({params:e})=>tv._`{additionalProperty: ${e.additionalProperty}}`},sv={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:nv,code(e){const{gen:t,schema:r,parentSchema:o,data:n,errsCount:s,it:a}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:i,opts:c}=a;if(a.props=!0,"all"!==c.removeAdditional&&(0,ov.alwaysValidSchema)(a,r))return;const u=(0,ev.allSchemaProperties)(o.properties),l=(0,ev.allSchemaProperties)(o.patternProperties);function d(e){t.code(tv._`delete ${n}[${e}]`)}function h(o){if("all"===c.removeAdditional||c.removeAdditional&&!1===r)d(o);else{if(!1===r)return e.setParams({additionalProperty:o}),e.error(),void(i||t.break());if("object"==typeof r&&!(0,ov.alwaysValidSchema)(a,r)){const r=t.name("valid");"failing"===c.removeAdditional?(p(o,r,!1),t.if((0,tv.not)(r),()=>{e.reset(),d(o)})):(p(o,r),i||t.if((0,tv.not)(r),()=>t.break()))}}}function p(t,r,o){const n={keyword:"additionalProperties",dataProp:t,dataPropType:ov.Type.Str};!1===o&&Object.assign(n,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(n,r)}t.forIn("key",n,r=>{u.length||l.length?t.if(function(r){let n;if(u.length>8){const e=(0,ov.schemaRefOrVal)(a,o.properties,"properties");n=(0,ev.isOwnProperty)(t,e,r)}else n=u.length?(0,tv.or)(...u.map(e=>tv._`${r} === ${e}`)):tv.nil;return l.length&&(n=(0,tv.or)(n,...l.map(t=>tv._`${(0,ev.usePattern)(e,t)}.test(${r})`))),(0,tv.not)(n)}(r),()=>h(r)):h(r)}),e.ok(tv._`${s} === ${rv.default.errors}`)}};Xg.default=sv;var av={};Object.defineProperty(av,"__esModule",{value:!0});const iv=Sm(),cv=rm(),uv=pf,lv=Xg,dv={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:o,data:n,it:s}=e;"all"===s.opts.removeAdditional&&void 0===o.additionalProperties&&lv.default.code(new iv.KeywordCxt(s,lv.default,"additionalProperties"));const a=(0,cv.allSchemaProperties)(r);for(const e of a)s.definedProperties.add(e);s.opts.unevaluated&&a.length&&!0!==s.props&&(s.props=uv.mergeEvaluated.props(t,(0,uv.toHash)(a),s.props));const i=a.filter(e=>!(0,uv.alwaysValidSchema)(s,r[e]));if(0===i.length)return;const c=t.name("valid");for(const r of i)u(r)?l(r):(t.if((0,cv.propertyInData)(t,n,r,s.opts.ownProperties)),l(r),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(r),e.ok(c);function u(e){return s.opts.useDefaults&&!s.compositeRule&&void 0!==r[e].default}function l(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},c)}}};av.default=dv;var hv={};Object.defineProperty(hv,"__esModule",{value:!0});const pv=rm(),fv=lf,mv=pf,yv=pf,gv={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:o,parentSchema:n,it:s}=e,{opts:a}=s,i=(0,pv.allSchemaProperties)(r),c=i.filter(e=>(0,mv.alwaysValidSchema)(s,r[e]));if(0===i.length||c.length===i.length&&(!s.opts.unevaluated||!0===s.props))return;const u=a.strictSchema&&!a.allowMatchingProperties&&n.properties,l=t.name("valid");!0===s.props||s.props instanceof fv.Name||(s.props=(0,yv.evaluatedPropsToName)(t,s.props));const{props:d}=s;function h(e){for(const t in u)new RegExp(e).test(t)&&(0,mv.checkStrictMode)(s,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function p(r){t.forIn("key",o,o=>{t.if(fv._`${(0,pv.usePattern)(e,r)}.test(${o})`,()=>{const n=c.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:o,dataPropType:yv.Type.Str},l),s.opts.unevaluated&&!0!==d?t.assign(fv._`${d}[${o}]`,!0):n||s.allErrors||t.if((0,fv.not)(l),()=>t.break())})})}!function(){for(const e of i)u&&h(e),s.allErrors?p(e):(t.var(l,!0),p(e),t.if(l))}()}};hv.default=gv;var vv={};Object.defineProperty(vv,"__esModule",{value:!0});const _v=pf,wv={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:o}=e;if((0,_v.alwaysValidSchema)(o,r))return void e.fail();const n=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),e.failResult(n,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};vv.default=wv;var $v={};Object.defineProperty($v,"__esModule",{value:!0});const bv={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:rm().validateUnion,error:{message:"must match a schema in anyOf"}};$v.default=bv;var kv={};Object.defineProperty(kv,"__esModule",{value:!0});const Ev=lf,Sv=pf,Pv={message:"must match exactly one schema in oneOf",params:({params:e})=>Ev._`{passingSchemas: ${e.passing}}`},Tv={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Pv,code(e){const{gen:t,schema:r,parentSchema:o,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&o.discriminator)return;const s=r,a=t.let("valid",!1),i=t.let("passing",null),c=t.name("_valid");e.setParams({passing:i}),t.block(function(){s.forEach((r,o)=>{let s;(0,Sv.alwaysValidSchema)(n,r)?t.var(c,!0):s=e.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},c),o>0&&t.if(Ev._`${c} && ${a}`).assign(a,!1).assign(i,Ev._`[${i}, ${o}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(i,o),s&&e.mergeEvaluated(s,Ev.Name)})})}),e.result(a,()=>e.reset(),()=>e.error(!0))}};kv.default=Tv;var Iv={};Object.defineProperty(Iv,"__esModule",{value:!0});const xv=pf,Nv={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const n=t.name("valid");r.forEach((t,r)=>{if((0,xv.alwaysValidSchema)(o,t))return;const s=e.subschema({keyword:"allOf",schemaProp:r},n);e.ok(n),e.mergeEvaluated(s)})}};Iv.default=Nv;var Cv={};Object.defineProperty(Cv,"__esModule",{value:!0});const jv=lf,Rv=pf,Ov={message:({params:e})=>jv.str`must match "${e.ifClause}" schema`,params:({params:e})=>jv._`{failingKeyword: ${e.ifClause}}`},zv={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Ov,code(e){const{gen:t,parentSchema:r,it:o}=e;void 0===r.then&&void 0===r.else&&(0,Rv.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const n=Av(o,"then"),s=Av(o,"else");if(!n&&!s)return;const a=t.let("valid",!0),i=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);e.mergeEvaluated(t)}(),e.reset(),n&&s){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(i,c("then",r),c("else",r))}else n?t.if(i,c("then")):t.if((0,jv.not)(i),c("else"));function c(r,o){return()=>{const n=e.subschema({keyword:r},i);t.assign(a,i),e.mergeValidEvaluated(n,a),o?t.assign(o,jv._`${r}`):e.setParams({ifClause:r})}}e.pass(a,()=>e.error(!0))}};function Av(e,t){const r=e.schema[t];return void 0!==r&&!(0,Rv.alwaysValidSchema)(e,r)}Cv.default=zv;var Mv={};Object.defineProperty(Mv,"__esModule",{value:!0});const Dv=pf,Uv={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,Dv.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Mv.default=Uv,Object.defineProperty(bg,"__esModule",{value:!0});const qv=kg,Vv=Ig,Fv=xg,Lv=Mg,Hv=Lg,Kv=Gg,Zv=Bg,Gv=Xg,Bv=av,Jv=hv,Wv=vv,Qv=$v,Yv=kv,Xv=Iv,e_=Cv,t_=Mv;bg.default=function(e=!1){const t=[Wv.default,Qv.default,Yv.default,Xv.default,e_.default,t_.default,Zv.default,Gv.default,Kv.default,Bv.default,Jv.default];return e?t.push(Vv.default,Lv.default):t.push(qv.default,Fv.default),t.push(Hv.default),t};var r_={},o_={};Object.defineProperty(o_,"__esModule",{value:!0});const n_=lf,s_={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>n_.str`must match format "${e}"`,params:({schemaCode:e})=>n_._`{format: ${e}}`},code(e,t){const{gen:r,data:o,$data:n,schema:s,schemaCode:a,it:i}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=i;c.validateFormats&&(n?function(){const n=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),s=r.const("fDef",n_._`${n}[${a}]`),i=r.let("fType"),u=r.let("format");r.if(n_._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(i,n_._`${s}.type || "string"`).assign(u,n_._`${s}.validate`),()=>r.assign(i,n_._`"string"`).assign(u,s)),e.fail$data((0,n_.or)(!1===c.strictSchema?n_.nil:n_._`${a} && !${u}`,function(){const e=l.$async?n_._`(${s}.async ? await ${u}(${o}) : ${u}(${o}))`:n_._`${u}(${o})`,r=n_._`(typeof ${u} == "function" ? ${e} : ${u}.test(${o}))`;return n_._`${u} && ${u} !== true && ${i} === ${t} && !${r}`}()))}():function(){const n=d.formats[s];if(!n)return void function(){if(!1===c.strictSchema)return void d.logger.warn(e());throw new Error(e());function e(){return`unknown format "${s}" ignored in schema at path "${u}"`}}();if(!0===n)return;const[a,i,h]=function(e){const t=e instanceof RegExp?(0,n_.regexpCode)(e):c.code.formats?n_._`${c.code.formats}${(0,n_.getProperty)(s)}`:void 0,o=r.scopeValue("formats",{key:s,ref:e,code:t});if("object"==typeof e&&!(e instanceof RegExp))return[e.type||"string",e.validate,n_._`${o}.validate`];return["string",e,o]}(n);a===t&&e.pass(function(){if("object"==typeof n&&!(n instanceof RegExp)&&n.async){if(!l.$async)throw new Error("async format in sync schema");return n_._`await ${h}(${o})`}return"function"==typeof i?n_._`${h}(${o})`:n_._`${h}.test(${o})`}())}())}};o_.default=s_,Object.defineProperty(r_,"__esModule",{value:!0});const a_=[o_.default];r_.default=a_;var i_={};Object.defineProperty(i_,"__esModule",{value:!0}),i_.contentVocabulary=i_.metadataVocabulary=void 0,i_.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],i_.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(Qm,"__esModule",{value:!0});const c_=py,u_=bg,l_=r_,d_=i_,h_=[Ym.default,c_.default,(0,u_.default)(),l_.default,d_.metadataVocabulary,d_.contentVocabulary];Qm.default=h_;var p_,f_={},m_={};Object.defineProperty(m_,"__esModule",{value:!0}),m_.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(p_||(m_.DiscrError=p_={})),Object.defineProperty(f_,"__esModule",{value:!0});const y_=lf,g_=m_,v_=jm,__=Cm(),w_=pf,$_={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===g_.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>y_._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},code(e){const{gen:t,data:r,schema:o,parentSchema:n,it:s}=e,{oneOf:a}=n;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const i=o.propertyName;if("string"!=typeof i)throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");const c=t.let("valid",!1),u=t.const("tag",y_._`${r}${(0,y_.getProperty)(i)}`);function l(r){const o=t.name("valid"),n=e.subschema({keyword:"oneOf",schemaProp:r},o);return e.mergeEvaluated(n,y_.Name),o}t.if(y_._`typeof ${u} == "string"`,()=>function(){const r=function(){var e;const t={},r=c(n);let o=!0;for(let t=0;t<a.length;t++){let n=a[t];if((null==n?void 0:n.$ref)&&!(0,w_.schemaHasRulesButRef)(n,s.self.RULES)){const e=n.$ref;if(n=v_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,e),n instanceof v_.SchemaEnv&&(n=n.schema),void 0===n)throw new __.default(s.opts.uriResolver,s.baseId,e)}const l=null===(e=null==n?void 0:n.properties)||void 0===e?void 0:e[i];if("object"!=typeof l)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);o=o&&(r||c(n)),u(l,t)}if(!o)throw new Error(`discriminator: "${i}" must be required`);return t;function c({required:e}){return Array.isArray(e)&&e.includes(i)}function u(e,t){if(e.const)l(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`);for(const r of e.enum)l(r,t)}}function l(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${i}" values must be unique strings`);t[e]=r}}();t.if(!1);for(const e in r)t.elseIf(y_._`${u} === ${e}`),t.assign(c,l(r[e]));t.else(),e.error(!1,{discrError:g_.DiscrError.Mapping,tag:u,tagName:i}),t.endIf()}(),()=>e.error(!1,{discrError:g_.DiscrError.Tag,tag:u,tagName:i})),e.ok(c)}};f_.default=$_;var b_={$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:!0,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:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},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:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},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:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},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:!0};!function(e,t){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 r=sf,o=Qm,n=f_,s=b_,a=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),o.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(n.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(e,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=Sm();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=lf;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 d=Im();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var h=Cm();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return h.default}})}(nf,nf.exports);var k_=nf.exports;!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=k_,r=lf,o=r.operators,n={formatMaximum:{okStr:"<=",ok:o.LTE,fail:o.GT},formatMinimum:{okStr:">=",ok:o.GTE,fail:o.LT},formatExclusiveMaximum:{okStr:"<",ok:o.LT,fail:o.GTE},formatExclusiveMinimum:{okStr:">",ok:o.GT,fail:o.LTE}},s={message:({keyword:e,schemaCode:t})=>r.str`should be ${n[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>r._`{comparison: ${n[e].okStr}, limit: ${t}}`};e.formatLimitDefinition={keyword:Object.keys(n),type:"string",schemaType:"string",$data:!0,error:s,code(e){const{gen:o,data:s,schemaCode:a,keyword:i,it:c}=e,{opts:u,self:l}=c;if(!u.validateFormats)return;const d=new t.KeywordCxt(c,l.RULES.all.format.definition,"format");function h(e){return r._`${e}.compare(${s}, ${a}) ${n[i].fail} 0`}d.$data?function(){const t=o.scopeValue("formats",{ref:l.formats,code:u.code.formats}),n=o.const("fmt",r._`${t}[${d.schemaCode}]`);e.fail$data((0,r.or)(r._`typeof ${n} != "object"`,r._`${n} instanceof RegExp`,r._`typeof ${n}.compare != "function"`,h(n)))}():function(){const t=d.schema,n=l.formats[t];if(!n||!0===n)return;if("object"!=typeof n||n instanceof RegExp||"function"!=typeof n.compare)throw new Error(`"${i}": format "${t}" does not define "compare" function`);const s=o.scopeValue("formats",{key:t,ref:n,code:u.code.formats?r._`${u.code.formats}${(0,r.getProperty)(t)}`:void 0});e.fail$data(h(s))}()},dependencies:["format"]};e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)}(of),function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=rf,o=of,n=lf,s=new n.Name("fullFormats"),a=new n.Name("fastFormats"),i=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,r.fullFormats,s),e;const[n,i]="fast"===t.mode?[r.fastFormats,a]:[r.fullFormats,s];return c(e,t.formats||r.formatNames,n,i),t.keywords&&(0,o.default)(e),e};function c(e,t,r,o){var s,a;null!==(s=(a=e.opts.code).formats)&&void 0!==s||(a.formats=n._`require("ajv-formats/dist/formats").${o}`);for(const o of t)e.addFormat(o,r[o])}i.get=(e,t="full")=>{const o=("fast"===t?r.fastFormats:r.fullFormats)[e];if(!o)throw new Error(`Unknown format "${e}"`);return o},e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i}(tf,tf.exports);var E_=Ji(tf.exports);class S_{constructor(e){this._ajv=e??function(){const e=new ef({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return E_(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 P_{constructor(e){this._client=e}async*callToolStream(e,t=Qa,r){const o=this._client,n={...r,task:r?.task??(o.isToolTask(e.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:e},t,n),a=o.getToolOutputValidator(e.name);for await(const t of s){if("result"===t.type&&a){const r=t.result;if(!r.structuredContent&&!r.isError)return void(yield{type:"error",error:new Fi(ks.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)});if(r.structuredContent)try{const e=a(r.structuredContent);if(!e.valid)return void(yield{type:"error",error:new Fi(ks.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)})}catch(e){return e instanceof Fi?void(yield{type:"error",error:e}):void(yield{type:"error",error:new Fi(ks.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)})}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}function T_(e,t){if(e&&null!==t&&"object"==typeof t){if("object"===e.type&&e.properties&&"object"==typeof e.properties){const r=t,o=e.properties;for(const e of Object.keys(o)){const t=o[e];void 0===r[e]&&Object.prototype.hasOwnProperty.call(t,"default")&&(r[e]=t.default),void 0!==r[e]&&T_(t,r[e])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)"boolean"!=typeof r&&T_(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)"boolean"!=typeof r&&T_(r,t)}}class I_ extends Gi{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new S_,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ei,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ka,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Ea,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new P_(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 o=e,n=t[o];if(void 0===n)continue;const s=r[o];Bi(s)&&Bi(n)?r[o]={...s,...n}:r[o]=n}return r}(this._capabilities,e)}setRequestHandler(e,t){const r=ko(e),o=r?.method;if(!o)throw new Error("Schema is missing a method literal");let n;if($o(o)){const e=o,t=e._zod?.def;n=t?.value??e.value}else{const e=o,t=e._def;n=t?.value??e.value}if("string"!=typeof n)throw new Error("Schema method literal must be a string");const s=n;if("elicitation/create"===s){const r=async(e,r)=>{const o=bo(xi,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Fi(ks.InvalidParams,`Invalid elicitation request: ${e}`)}const{params:n}=o.data;n.mode=n.mode??"form";const{supportsFormMode:s,supportsUrlMode:a}=function(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=void 0!==e.form,r=void 0!==e.url;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}(this._capabilities.elicitation);if("form"===n.mode&&!s)throw new Fi(ks.InvalidParams,"Client does not support form-mode elicitation requests");if("url"===n.mode&&!a)throw new Fi(ks.InvalidParams,"Client does not support URL-mode elicitation requests");const i=await Promise.resolve(t(e,r));if(n.task){const e=bo(Ys,i);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Fi(ks.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const c=bo(ji,i);if(!c.success){const e=c.error instanceof Error?c.error.message:String(c.error);throw new Fi(ks.InvalidParams,`Invalid elicitation result: ${e}`)}const u=c.data,l="form"===n.mode?n.requestedSchema:void 0;if("form"===n.mode&&"accept"===u.action&&u.content&&l&&this._capabilities.elicitation?.form?.applyDefaults)try{T_(l,u.content)}catch{}return u};return super.setRequestHandler(e,r)}if("sampling/createMessage"===s){const r=async(e,r)=>{const o=bo(mi,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Fi(ks.InvalidParams,`Invalid sampling request: ${e}`)}const{params:n}=o.data,s=await Promise.resolve(t(e,r));if(n.task){const e=bo(Ys,s);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Fi(ks.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const a=bo(n.tools||n.toolChoice?gi:yi,s);if(!a.success){const e=a.error instanceof Error?a.error.message:String(a.error);throw new Fi(ks.InvalidParams,`Invalid sampling result: ${e}`)}return a.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),void 0===e.sessionId)try{const r=await this.request({method:"initialize",params:{protocolVersion:es,capabilities:this._capabilities,clientInfo:this._clientInfo}},Vs,t);if(void 0===r)throw new Error(`Server sent invalid initialize result: ${r}`);if(!ts.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if("notifications/roots/list_changed"===e)if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client 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})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`)}(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&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._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Ps,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},Mi,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},Ps,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},Ha,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},Oa,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},ga,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},_a,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},ka,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},Ps,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},Ps,t)}async callTool(e,t=Qa,r){if(this.isToolTaskRequired(e.name))throw new Fi(ks.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:e},t,r),n=this.getToolOutputValidator(e.name);if(n){if(!o.structuredContent&&!o.isError)throw new Fi(ks.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const e=n(o.structuredContent);if(!e.valid)throw new Fi(ks.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){if(e instanceof Fi)throw e;throw new Fi(ks.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}isToolTask(e){return!!this._serverCapabilities?.tasks?.requests?.tools?.call&&this._cachedKnownTaskTools.has(e)}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}const e=t.execution?.taskSupport;"required"!==e&&"optional"!==e||this._cachedKnownTaskTools.add(t.name),"required"===e&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Wa,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,o){const n=ti.safeParse(r);if(!n.success)throw new Error(`Invalid ${e} listChanged options: ${n.error.message}`);if("function"!=typeof r.onChanged)throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:s,debounceMs:a}=n.data,{onChanged:i}=r,c=async()=>{if(s)try{const e=await o();i(null,e)}catch(e){const t=e instanceof Error?e:new Error(String(e));i(t,null)}else i(null,null)};this.setNotificationHandler(t,()=>{if(a){const t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);const r=setTimeout(c,a);this._listChangedDebounceTimers.set(e,r)}else c()})}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function x_(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}const N_=lo(Ko,C_).superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Xn,message:"URL must be parseable",fatal:!0}),ke}).refine(e=>{const t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"});var C_;const j_=Sn({resource:qo().url(),authorization_servers:bn(N_).optional(),jwks_uri:qo().url().optional(),scopes_supported:bn(qo()).optional(),bearer_methods_supported:bn(qo()).optional(),resource_signing_alg_values_supported:bn(qo()).optional(),resource_name:qo().optional(),resource_documentation:qo().optional(),resource_policy_uri:qo().url().optional(),resource_tos_uri:qo().url().optional(),tls_client_certificate_bound_access_tokens:pn().optional(),authorization_details_types_supported:bn(qo()).optional(),dpop_signing_alg_values_supported:bn(qo()).optional(),dpop_bound_access_tokens_required:pn().optional()}),R_=Sn({issuer:qo(),authorization_endpoint:N_,token_endpoint:N_,registration_endpoint:N_.optional(),scopes_supported:bn(qo()).optional(),response_types_supported:bn(qo()),response_modes_supported:bn(qo()).optional(),grant_types_supported:bn(qo()).optional(),token_endpoint_auth_methods_supported:bn(qo()).optional(),token_endpoint_auth_signing_alg_values_supported:bn(qo()).optional(),service_documentation:N_.optional(),revocation_endpoint:N_.optional(),revocation_endpoint_auth_methods_supported:bn(qo()).optional(),revocation_endpoint_auth_signing_alg_values_supported:bn(qo()).optional(),introspection_endpoint:qo().optional(),introspection_endpoint_auth_methods_supported:bn(qo()).optional(),introspection_endpoint_auth_signing_alg_values_supported:bn(qo()).optional(),code_challenge_methods_supported:bn(qo()).optional(),client_id_metadata_document_supported:pn().optional()}),O_=En({...Sn({issuer:qo(),authorization_endpoint:N_,token_endpoint:N_,userinfo_endpoint:N_.optional(),jwks_uri:N_,registration_endpoint:N_.optional(),scopes_supported:bn(qo()).optional(),response_types_supported:bn(qo()),response_modes_supported:bn(qo()).optional(),grant_types_supported:bn(qo()).optional(),acr_values_supported:bn(qo()).optional(),subject_types_supported:bn(qo()),id_token_signing_alg_values_supported:bn(qo()),id_token_encryption_alg_values_supported:bn(qo()).optional(),id_token_encryption_enc_values_supported:bn(qo()).optional(),userinfo_signing_alg_values_supported:bn(qo()).optional(),userinfo_encryption_alg_values_supported:bn(qo()).optional(),userinfo_encryption_enc_values_supported:bn(qo()).optional(),request_object_signing_alg_values_supported:bn(qo()).optional(),request_object_encryption_alg_values_supported:bn(qo()).optional(),request_object_encryption_enc_values_supported:bn(qo()).optional(),token_endpoint_auth_methods_supported:bn(qo()).optional(),token_endpoint_auth_signing_alg_values_supported:bn(qo()).optional(),display_values_supported:bn(qo()).optional(),claim_types_supported:bn(qo()).optional(),claims_supported:bn(qo()).optional(),service_documentation:qo().optional(),claims_locales_supported:bn(qo()).optional(),ui_locales_supported:bn(qo()).optional(),claims_parameter_supported:pn().optional(),request_parameter_supported:pn().optional(),request_uri_parameter_supported:pn().optional(),require_request_uri_registration:pn().optional(),op_policy_uri:N_.optional(),op_tos_uri:N_.optional(),client_id_metadata_document_supported:pn().optional()}).shape,...R_.pick({code_challenge_methods_supported:!0}).shape}),z_=En({access_token:qo(),id_token:qo().optional(),token_type:qo(),expires_in:function(e){return function(e,t){return new e({type:"number",coerce:!0,checks:[],...Fe(t)})}(cn,e)}().optional(),scope:qo().optional(),refresh_token:qo().optional()}).strip(),A_=En({error:qo(),error_description:qo().optional(),error_uri:qo().optional()}),M_=N_.optional().or(Mn("").transform(()=>{})),D_=En({redirect_uris:bn(N_),token_endpoint_auth_method:qo().optional(),grant_types:bn(qo()).optional(),response_types:bn(qo()).optional(),client_name:qo().optional(),client_uri:N_.optional(),logo_uri:M_,scope:qo().optional(),contacts:bn(qo()).optional(),tos_uri:M_,policy_uri:qo().optional(),jwks_uri:N_.optional(),jwks:new yn({type:"any"}).optional(),software_id:qo().optional(),software_version:qo().optional(),software_statement:qo().optional()}).strip(),U_=En({client_id:qo(),client_secret:qo().optional(),client_id_issued_at:un().optional(),client_secret_expires_at:un().optional()}).strip(),q_=D_.merge(U_);En({error:qo(),error_description:qo().optional()}).strip(),En({token:qo(),token_type_hint:qo().optional()}).strip();class V_ extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class F_ extends V_{}F_.errorCode="invalid_request";class L_ extends V_{}L_.errorCode="invalid_client";class H_ extends V_{}H_.errorCode="invalid_grant";class K_ extends V_{}K_.errorCode="unauthorized_client";class Z_ extends V_{}Z_.errorCode="unsupported_grant_type";class G_ extends V_{}G_.errorCode="invalid_scope";class B_ extends V_{}B_.errorCode="access_denied";class J_ extends V_{}J_.errorCode="server_error";class W_ extends V_{}W_.errorCode="temporarily_unavailable";class Q_ extends V_{}Q_.errorCode="unsupported_response_type";class Y_ extends V_{}Y_.errorCode="unsupported_token_type";class X_ extends V_{}X_.errorCode="invalid_token";class ew extends V_{}ew.errorCode="method_not_allowed";class tw extends V_{}tw.errorCode="too_many_requests";class rw extends V_{}rw.errorCode="invalid_client_metadata";class ow extends V_{}ow.errorCode="insufficient_scope";class nw extends V_{}nw.errorCode="invalid_target";const sw={[F_.errorCode]:F_,[L_.errorCode]:L_,[H_.errorCode]:H_,[K_.errorCode]:K_,[Z_.errorCode]:Z_,[G_.errorCode]:G_,[B_.errorCode]:B_,[J_.errorCode]:J_,[W_.errorCode]:W_,[Q_.errorCode]:Q_,[Y_.errorCode]:Y_,[X_.errorCode]:X_,[ew.errorCode]:ew,[tw.errorCode]:tw,[rw.errorCode]:rw,[ow.errorCode]:ow,[nw.errorCode]:nw};class aw extends Error{constructor(e){super(e??"Unauthorized")}}const iw="code",cw="S256";function uw(e,t,r,o){const{client_id:n,client_secret:s}=t;switch(e){case"client_secret_basic":return void function(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}(n,s,r);case"client_secret_post":return void function(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}(n,s,o);case"none":return void function(e,t){t.set("client_id",e)}(n,o);default:throw new Error(`Unsupported client authentication method: ${e}`)}}async function lw(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=A_.parse(JSON.parse(r)),{error:t,error_description:o,error_uri:n}=e;return new(sw[t]||J_)(o||"",n)}catch(e){return new J_(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function dw(e,t){try{return await hw(e,t)}catch(r){if(r instanceof L_||r instanceof K_)return await(e.invalidateCredentials?.("all")),await hw(e,t);if(r instanceof H_)return await(e.invalidateCredentials?.("tokens")),await hw(e,t);throw r}}async function hw(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:n,fetchFn:s}){let a,i;try{a=await async function(e,t,r=fetch){const o=await async function(e,t,r,o){const n=new URL(e),s=o?.protocolVersion??es;let a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{const e=function(e,t="",r={}){t.endsWith("/")&&(t=t.slice(0,-1));return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,n.pathname);a=new URL(e,o?.metadataServerUrl??n),a.search=n.search}let i=await yw(a,s,r);if(!o?.metadataUrl&&function(e,t){return!e||e.status>=400&&e.status<500&&"/"!==t}(i,n.pathname)){const e=new URL(`/.well-known/${t}`,n);i=await yw(e,s,r)}return i}(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||404===o.status)throw await(o?.body?.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await(o.body?.cancel()),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return j_.parse(await o.json())}(t,{resourceMetadataUrl:n},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",t));const c=await async function(e,t,r){const o=function(e){const t="string"==typeof e?new URL(e):new URL(e.href);return t.hash="",t}(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!function({requestedResource:e,configuredResource:t}){const r="string"==typeof e?new URL(e):new URL(e.href),o="string"==typeof t?new URL(t):new URL(t.href);if(r.origin!==o.origin)return!1;if(r.pathname.length<o.pathname.length)return!1;const n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(s)}({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}(t,e,a),u=await async function(e,{fetchFn:t=fetch,protocolVersion:r=es}={}){const o={"MCP-Protocol-Version":r,Accept:"application/json"},n=function(e){const t="string"==typeof e?new URL(e):e,r="/"!==t.pathname,o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;n.endsWith("/")&&(n=n.slice(0,-1));return o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"}),o.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}(e);for(const{url:e,type:r}of n){const n=await mw(e,o,t);if(n){if(!n.ok){if(await(n.body?.cancel()),n.status>=400&&n.status<500)continue;throw new Error(`HTTP ${n.status} trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`)}return"oauth"===r?R_.parse(await n.json()):O_.parse(await n.json())}}return}(i,{fetchFn:s});let l=await Promise.resolve(e.clientInformation());if(!l){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const t=!0===u?.client_id_metadata_document_supported,o=e.clientMetadataUrl;if(o&&!function(e){if(!e)return!1;try{const t=new URL(e);return"https:"===t.protocol&&"/"!==t.pathname}catch{return!1}}(o))throw new rw(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${o}`);if(t&&o)l={client_id:o},await(e.saveClientInformation?.(l));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const t=await async function(e,{metadata:t,clientMetadata:r,fetchFn:o}){let n;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(t.registration_endpoint)}else n=new URL("/register",e);const s=await(o??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await lw(s);return q_.parse(await s.json())}(i,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(t),l=t}}const d=!e.redirectUrl;if(void 0!==r||d){const t=await async function(e,t,{metadata:r,resource:o,authorizationCode:n,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a));if(!i){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");i=function(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}(n,await e.codeVerifier(),e.redirectUrl)}const c=await e.clientInformation();return gw(t,{metadata:r,tokenRequestParams:i,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:s})}(e,i,{metadata:u,resource:c,authorizationCode:r,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}const h=await e.tokens();if(h?.refresh_token)try{const t=await async function(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),c=await gw(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:n,fetchFn:a});return{refresh_token:o,...c}}(i,{metadata:u,clientInformation:l,refreshToken:h.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof V_&&!(e instanceof J_))throw e}const f=e.state?await e.state():void 0,{authorizationUrl:m,codeVerifier:y}=await async function(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(iw))throw new Error(`Incompatible auth server: does not support response type ${iw}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(cw))throw new Error(`Incompatible auth server: does not support code challenge method ${cw}`)}else i=new URL("/authorize",e);const c=await p(),u=c.code_verifier,l=c.code_challenge;i.searchParams.set("response_type",iw),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",l),i.searchParams.set("code_challenge_method",cw),i.searchParams.set("redirect_uri",String(o)),s&&i.searchParams.set("state",s);n&&i.searchParams.set("scope",n);n?.includes("offline_access")&&i.searchParams.append("prompt","consent");a&&i.searchParams.set("resource",a.href);return{authorizationUrl:i,codeVerifier:u}}(i,{metadata:u,clientInformation:l,state:f,redirectUrl:e.redirectUrl,scope:o||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(y),await e.redirectToAuthorization(m),"REDIRECT"}function pw(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,o]=t.split(" ");if("bearer"!==r.toLowerCase()||!o)return{};const n=fw(e,"resource_metadata")||void 0;let s;if(n)try{s=new URL(n)}catch{}return{resourceMetadataUrl:s,scope:fw(e,"scope")||void 0,error:fw(e,"error")||void 0}}function fw(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),n=r.match(o);return n?n[1]||n[2]:null}async function mw(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?mw(e,void 0,r):void 0;throw o}}async function yw(e,t,r=fetch){const o={"MCP-Protocol-Version":t};return await mw(e,o,r)}async function gw(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:s,fetchFn:a}){const i=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),n)await n(c,r,i,t);else if(o){const e=function(e,t){const r=void 0!==e.client_secret;return 0===t.length?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&(o=e.token_endpoint_auth_method,["client_secret_basic","client_secret_post","none"].includes(o))&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none";var o}(o,t?.token_endpoint_auth_methods_supported??[]);uw(e,o,c,r)}const u=await(a??fetch)(i,{method:"POST",headers:c,body:r});if(!u.ok)throw await lw(u);return z_.parse(await u.json())}class vw extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function _w(e){}function ww(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=_w,onError:r=_w,onRetry:o=_w,onComment:n}=e;let s,a="",i=!0,c="",u="";function l(e){if(""===e)return c.length>0&&t({id:s,event:u||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),s=void 0,c="",void(u="");if(e.startsWith(":"))return void(n&&n(e.slice(e.startsWith(": ")?2:1)));const r=e.indexOf(":");if(-1!==r){const t=e.slice(0,r),o=" "===e[r+1]?2:1;return void d(t,e.slice(r+o),e)}d(e,"",e)}function d(e,t,n){switch(e){case"event":u=t;break;case"data":c=`${c}${t}\n`;break;case"id":s=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?o(parseInt(t,10)):r(new vw(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:n}));break;default:r(new vw(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:n}))}}return{feed:function(e){const t=i?e.replace(/^\xEF\xBB\xBF/,""):e,[r,o]=function(e){const t=[];let r="",o=0;for(;o<e.length;){const n=e.indexOf("\r",o),s=e.indexOf("\n",o);let a=-1;if(-1!==n&&-1!==s?a=Math.min(n,s):-1!==n?a=n:-1!==s&&(a=s),-1===a){r=e.slice(o);break}{const r=e.slice(o,a);t.push(r),o=a+1,"\r"===e[o-1]&&"\n"===e[o]&&o++}}return[t,r]}(`${a}${t}`);for(const e of r)l(e);a=o,i=!1},reset:function(e={}){a&&e.consume&&l(a),i=!0,s=void 0,c="",u="",a=""}}}class $w extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let o;super({start(n){o=ww({onEvent:e=>{n.enqueue(e)},onError(t){"terminate"===e?n.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:r})},transform(e){o.feed(e)}})}}const bw={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class kw extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class Ew{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=function(e=fetch,t){return t?async(r,o)=>{const n={...t,...o,headers:o?.headers?{...x_(t.headers),...x_(o.headers)}:t.headers};return e(r,n)}:e}(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??bw}async _authThenStart(){if(!this._authProvider)throw new aw("No auth provider");let e;try{e=await dw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new aw;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=x_(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){const{resumptionToken:t}=e;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);const o=await(this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!o.ok){if(await(o.body?.cancel()),401===o.status&&this._authProvider)return await this._authThenStart();if(405===o.status)return;throw new kw(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(void 0!==this._serverRetryMs)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){const r=this._reconnectionOptions.maxRetries;if(t>=r)return void this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));const o=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},o)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:o,replayMessageId:n}=t;let s,a=!1,i=!1;(async()=>{try{const t=e.pipeThrough(new TextDecoderStream).pipeThrough(new $w({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){const{value:e,done:r}=await t.read();if(r)break;if(e.id&&(s=e.id,a=!0,o?.(e.id)),e.data&&(!e.event||"message"===e.event))try{const t=Ss.parse(JSON.parse(e.data));bs(t)&&(i=!0,void 0!==n&&(t.id=n)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(r||a)&&!i&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:n},0)}catch(e){this.onerror?.(new Error(`SSE stream disconnected: ${e}`));if((r||a)&&!i&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:n},0)}catch(e){this.onerror?.(new Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new aw("No auth provider");if("AUTHORIZED"!==await dw(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new aw("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{const{resumptionToken:o,onresumptiontoken:n}=t||{};if(o)return void this._startOrAuthSse({resumptionToken:o,replayMessageId:_s(e)?e.id:void 0}).catch(e=>this.onerror?.(e));const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),c=i.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!i.ok){const t=await i.text().catch(()=>null);if(401===i.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new kw(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:t,scope:r}=pw(i);this._resourceMetadataUrl=t,this._scope=r;if("AUTHORIZED"!==await dw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new aw;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===i.status&&this._authProvider){const{resourceMetadataUrl:t,scope:r,error:o}=pw(i);if("insufficient_scope"===o){const o=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===o)throw new kw(403,"Server returned 403 after trying upscoping");r&&(this._scope=r),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=o??void 0;if("AUTHORIZED"!==await dw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch}))throw new aw;return this.send(e)}}throw new kw(i.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===i.status)return await(i.body?.cancel()),r=e,void(Fs.safeParse(r).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e)));const u=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,l=i.headers.get("content-type");if(u)if(l?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:n},!1);else{if(!l?.includes("application/json"))throw await(i.body?.cancel()),new kw(-1,`Unexpected content type: ${l}`);{const e=await i.json(),t=Array.isArray(e)?e.map(e=>Ss.parse(e)):[Ss.parse(e)];for(const e of t)this.onmessage?.(e)}}else await(i.body?.cancel())}catch(e){throw this.onerror?.(e),e}var r}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._url,t);if(await(r.body?.cancel()),!r.ok&&405!==r.status)throw new kw(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}const Sw=H("quickstart");async function Pw(t={}){if(!R)throw new Error("Interactive login is only available in Node.js environment");Sw.info("Starting interactive login flow");const r=M();let o;o=t.authIssuer?t.authIssuer:t.authDomain?t.authDomain.startsWith("http")?t.authDomain:`https://${t.authDomain}`:r.authIssuer;const{clientId:n=r.clientId,clientSecret:s=r.clientSecret,audience:a=r.apiAudience,baseUrl:i,port:c=52765}=t;if(!n||!s)throw new Error("AGENT_CLIENT_ID / AGENT_CLIENT_SECRET not set – create a .env file or export in the shell");const u=await he();if(u)try{let e;q(u)?e=D(u):(Sw.warn("Cached token has no organization information, using static config"),e=M());const t=new be(e.baseUrl,{token:u});return await t.validateCachedToken(),Sw.info("Using cached valid token"),t}catch(e){Sw.info("Cached token invalid, starting OAuth flow")}else Sw.info("No cached token, starting OAuth flow");const l="undefined"!=typeof process&&!(!process.env||"1"!==process.env.BARNDOOR_MANUAL_CODE&&"true"!==process.env.BARNDOOR_MANUAL_CODE);let p,f=null;if(l){const e=process.env&&process.env.BARNDOOR_REDIRECT_HOST||"127.0.0.1";p=e.startsWith("http")?`${e}:${c}/cb`:`http://${e}:${c}/cb`}else{const e=$e(c);p=e[0],f=e[1]}const m=new ve,y=await m.buildAuthorizationUrl({clientId:n,redirectUri:p,audience:a,issuer:o});Sw.info(`Auth URL: ${y}`);const g=e.platform();let v,_;try{v=new URL(y)}catch{throw new Error("Invalid auth URL")}if("https:"!==v.protocol&&("http:"!==v.protocol||"localhost"!==v.hostname&&"127.0.0.1"!==v.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===g?d("open",[y],{detached:!0,stdio:"ignore"}).unref():"win32"===g?d("powershell",["-NoProfile","Start-Process",y],{detached:!0,stdio:"ignore"}).unref():d("xdg-open",[y],{detached:!0,stdio:"ignore"}).unref(),Sw.info("Please complete login in your browser…")}catch(e){Sw.warn("Failed to open browser automatically. Please visit:",y)}if(l){const e=await new Promise(e=>{const t=h.createInterface({input:process.stdin,output:process.stdout});t.question("Paste the full redirected URL (or just the code= value): ",r=>{t.close(),e(r.trim())})});try{const t=new URL(e);_=t.searchParams.get("code")||e}catch{_=e}}else{const e=new Promise((e,t)=>{setTimeout(()=>{t(new Error(`OAuth callback timeout after 2 minutes. This usually means the callback URL is not registered in Auth0. Please add "${p}" to Allowed Callback URLs in your Auth0 application settings.`))},12e4)});_=(await Promise.race([f,e]))[0]}const w=await m.exchangeCodeForToken({clientId:n,clientSecret:s,code:_,redirectUri:p,issuer:o});let $;if(await pe(w),i)$=i;else if(q(w.access_token)){$=D(w.access_token).baseUrl}else Sw.warn("New token has no organization information, using static config"),$=M().baseUrl;return new be($,{token:w.access_token})}async function Tw(e,t,r={}){const{timeout:o=90}=r;Sw.info(`Ensuring ${t} server is connected`);try{await e.ensureServerConnected(t,{pollSeconds:o}),Sw.info(`Server ${t} connected successfully`)}catch(e){throw e instanceof b?Sw.error(`Server '${t}' not found`):Sw.error(`Failed to connect to ${t}:`,e),e}}async function Iw(e,t,r={}){const{serverId:o,serverSlug:n,proxyBaseUrl:s="http://proxy-ingress:8080",transport:a="streamable-http"}=r,i=o||n||t;let c;try{c=await e.getServer(i)}catch(e){if(e instanceof $&&404===e.statusCode)throw new b(i);throw e}const u=c.slug||i;let l;if(q(e.token)){l=`${D(e.token).baseUrl}/mcp/${u}`}else{Sw.warn("Token has no organization information, using static config for MCP connection");l=`${M().baseUrl}/mcp/${u}`}return[{url:l,transport:a,headers:{Accept:"application/json, text/event-stream",Authorization:`Bearer ${e.token}`,"x-barndoor-session-id":Nw()}},l]}async function xw(e,t,r={}){const[o]=await Iw(e,t,r),n=o,s=new I_({name:"barndoor-js-sdk",version:"0.1.0"}),a=new Ew(new URL(n.url),{requestInit:{headers:n.headers}});return await s.connect(a),s}function Nw(){if(R&&"function"==typeof i.randomUUID)return i.randomUUID();if("undefined"!=typeof globalThis&&globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e;if(R&&"function"==typeof i.randomBytes)e=i.randomBytes(16);else{if("undefined"==typeof globalThis||!globalThis.crypto?.getRandomValues)throw new Error("Secure random generator not available for UUID.");e=new Uint8Array(16),globalThis.crypto.getRandomValues(e)}const t=e??new Uint8Array(0);if(t.length<16)throw new Error("Secure random generator not available for UUID.");const r=t[6],o=t[8];t[6]=15&r|64,t[8]=63&o|128;const n=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${n.substring(0,8)}-${n.substring(8,12)}-${n.substring(12,16)}-${n.substring(16,20)}-${n.substring(20)}`}const Cw=function(){try{if("undefined"!=typeof process&&process.versions?.node){const e=l(import.meta.url),t=r(e),n=o(t,"..","package.json");return JSON.parse(f(n,"utf8")).version}return'"0.4.3"'}catch(e){return console.warn("Could not read version from package.json:",e),"0.1.0"}}();export{C as AUTH_CONFIG,N as AgentToken,y as AuthenticationError,z as BarndoorConfig,m as BarndoorError,be as BarndoorSDK,E as ConfigurationError,w as ConnectionError,$ as HTTPError,re as JWTVerificationResult,k as OAuthError,ve as PKCEManager,x as ServerDetail,b as ServerNotFoundError,I as ServerSummary,S as TimeoutError,g as TokenError,v as TokenExpiredError,de as TokenManager,_ as TokenValidationError,U as checkTokenOrganization,fe as clearCachedToken,Y as clearOidcConfigCache,H as createScopedLogger,K as debug,Tw as ensureServerConnected,B as error,D as getDynamicConfig,L as getLogger,Q as getOidcConfig,M as getStaticConfig,q as hasOrganizationInfo,Z as info,j as isBrowser,R as isNode,me as isTokenActive,ye as isTokenActiveWithRefresh,he as loadUserToken,Pw as loginInteractive,xw as makeMcpClient,Iw as makeMcpConnectionParams,pe as saveUserToken,F as setLogger,X as setTokenLogger,$e as startLocalCallbackServer,ge as validateToken,ue as verifyJWTLocal,Cw as version,G as warn};
13
+ deps: ${o}}`};const n={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const o in e){if("__proto__"===o)continue;(Array.isArray(e[o])?t:r)[o]=e[o]}return[t,r]}(e);s(e,t),a(e,r)}};function s(e,r=e.schema){const{gen:n,data:s,it:a}=e;if(0===Object.keys(r).length)return;const i=n.let("missing");for(const c in r){const u=r[c];if(0===u.length)continue;const l=(0,o.propertyInData)(n,s,c,a.opts.ownProperties);e.setParams({property:c,depsCount:u.length,deps:u.join(", ")}),a.allErrors?n.if(l,()=>{for(const t of u)(0,o.checkReportMissingProp)(e,t)}):(n.if(t._`${l} && (${(0,o.checkMissingProp)(e,u,i)})`),(0,o.reportMissingProp)(e,i),n.else())}}function a(e,t=e.schema){const{gen:n,data:s,keyword:a,it:i}=e,c=n.name("valid");for(const u in t)(0,r.alwaysValidSchema)(i,t[u])||(n.if((0,o.propertyInData)(n,s,u,i.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:u},c);e.mergeValidEvaluated(t,c)},()=>n.var(c,!0)),e.ok(c))}e.validatePropertyDeps=s,e.validateSchemaDeps=a,e.default=n}(Gg);var Bg={};Object.defineProperty(Bg,"__esModule",{value:!0});const Jg=lf,Wg=pf,Qg={message:"property name must be valid",params:({params:e})=>Jg._`{propertyName: ${e.propertyName}}`},Yg={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Qg,code(e){const{gen:t,schema:r,data:o,it:n}=e;if((0,Wg.alwaysValidSchema)(n,r))return;const s=t.name("valid");t.forIn("key",o,r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},s),t.if((0,Jg.not)(s),()=>{e.error(!0),n.allErrors||t.break()})}),e.ok(s)}};Bg.default=Yg;var Xg={};Object.defineProperty(Xg,"__esModule",{value:!0});const ev=rm(),tv=lf,rv=Nf(),ov=pf,nv={message:"must NOT have additional properties",params:({params:e})=>tv._`{additionalProperty: ${e.additionalProperty}}`},sv={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:nv,code(e){const{gen:t,schema:r,parentSchema:o,data:n,errsCount:s,it:a}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:i,opts:c}=a;if(a.props=!0,"all"!==c.removeAdditional&&(0,ov.alwaysValidSchema)(a,r))return;const u=(0,ev.allSchemaProperties)(o.properties),l=(0,ev.allSchemaProperties)(o.patternProperties);function d(e){t.code(tv._`delete ${n}[${e}]`)}function h(o){if("all"===c.removeAdditional||c.removeAdditional&&!1===r)d(o);else{if(!1===r)return e.setParams({additionalProperty:o}),e.error(),void(i||t.break());if("object"==typeof r&&!(0,ov.alwaysValidSchema)(a,r)){const r=t.name("valid");"failing"===c.removeAdditional?(p(o,r,!1),t.if((0,tv.not)(r),()=>{e.reset(),d(o)})):(p(o,r),i||t.if((0,tv.not)(r),()=>t.break()))}}}function p(t,r,o){const n={keyword:"additionalProperties",dataProp:t,dataPropType:ov.Type.Str};!1===o&&Object.assign(n,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(n,r)}t.forIn("key",n,r=>{u.length||l.length?t.if(function(r){let n;if(u.length>8){const e=(0,ov.schemaRefOrVal)(a,o.properties,"properties");n=(0,ev.isOwnProperty)(t,e,r)}else n=u.length?(0,tv.or)(...u.map(e=>tv._`${r} === ${e}`)):tv.nil;return l.length&&(n=(0,tv.or)(n,...l.map(t=>tv._`${(0,ev.usePattern)(e,t)}.test(${r})`))),(0,tv.not)(n)}(r),()=>h(r)):h(r)}),e.ok(tv._`${s} === ${rv.default.errors}`)}};Xg.default=sv;var av={};Object.defineProperty(av,"__esModule",{value:!0});const iv=Sm(),cv=rm(),uv=pf,lv=Xg,dv={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:o,data:n,it:s}=e;"all"===s.opts.removeAdditional&&void 0===o.additionalProperties&&lv.default.code(new iv.KeywordCxt(s,lv.default,"additionalProperties"));const a=(0,cv.allSchemaProperties)(r);for(const e of a)s.definedProperties.add(e);s.opts.unevaluated&&a.length&&!0!==s.props&&(s.props=uv.mergeEvaluated.props(t,(0,uv.toHash)(a),s.props));const i=a.filter(e=>!(0,uv.alwaysValidSchema)(s,r[e]));if(0===i.length)return;const c=t.name("valid");for(const r of i)u(r)?l(r):(t.if((0,cv.propertyInData)(t,n,r,s.opts.ownProperties)),l(r),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(r),e.ok(c);function u(e){return s.opts.useDefaults&&!s.compositeRule&&void 0!==r[e].default}function l(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},c)}}};av.default=dv;var hv={};Object.defineProperty(hv,"__esModule",{value:!0});const pv=rm(),fv=lf,mv=pf,yv=pf,gv={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:o,parentSchema:n,it:s}=e,{opts:a}=s,i=(0,pv.allSchemaProperties)(r),c=i.filter(e=>(0,mv.alwaysValidSchema)(s,r[e]));if(0===i.length||c.length===i.length&&(!s.opts.unevaluated||!0===s.props))return;const u=a.strictSchema&&!a.allowMatchingProperties&&n.properties,l=t.name("valid");!0===s.props||s.props instanceof fv.Name||(s.props=(0,yv.evaluatedPropsToName)(t,s.props));const{props:d}=s;function h(e){for(const t in u)new RegExp(e).test(t)&&(0,mv.checkStrictMode)(s,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function p(r){t.forIn("key",o,o=>{t.if(fv._`${(0,pv.usePattern)(e,r)}.test(${o})`,()=>{const n=c.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:o,dataPropType:yv.Type.Str},l),s.opts.unevaluated&&!0!==d?t.assign(fv._`${d}[${o}]`,!0):n||s.allErrors||t.if((0,fv.not)(l),()=>t.break())})})}!function(){for(const e of i)u&&h(e),s.allErrors?p(e):(t.var(l,!0),p(e),t.if(l))}()}};hv.default=gv;var vv={};Object.defineProperty(vv,"__esModule",{value:!0});const _v=pf,wv={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:o}=e;if((0,_v.alwaysValidSchema)(o,r))return void e.fail();const n=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),e.failResult(n,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};vv.default=wv;var $v={};Object.defineProperty($v,"__esModule",{value:!0});const bv={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:rm().validateUnion,error:{message:"must match a schema in anyOf"}};$v.default=bv;var kv={};Object.defineProperty(kv,"__esModule",{value:!0});const Ev=lf,Sv=pf,Pv={message:"must match exactly one schema in oneOf",params:({params:e})=>Ev._`{passingSchemas: ${e.passing}}`},Tv={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Pv,code(e){const{gen:t,schema:r,parentSchema:o,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&o.discriminator)return;const s=r,a=t.let("valid",!1),i=t.let("passing",null),c=t.name("_valid");e.setParams({passing:i}),t.block(function(){s.forEach((r,o)=>{let s;(0,Sv.alwaysValidSchema)(n,r)?t.var(c,!0):s=e.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},c),o>0&&t.if(Ev._`${c} && ${a}`).assign(a,!1).assign(i,Ev._`[${i}, ${o}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(i,o),s&&e.mergeEvaluated(s,Ev.Name)})})}),e.result(a,()=>e.reset(),()=>e.error(!0))}};kv.default=Tv;var Iv={};Object.defineProperty(Iv,"__esModule",{value:!0});const xv=pf,Nv={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const n=t.name("valid");r.forEach((t,r)=>{if((0,xv.alwaysValidSchema)(o,t))return;const s=e.subschema({keyword:"allOf",schemaProp:r},n);e.ok(n),e.mergeEvaluated(s)})}};Iv.default=Nv;var Cv={};Object.defineProperty(Cv,"__esModule",{value:!0});const jv=lf,Rv=pf,Ov={message:({params:e})=>jv.str`must match "${e.ifClause}" schema`,params:({params:e})=>jv._`{failingKeyword: ${e.ifClause}}`},zv={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Ov,code(e){const{gen:t,parentSchema:r,it:o}=e;void 0===r.then&&void 0===r.else&&(0,Rv.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const n=Av(o,"then"),s=Av(o,"else");if(!n&&!s)return;const a=t.let("valid",!0),i=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);e.mergeEvaluated(t)}(),e.reset(),n&&s){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(i,c("then",r),c("else",r))}else n?t.if(i,c("then")):t.if((0,jv.not)(i),c("else"));function c(r,o){return()=>{const n=e.subschema({keyword:r},i);t.assign(a,i),e.mergeValidEvaluated(n,a),o?t.assign(o,jv._`${r}`):e.setParams({ifClause:r})}}e.pass(a,()=>e.error(!0))}};function Av(e,t){const r=e.schema[t];return void 0!==r&&!(0,Rv.alwaysValidSchema)(e,r)}Cv.default=zv;var Mv={};Object.defineProperty(Mv,"__esModule",{value:!0});const Dv=pf,Uv={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,Dv.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Mv.default=Uv,Object.defineProperty(bg,"__esModule",{value:!0});const qv=kg,Vv=Ig,Fv=xg,Lv=Mg,Hv=Lg,Kv=Gg,Zv=Bg,Gv=Xg,Bv=av,Jv=hv,Wv=vv,Qv=$v,Yv=kv,Xv=Iv,e_=Cv,t_=Mv;bg.default=function(e=!1){const t=[Wv.default,Qv.default,Yv.default,Xv.default,e_.default,t_.default,Zv.default,Gv.default,Kv.default,Bv.default,Jv.default];return e?t.push(Vv.default,Lv.default):t.push(qv.default,Fv.default),t.push(Hv.default),t};var r_={},o_={};Object.defineProperty(o_,"__esModule",{value:!0});const n_=lf,s_={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>n_.str`must match format "${e}"`,params:({schemaCode:e})=>n_._`{format: ${e}}`},code(e,t){const{gen:r,data:o,$data:n,schema:s,schemaCode:a,it:i}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=i;c.validateFormats&&(n?function(){const n=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),s=r.const("fDef",n_._`${n}[${a}]`),i=r.let("fType"),u=r.let("format");r.if(n_._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(i,n_._`${s}.type || "string"`).assign(u,n_._`${s}.validate`),()=>r.assign(i,n_._`"string"`).assign(u,s)),e.fail$data((0,n_.or)(!1===c.strictSchema?n_.nil:n_._`${a} && !${u}`,function(){const e=l.$async?n_._`(${s}.async ? await ${u}(${o}) : ${u}(${o}))`:n_._`${u}(${o})`,r=n_._`(typeof ${u} == "function" ? ${e} : ${u}.test(${o}))`;return n_._`${u} && ${u} !== true && ${i} === ${t} && !${r}`}()))}():function(){const n=d.formats[s];if(!n)return void function(){if(!1===c.strictSchema)return void d.logger.warn(e());throw new Error(e());function e(){return`unknown format "${s}" ignored in schema at path "${u}"`}}();if(!0===n)return;const[a,i,h]=function(e){const t=e instanceof RegExp?(0,n_.regexpCode)(e):c.code.formats?n_._`${c.code.formats}${(0,n_.getProperty)(s)}`:void 0,o=r.scopeValue("formats",{key:s,ref:e,code:t});if("object"==typeof e&&!(e instanceof RegExp))return[e.type||"string",e.validate,n_._`${o}.validate`];return["string",e,o]}(n);a===t&&e.pass(function(){if("object"==typeof n&&!(n instanceof RegExp)&&n.async){if(!l.$async)throw new Error("async format in sync schema");return n_._`await ${h}(${o})`}return"function"==typeof i?n_._`${h}(${o})`:n_._`${h}.test(${o})`}())}())}};o_.default=s_,Object.defineProperty(r_,"__esModule",{value:!0});const a_=[o_.default];r_.default=a_;var i_={};Object.defineProperty(i_,"__esModule",{value:!0}),i_.contentVocabulary=i_.metadataVocabulary=void 0,i_.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],i_.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(Qm,"__esModule",{value:!0});const c_=py,u_=bg,l_=r_,d_=i_,h_=[Ym.default,c_.default,(0,u_.default)(),l_.default,d_.metadataVocabulary,d_.contentVocabulary];Qm.default=h_;var p_,f_={},m_={};Object.defineProperty(m_,"__esModule",{value:!0}),m_.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(p_||(m_.DiscrError=p_={})),Object.defineProperty(f_,"__esModule",{value:!0});const y_=lf,g_=m_,v_=jm,__=Cm(),w_=pf,$_={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===g_.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>y_._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},code(e){const{gen:t,data:r,schema:o,parentSchema:n,it:s}=e,{oneOf:a}=n;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const i=o.propertyName;if("string"!=typeof i)throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");const c=t.let("valid",!1),u=t.const("tag",y_._`${r}${(0,y_.getProperty)(i)}`);function l(r){const o=t.name("valid"),n=e.subschema({keyword:"oneOf",schemaProp:r},o);return e.mergeEvaluated(n,y_.Name),o}t.if(y_._`typeof ${u} == "string"`,()=>function(){const r=function(){var e;const t={},r=c(n);let o=!0;for(let t=0;t<a.length;t++){let n=a[t];if((null==n?void 0:n.$ref)&&!(0,w_.schemaHasRulesButRef)(n,s.self.RULES)){const e=n.$ref;if(n=v_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,e),n instanceof v_.SchemaEnv&&(n=n.schema),void 0===n)throw new __.default(s.opts.uriResolver,s.baseId,e)}const l=null===(e=null==n?void 0:n.properties)||void 0===e?void 0:e[i];if("object"!=typeof l)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);o=o&&(r||c(n)),u(l,t)}if(!o)throw new Error(`discriminator: "${i}" must be required`);return t;function c({required:e}){return Array.isArray(e)&&e.includes(i)}function u(e,t){if(e.const)l(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`);for(const r of e.enum)l(r,t)}}function l(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${i}" values must be unique strings`);t[e]=r}}();t.if(!1);for(const e in r)t.elseIf(y_._`${u} === ${e}`),t.assign(c,l(r[e]));t.else(),e.error(!1,{discrError:g_.DiscrError.Mapping,tag:u,tagName:i}),t.endIf()}(),()=>e.error(!1,{discrError:g_.DiscrError.Tag,tag:u,tagName:i})),e.ok(c)}};f_.default=$_;var b_={$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:!0,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:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},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:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},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:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},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:!0};!function(e,t){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 r=sf,o=Qm,n=f_,s=b_,a=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),o.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(n.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(e,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=Sm();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=lf;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 d=Im();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var h=Cm();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return h.default}})}(nf,nf.exports);var k_=nf.exports;!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=k_,r=lf,o=r.operators,n={formatMaximum:{okStr:"<=",ok:o.LTE,fail:o.GT},formatMinimum:{okStr:">=",ok:o.GTE,fail:o.LT},formatExclusiveMaximum:{okStr:"<",ok:o.LT,fail:o.GTE},formatExclusiveMinimum:{okStr:">",ok:o.GT,fail:o.LTE}},s={message:({keyword:e,schemaCode:t})=>r.str`should be ${n[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>r._`{comparison: ${n[e].okStr}, limit: ${t}}`};e.formatLimitDefinition={keyword:Object.keys(n),type:"string",schemaType:"string",$data:!0,error:s,code(e){const{gen:o,data:s,schemaCode:a,keyword:i,it:c}=e,{opts:u,self:l}=c;if(!u.validateFormats)return;const d=new t.KeywordCxt(c,l.RULES.all.format.definition,"format");function h(e){return r._`${e}.compare(${s}, ${a}) ${n[i].fail} 0`}d.$data?function(){const t=o.scopeValue("formats",{ref:l.formats,code:u.code.formats}),n=o.const("fmt",r._`${t}[${d.schemaCode}]`);e.fail$data((0,r.or)(r._`typeof ${n} != "object"`,r._`${n} instanceof RegExp`,r._`typeof ${n}.compare != "function"`,h(n)))}():function(){const t=d.schema,n=l.formats[t];if(!n||!0===n)return;if("object"!=typeof n||n instanceof RegExp||"function"!=typeof n.compare)throw new Error(`"${i}": format "${t}" does not define "compare" function`);const s=o.scopeValue("formats",{key:t,ref:n,code:u.code.formats?r._`${u.code.formats}${(0,r.getProperty)(t)}`:void 0});e.fail$data(h(s))}()},dependencies:["format"]};e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)}(of),function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=rf,o=of,n=lf,s=new n.Name("fullFormats"),a=new n.Name("fastFormats"),i=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,r.fullFormats,s),e;const[n,i]="fast"===t.mode?[r.fastFormats,a]:[r.fullFormats,s];return c(e,t.formats||r.formatNames,n,i),t.keywords&&(0,o.default)(e),e};function c(e,t,r,o){var s,a;null!==(s=(a=e.opts.code).formats)&&void 0!==s||(a.formats=n._`require("ajv-formats/dist/formats").${o}`);for(const o of t)e.addFormat(o,r[o])}i.get=(e,t="full")=>{const o=("fast"===t?r.fastFormats:r.fullFormats)[e];if(!o)throw new Error(`Unknown format "${e}"`);return o},e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i}(tf,tf.exports);var E_=Ji(tf.exports);class S_{constructor(e){this._ajv=e??function(){const e=new ef({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return E_(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 P_{constructor(e){this._client=e}async*callToolStream(e,t=Qa,r){const o=this._client,n={...r,task:r?.task??(o.isToolTask(e.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:e},t,n),a=o.getToolOutputValidator(e.name);for await(const t of s){if("result"===t.type&&a){const r=t.result;if(!r.structuredContent&&!r.isError)return void(yield{type:"error",error:new Fi(ks.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)});if(r.structuredContent)try{const e=a(r.structuredContent);if(!e.valid)return void(yield{type:"error",error:new Fi(ks.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)})}catch(e){return e instanceof Fi?void(yield{type:"error",error:e}):void(yield{type:"error",error:new Fi(ks.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)})}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}function T_(e,t){if(e&&null!==t&&"object"==typeof t){if("object"===e.type&&e.properties&&"object"==typeof e.properties){const r=t,o=e.properties;for(const e of Object.keys(o)){const t=o[e];void 0===r[e]&&Object.prototype.hasOwnProperty.call(t,"default")&&(r[e]=t.default),void 0!==r[e]&&T_(t,r[e])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)"boolean"!=typeof r&&T_(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)"boolean"!=typeof r&&T_(r,t)}}class I_ extends Gi{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new S_,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ei,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ka,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Ea,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new P_(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 o=e,n=t[o];if(void 0===n)continue;const s=r[o];Bi(s)&&Bi(n)?r[o]={...s,...n}:r[o]=n}return r}(this._capabilities,e)}setRequestHandler(e,t){const r=ko(e),o=r?.method;if(!o)throw new Error("Schema is missing a method literal");let n;if($o(o)){const e=o,t=e._zod?.def;n=t?.value??e.value}else{const e=o,t=e._def;n=t?.value??e.value}if("string"!=typeof n)throw new Error("Schema method literal must be a string");const s=n;if("elicitation/create"===s){const r=async(e,r)=>{const o=bo(xi,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Fi(ks.InvalidParams,`Invalid elicitation request: ${e}`)}const{params:n}=o.data;n.mode=n.mode??"form";const{supportsFormMode:s,supportsUrlMode:a}=function(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=void 0!==e.form,r=void 0!==e.url;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}(this._capabilities.elicitation);if("form"===n.mode&&!s)throw new Fi(ks.InvalidParams,"Client does not support form-mode elicitation requests");if("url"===n.mode&&!a)throw new Fi(ks.InvalidParams,"Client does not support URL-mode elicitation requests");const i=await Promise.resolve(t(e,r));if(n.task){const e=bo(Ys,i);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Fi(ks.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const c=bo(ji,i);if(!c.success){const e=c.error instanceof Error?c.error.message:String(c.error);throw new Fi(ks.InvalidParams,`Invalid elicitation result: ${e}`)}const u=c.data,l="form"===n.mode?n.requestedSchema:void 0;if("form"===n.mode&&"accept"===u.action&&u.content&&l&&this._capabilities.elicitation?.form?.applyDefaults)try{T_(l,u.content)}catch{}return u};return super.setRequestHandler(e,r)}if("sampling/createMessage"===s){const r=async(e,r)=>{const o=bo(mi,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Fi(ks.InvalidParams,`Invalid sampling request: ${e}`)}const{params:n}=o.data,s=await Promise.resolve(t(e,r));if(n.task){const e=bo(Ys,s);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Fi(ks.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const a=bo(n.tools||n.toolChoice?gi:yi,s);if(!a.success){const e=a.error instanceof Error?a.error.message:String(a.error);throw new Fi(ks.InvalidParams,`Invalid sampling result: ${e}`)}return a.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),void 0===e.sessionId)try{const r=await this.request({method:"initialize",params:{protocolVersion:es,capabilities:this._capabilities,clientInfo:this._clientInfo}},Vs,t);if(void 0===r)throw new Error(`Server sent invalid initialize result: ${r}`);if(!ts.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if("notifications/roots/list_changed"===e)if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client 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})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`)}(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&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._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Ps,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},Mi,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},Ps,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},Ha,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},Oa,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},ga,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},_a,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},ka,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},Ps,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},Ps,t)}async callTool(e,t=Qa,r){if(this.isToolTaskRequired(e.name))throw new Fi(ks.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:e},t,r),n=this.getToolOutputValidator(e.name);if(n){if(!o.structuredContent&&!o.isError)throw new Fi(ks.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const e=n(o.structuredContent);if(!e.valid)throw new Fi(ks.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){if(e instanceof Fi)throw e;throw new Fi(ks.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}isToolTask(e){return!!this._serverCapabilities?.tasks?.requests?.tools?.call&&this._cachedKnownTaskTools.has(e)}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}const e=t.execution?.taskSupport;"required"!==e&&"optional"!==e||this._cachedKnownTaskTools.add(t.name),"required"===e&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Wa,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,o){const n=ti.safeParse(r);if(!n.success)throw new Error(`Invalid ${e} listChanged options: ${n.error.message}`);if("function"!=typeof r.onChanged)throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:s,debounceMs:a}=n.data,{onChanged:i}=r,c=async()=>{if(s)try{const e=await o();i(null,e)}catch(e){const t=e instanceof Error?e:new Error(String(e));i(t,null)}else i(null,null)};this.setNotificationHandler(t,()=>{if(a){const t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);const r=setTimeout(c,a);this._listChangedDebounceTimers.set(e,r)}else c()})}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function x_(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}const N_=lo(Ko,C_).superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Xn,message:"URL must be parseable",fatal:!0}),ke}).refine(e=>{const t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"});var C_;const j_=Sn({resource:qo().url(),authorization_servers:bn(N_).optional(),jwks_uri:qo().url().optional(),scopes_supported:bn(qo()).optional(),bearer_methods_supported:bn(qo()).optional(),resource_signing_alg_values_supported:bn(qo()).optional(),resource_name:qo().optional(),resource_documentation:qo().optional(),resource_policy_uri:qo().url().optional(),resource_tos_uri:qo().url().optional(),tls_client_certificate_bound_access_tokens:pn().optional(),authorization_details_types_supported:bn(qo()).optional(),dpop_signing_alg_values_supported:bn(qo()).optional(),dpop_bound_access_tokens_required:pn().optional()}),R_=Sn({issuer:qo(),authorization_endpoint:N_,token_endpoint:N_,registration_endpoint:N_.optional(),scopes_supported:bn(qo()).optional(),response_types_supported:bn(qo()),response_modes_supported:bn(qo()).optional(),grant_types_supported:bn(qo()).optional(),token_endpoint_auth_methods_supported:bn(qo()).optional(),token_endpoint_auth_signing_alg_values_supported:bn(qo()).optional(),service_documentation:N_.optional(),revocation_endpoint:N_.optional(),revocation_endpoint_auth_methods_supported:bn(qo()).optional(),revocation_endpoint_auth_signing_alg_values_supported:bn(qo()).optional(),introspection_endpoint:qo().optional(),introspection_endpoint_auth_methods_supported:bn(qo()).optional(),introspection_endpoint_auth_signing_alg_values_supported:bn(qo()).optional(),code_challenge_methods_supported:bn(qo()).optional(),client_id_metadata_document_supported:pn().optional()}),O_=En({...Sn({issuer:qo(),authorization_endpoint:N_,token_endpoint:N_,userinfo_endpoint:N_.optional(),jwks_uri:N_,registration_endpoint:N_.optional(),scopes_supported:bn(qo()).optional(),response_types_supported:bn(qo()),response_modes_supported:bn(qo()).optional(),grant_types_supported:bn(qo()).optional(),acr_values_supported:bn(qo()).optional(),subject_types_supported:bn(qo()),id_token_signing_alg_values_supported:bn(qo()),id_token_encryption_alg_values_supported:bn(qo()).optional(),id_token_encryption_enc_values_supported:bn(qo()).optional(),userinfo_signing_alg_values_supported:bn(qo()).optional(),userinfo_encryption_alg_values_supported:bn(qo()).optional(),userinfo_encryption_enc_values_supported:bn(qo()).optional(),request_object_signing_alg_values_supported:bn(qo()).optional(),request_object_encryption_alg_values_supported:bn(qo()).optional(),request_object_encryption_enc_values_supported:bn(qo()).optional(),token_endpoint_auth_methods_supported:bn(qo()).optional(),token_endpoint_auth_signing_alg_values_supported:bn(qo()).optional(),display_values_supported:bn(qo()).optional(),claim_types_supported:bn(qo()).optional(),claims_supported:bn(qo()).optional(),service_documentation:qo().optional(),claims_locales_supported:bn(qo()).optional(),ui_locales_supported:bn(qo()).optional(),claims_parameter_supported:pn().optional(),request_parameter_supported:pn().optional(),request_uri_parameter_supported:pn().optional(),require_request_uri_registration:pn().optional(),op_policy_uri:N_.optional(),op_tos_uri:N_.optional(),client_id_metadata_document_supported:pn().optional()}).shape,...R_.pick({code_challenge_methods_supported:!0}).shape}),z_=En({access_token:qo(),id_token:qo().optional(),token_type:qo(),expires_in:function(e){return function(e,t){return new e({type:"number",coerce:!0,checks:[],...Fe(t)})}(cn,e)}().optional(),scope:qo().optional(),refresh_token:qo().optional()}).strip(),A_=En({error:qo(),error_description:qo().optional(),error_uri:qo().optional()}),M_=N_.optional().or(Mn("").transform(()=>{})),D_=En({redirect_uris:bn(N_),token_endpoint_auth_method:qo().optional(),grant_types:bn(qo()).optional(),response_types:bn(qo()).optional(),client_name:qo().optional(),client_uri:N_.optional(),logo_uri:M_,scope:qo().optional(),contacts:bn(qo()).optional(),tos_uri:M_,policy_uri:qo().optional(),jwks_uri:N_.optional(),jwks:new yn({type:"any"}).optional(),software_id:qo().optional(),software_version:qo().optional(),software_statement:qo().optional()}).strip(),U_=En({client_id:qo(),client_secret:qo().optional(),client_id_issued_at:un().optional(),client_secret_expires_at:un().optional()}).strip(),q_=D_.merge(U_);En({error:qo(),error_description:qo().optional()}).strip(),En({token:qo(),token_type_hint:qo().optional()}).strip();class V_ extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class F_ extends V_{}F_.errorCode="invalid_request";class L_ extends V_{}L_.errorCode="invalid_client";class H_ extends V_{}H_.errorCode="invalid_grant";class K_ extends V_{}K_.errorCode="unauthorized_client";class Z_ extends V_{}Z_.errorCode="unsupported_grant_type";class G_ extends V_{}G_.errorCode="invalid_scope";class B_ extends V_{}B_.errorCode="access_denied";class J_ extends V_{}J_.errorCode="server_error";class W_ extends V_{}W_.errorCode="temporarily_unavailable";class Q_ extends V_{}Q_.errorCode="unsupported_response_type";class Y_ extends V_{}Y_.errorCode="unsupported_token_type";class X_ extends V_{}X_.errorCode="invalid_token";class ew extends V_{}ew.errorCode="method_not_allowed";class tw extends V_{}tw.errorCode="too_many_requests";class rw extends V_{}rw.errorCode="invalid_client_metadata";class ow extends V_{}ow.errorCode="insufficient_scope";class nw extends V_{}nw.errorCode="invalid_target";const sw={[F_.errorCode]:F_,[L_.errorCode]:L_,[H_.errorCode]:H_,[K_.errorCode]:K_,[Z_.errorCode]:Z_,[G_.errorCode]:G_,[B_.errorCode]:B_,[J_.errorCode]:J_,[W_.errorCode]:W_,[Q_.errorCode]:Q_,[Y_.errorCode]:Y_,[X_.errorCode]:X_,[ew.errorCode]:ew,[tw.errorCode]:tw,[rw.errorCode]:rw,[ow.errorCode]:ow,[nw.errorCode]:nw};class aw extends Error{constructor(e){super(e??"Unauthorized")}}const iw="code",cw="S256";function uw(e,t,r,o){const{client_id:n,client_secret:s}=t;switch(e){case"client_secret_basic":return void function(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}(n,s,r);case"client_secret_post":return void function(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}(n,s,o);case"none":return void function(e,t){t.set("client_id",e)}(n,o);default:throw new Error(`Unsupported client authentication method: ${e}`)}}async function lw(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=A_.parse(JSON.parse(r)),{error:t,error_description:o,error_uri:n}=e;return new(sw[t]||J_)(o||"",n)}catch(e){return new J_(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function dw(e,t){try{return await hw(e,t)}catch(r){if(r instanceof L_||r instanceof K_)return await(e.invalidateCredentials?.("all")),await hw(e,t);if(r instanceof H_)return await(e.invalidateCredentials?.("tokens")),await hw(e,t);throw r}}async function hw(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:n,fetchFn:s}){let a,i;try{a=await async function(e,t,r=fetch){const o=await async function(e,t,r,o){const n=new URL(e),s=o?.protocolVersion??es;let a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{const e=function(e,t="",r={}){t.endsWith("/")&&(t=t.slice(0,-1));return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,n.pathname);a=new URL(e,o?.metadataServerUrl??n),a.search=n.search}let i=await yw(a,s,r);if(!o?.metadataUrl&&function(e,t){return!e||e.status>=400&&e.status<500&&"/"!==t}(i,n.pathname)){const e=new URL(`/.well-known/${t}`,n);i=await yw(e,s,r)}return i}(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||404===o.status)throw await(o?.body?.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await(o.body?.cancel()),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return j_.parse(await o.json())}(t,{resourceMetadataUrl:n},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",t));const c=await async function(e,t,r){const o=function(e){const t="string"==typeof e?new URL(e):new URL(e.href);return t.hash="",t}(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!function({requestedResource:e,configuredResource:t}){const r="string"==typeof e?new URL(e):new URL(e.href),o="string"==typeof t?new URL(t):new URL(t.href);if(r.origin!==o.origin)return!1;if(r.pathname.length<o.pathname.length)return!1;const n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(s)}({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}(t,e,a),u=await async function(e,{fetchFn:t=fetch,protocolVersion:r=es}={}){const o={"MCP-Protocol-Version":r,Accept:"application/json"},n=function(e){const t="string"==typeof e?new URL(e):e,r="/"!==t.pathname,o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;n.endsWith("/")&&(n=n.slice(0,-1));return o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"}),o.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}(e);for(const{url:e,type:r}of n){const n=await mw(e,o,t);if(n){if(!n.ok){if(await(n.body?.cancel()),n.status>=400&&n.status<500)continue;throw new Error(`HTTP ${n.status} trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`)}return"oauth"===r?R_.parse(await n.json()):O_.parse(await n.json())}}return}(i,{fetchFn:s});let l=await Promise.resolve(e.clientInformation());if(!l){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const t=!0===u?.client_id_metadata_document_supported,o=e.clientMetadataUrl;if(o&&!function(e){if(!e)return!1;try{const t=new URL(e);return"https:"===t.protocol&&"/"!==t.pathname}catch{return!1}}(o))throw new rw(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${o}`);if(t&&o)l={client_id:o},await(e.saveClientInformation?.(l));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const t=await async function(e,{metadata:t,clientMetadata:r,fetchFn:o}){let n;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(t.registration_endpoint)}else n=new URL("/register",e);const s=await(o??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await lw(s);return q_.parse(await s.json())}(i,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(t),l=t}}const d=!e.redirectUrl;if(void 0!==r||d){const t=await async function(e,t,{metadata:r,resource:o,authorizationCode:n,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a));if(!i){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");i=function(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}(n,await e.codeVerifier(),e.redirectUrl)}const c=await e.clientInformation();return gw(t,{metadata:r,tokenRequestParams:i,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:s})}(e,i,{metadata:u,resource:c,authorizationCode:r,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}const h=await e.tokens();if(h?.refresh_token)try{const t=await async function(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),c=await gw(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:n,fetchFn:a});return{refresh_token:o,...c}}(i,{metadata:u,clientInformation:l,refreshToken:h.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof V_&&!(e instanceof J_))throw e}const f=e.state?await e.state():void 0,{authorizationUrl:m,codeVerifier:y}=await async function(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(iw))throw new Error(`Incompatible auth server: does not support response type ${iw}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(cw))throw new Error(`Incompatible auth server: does not support code challenge method ${cw}`)}else i=new URL("/authorize",e);const c=await p(),u=c.code_verifier,l=c.code_challenge;i.searchParams.set("response_type",iw),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",l),i.searchParams.set("code_challenge_method",cw),i.searchParams.set("redirect_uri",String(o)),s&&i.searchParams.set("state",s);n&&i.searchParams.set("scope",n);n?.includes("offline_access")&&i.searchParams.append("prompt","consent");a&&i.searchParams.set("resource",a.href);return{authorizationUrl:i,codeVerifier:u}}(i,{metadata:u,clientInformation:l,state:f,redirectUrl:e.redirectUrl,scope:o||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(y),await e.redirectToAuthorization(m),"REDIRECT"}function pw(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,o]=t.split(" ");if("bearer"!==r.toLowerCase()||!o)return{};const n=fw(e,"resource_metadata")||void 0;let s;if(n)try{s=new URL(n)}catch{}return{resourceMetadataUrl:s,scope:fw(e,"scope")||void 0,error:fw(e,"error")||void 0}}function fw(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),n=r.match(o);return n?n[1]||n[2]:null}async function mw(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?mw(e,void 0,r):void 0;throw o}}async function yw(e,t,r=fetch){const o={"MCP-Protocol-Version":t};return await mw(e,o,r)}async function gw(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:s,fetchFn:a}){const i=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),n)await n(c,r,i,t);else if(o){const e=function(e,t){const r=void 0!==e.client_secret;return 0===t.length?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&(o=e.token_endpoint_auth_method,["client_secret_basic","client_secret_post","none"].includes(o))&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none";var o}(o,t?.token_endpoint_auth_methods_supported??[]);uw(e,o,c,r)}const u=await(a??fetch)(i,{method:"POST",headers:c,body:r});if(!u.ok)throw await lw(u);return z_.parse(await u.json())}class vw extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function _w(e){}function ww(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=_w,onError:r=_w,onRetry:o=_w,onComment:n}=e;let s,a="",i=!0,c="",u="";function l(e){if(""===e)return c.length>0&&t({id:s,event:u||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),s=void 0,c="",void(u="");if(e.startsWith(":"))return void(n&&n(e.slice(e.startsWith(": ")?2:1)));const r=e.indexOf(":");if(-1!==r){const t=e.slice(0,r),o=" "===e[r+1]?2:1;return void d(t,e.slice(r+o),e)}d(e,"",e)}function d(e,t,n){switch(e){case"event":u=t;break;case"data":c=`${c}${t}\n`;break;case"id":s=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?o(parseInt(t,10)):r(new vw(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:n}));break;default:r(new vw(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:n}))}}return{feed:function(e){const t=i?e.replace(/^\xEF\xBB\xBF/,""):e,[r,o]=function(e){const t=[];let r="",o=0;for(;o<e.length;){const n=e.indexOf("\r",o),s=e.indexOf("\n",o);let a=-1;if(-1!==n&&-1!==s?a=Math.min(n,s):-1!==n?a=n:-1!==s&&(a=s),-1===a){r=e.slice(o);break}{const r=e.slice(o,a);t.push(r),o=a+1,"\r"===e[o-1]&&"\n"===e[o]&&o++}}return[t,r]}(`${a}${t}`);for(const e of r)l(e);a=o,i=!1},reset:function(e={}){a&&e.consume&&l(a),i=!0,s=void 0,c="",u="",a=""}}}class $w extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let o;super({start(n){o=ww({onEvent:e=>{n.enqueue(e)},onError(t){"terminate"===e?n.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:r})},transform(e){o.feed(e)}})}}const bw={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class kw extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class Ew{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=function(e=fetch,t){return t?async(r,o)=>{const n={...t,...o,headers:o?.headers?{...x_(t.headers),...x_(o.headers)}:t.headers};return e(r,n)}:e}(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??bw}async _authThenStart(){if(!this._authProvider)throw new aw("No auth provider");let e;try{e=await dw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new aw;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=x_(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){const{resumptionToken:t}=e;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);const o=await(this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!o.ok){if(await(o.body?.cancel()),401===o.status&&this._authProvider)return await this._authThenStart();if(405===o.status)return;throw new kw(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(void 0!==this._serverRetryMs)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){const r=this._reconnectionOptions.maxRetries;if(t>=r)return void this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));const o=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},o)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:o,replayMessageId:n}=t;let s,a=!1,i=!1;(async()=>{try{const t=e.pipeThrough(new TextDecoderStream).pipeThrough(new $w({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){const{value:e,done:r}=await t.read();if(r)break;if(e.id&&(s=e.id,a=!0,o?.(e.id)),e.data&&(!e.event||"message"===e.event))try{const t=Ss.parse(JSON.parse(e.data));bs(t)&&(i=!0,void 0!==n&&(t.id=n)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(r||a)&&!i&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:n},0)}catch(e){this.onerror?.(new Error(`SSE stream disconnected: ${e}`));if((r||a)&&!i&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:n},0)}catch(e){this.onerror?.(new Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new aw("No auth provider");if("AUTHORIZED"!==await dw(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new aw("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{const{resumptionToken:o,onresumptiontoken:n}=t||{};if(o)return void this._startOrAuthSse({resumptionToken:o,replayMessageId:_s(e)?e.id:void 0}).catch(e=>this.onerror?.(e));const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),c=i.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!i.ok){const t=await i.text().catch(()=>null);if(401===i.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new kw(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:t,scope:r}=pw(i);this._resourceMetadataUrl=t,this._scope=r;if("AUTHORIZED"!==await dw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new aw;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===i.status&&this._authProvider){const{resourceMetadataUrl:t,scope:r,error:o}=pw(i);if("insufficient_scope"===o){const o=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===o)throw new kw(403,"Server returned 403 after trying upscoping");r&&(this._scope=r),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=o??void 0;if("AUTHORIZED"!==await dw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch}))throw new aw;return this.send(e)}}throw new kw(i.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===i.status)return await(i.body?.cancel()),r=e,void(Fs.safeParse(r).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e)));const u=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,l=i.headers.get("content-type");if(u)if(l?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:n},!1);else{if(!l?.includes("application/json"))throw await(i.body?.cancel()),new kw(-1,`Unexpected content type: ${l}`);{const e=await i.json(),t=Array.isArray(e)?e.map(e=>Ss.parse(e)):[Ss.parse(e)];for(const e of t)this.onmessage?.(e)}}else await(i.body?.cancel())}catch(e){throw this.onerror?.(e),e}var r}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._url,t);if(await(r.body?.cancel()),!r.ok&&405!==r.status)throw new kw(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}const Sw=H("quickstart");async function Pw(t={}){if(!R)throw new Error("Interactive login is only available in Node.js environment");Sw.info("Starting interactive login flow");const r=M();let o;o=t.authIssuer?t.authIssuer:t.authDomain?t.authDomain.startsWith("http")?t.authDomain:`https://${t.authDomain}`:r.authIssuer;const{clientId:n=r.clientId,clientSecret:s=r.clientSecret,audience:a=r.apiAudience,baseUrl:i,port:c=52765}=t;if(!n||!s)throw new Error("AGENT_CLIENT_ID / AGENT_CLIENT_SECRET not set – create a .env file or export in the shell");const u=await he();if(u)try{let e;q(u)?e=D(u):(Sw.warn("Cached token has no organization information, using static config"),e=M());const t=new be(e.baseUrl,{token:u});return await t.validateCachedToken(),Sw.info("Using cached valid token"),t}catch(e){Sw.info("Cached token invalid, starting OAuth flow")}else Sw.info("No cached token, starting OAuth flow");const l="undefined"!=typeof process&&!(!process.env||"1"!==process.env.BARNDOOR_MANUAL_CODE&&"true"!==process.env.BARNDOOR_MANUAL_CODE);let p,f=null;if(l){const e=process.env&&process.env.BARNDOOR_REDIRECT_HOST||"127.0.0.1";p=e.startsWith("http")?`${e}:${c}/cb`:`http://${e}:${c}/cb`}else{const e=$e(c);p=e[0],f=e[1]}const m=new ve,y=await m.buildAuthorizationUrl({clientId:n,redirectUri:p,audience:a,issuer:o});Sw.info(`Auth URL: ${y}`);const g=e.platform();let v,_;try{v=new URL(y)}catch{throw new Error("Invalid auth URL")}if("https:"!==v.protocol&&("http:"!==v.protocol||"localhost"!==v.hostname&&"127.0.0.1"!==v.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===g?d("open",[y],{detached:!0,stdio:"ignore"}).unref():"win32"===g?d("powershell",["-NoProfile","Start-Process",y],{detached:!0,stdio:"ignore"}).unref():d("xdg-open",[y],{detached:!0,stdio:"ignore"}).unref(),Sw.info("Please complete login in your browser…")}catch(e){Sw.warn("Failed to open browser automatically. Please visit:",y)}if(l){const e=await new Promise(e=>{const t=h.createInterface({input:process.stdin,output:process.stdout});t.question("Paste the full redirected URL (or just the code= value): ",r=>{t.close(),e(r.trim())})});try{const t=new URL(e);_=t.searchParams.get("code")||e}catch{_=e}}else{const e=new Promise((e,t)=>{setTimeout(()=>{t(new Error(`OAuth callback timeout after 2 minutes. This usually means the callback URL is not registered in Auth0. Please add "${p}" to Allowed Callback URLs in your Auth0 application settings.`))},12e4)});_=(await Promise.race([f,e]))[0]}const w=await m.exchangeCodeForToken({clientId:n,clientSecret:s,code:_,redirectUri:p,issuer:o});let $;if(await pe(w),i)$=i;else if(q(w.access_token)){$=D(w.access_token).baseUrl}else Sw.warn("New token has no organization information, using static config"),$=M().baseUrl;return new be($,{token:w.access_token})}async function Tw(e,t,r={}){const{timeout:o=90}=r;Sw.info(`Ensuring ${t} server is connected`);try{await e.ensureServerConnected(t,{pollSeconds:o}),Sw.info(`Server ${t} connected successfully`)}catch(e){throw e instanceof b?Sw.error(`Server '${t}' not found`):Sw.error(`Failed to connect to ${t}:`,e),e}}async function Iw(e,t,r={}){const{serverId:o,serverSlug:n,proxyBaseUrl:s="http://proxy-ingress:8080",transport:a="streamable-http"}=r,i=o||n||t;let c;try{c=await e.getServer(i)}catch(e){if(e instanceof $&&404===e.statusCode)throw new b(i);throw e}const u=c.slug||i;let l;if(q(e.token)){l=`${D(e.token).baseUrl}/mcp/${u}`}else{Sw.warn("Token has no organization information, using static config for MCP connection");l=`${M().baseUrl}/mcp/${u}`}return[{url:l,transport:a,headers:{Accept:"application/json, text/event-stream",Authorization:`Bearer ${e.token}`,"x-barndoor-session-id":Nw()}},l]}async function xw(e,t,r={}){const[o]=await Iw(e,t,r),n=o,s=new I_({name:"barndoor-js-sdk",version:"0.1.0"}),a=new Ew(new URL(n.url),{requestInit:{headers:n.headers}});return await s.connect(a),s}function Nw(){if(R&&"function"==typeof i.randomUUID)return i.randomUUID();if("undefined"!=typeof globalThis&&globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e;if(R&&"function"==typeof i.randomBytes)e=i.randomBytes(16);else{if("undefined"==typeof globalThis||!globalThis.crypto?.getRandomValues)throw new Error("Secure random generator not available for UUID.");e=new Uint8Array(16),globalThis.crypto.getRandomValues(e)}const t=e??new Uint8Array(0);if(t.length<16)throw new Error("Secure random generator not available for UUID.");const r=t[6],o=t[8];t[6]=15&r|64,t[8]=63&o|128;const n=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${n.substring(0,8)}-${n.substring(8,12)}-${n.substring(12,16)}-${n.substring(16,20)}-${n.substring(20)}`}const Cw=function(){try{if("undefined"!=typeof process&&process.versions?.node){const e=l(import.meta.url),t=r(e),n=o(t,"..","package.json");return JSON.parse(f(n,"utf8")).version}return'"1.0.1"'}catch(e){return console.warn("Could not read version from package.json:",e),"0.1.0"}}();export{C as AUTH_CONFIG,N as AgentToken,y as AuthenticationError,z as BarndoorConfig,m as BarndoorError,be as BarndoorSDK,E as ConfigurationError,w as ConnectionError,$ as HTTPError,re as JWTVerificationResult,k as OAuthError,ve as PKCEManager,x as ServerDetail,b as ServerNotFoundError,I as ServerSummary,S as TimeoutError,g as TokenError,v as TokenExpiredError,de as TokenManager,_ as TokenValidationError,U as checkTokenOrganization,fe as clearCachedToken,Y as clearOidcConfigCache,H as createScopedLogger,K as debug,Tw as ensureServerConnected,B as error,D as getDynamicConfig,L as getLogger,Q as getOidcConfig,M as getStaticConfig,q as hasOrganizationInfo,Z as info,j as isBrowser,R as isNode,me as isTokenActive,ye as isTokenActiveWithRefresh,he as loadUserToken,Pw as loginInteractive,xw as makeMcpClient,Iw as makeMcpConnectionParams,pe as saveUserToken,F as setLogger,X as setTokenLogger,$e as startLocalCallbackServer,ge as validateToken,ue as verifyJWTLocal,Cw as version,G as warn};
package/dist/index.js CHANGED
@@ -10,4 +10,4 @@
10
10
  || ${a} === "boolean" || ${n} === null`).assign(i,Ef._`[${n}]`)}}o.else(),jf(e),o.endIf(),o.if(Ef._`${i} !== undefined`,()=>{o.assign(n,i),function({gen:e,parentData:t,parentDataProperty:r},o){e.if(Ef._`${t} !== undefined`,()=>e.assign(Ef._`${t}[${r}]`,o))}(e,i)})}(e,t,s):jf(e)})}return a};const xf=new Set(["string","number","integer","boolean","null"]);function If(e,t,r,o=Pf.Correct){const n=o===Pf.Correct?Ef.operators.EQ:Ef.operators.NEQ;let s;switch(e){case"null":return Ef._`${t} ${n} null`;case"array":s=Ef._`Array.isArray(${t})`;break;case"object":s=Ef._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=a(Ef._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=a();break;default:return Ef._`typeof ${t} ${n} ${e}`}return o===Pf.Correct?s:(0,Ef.not)(s);function a(e=Ef.nil){return(0,Ef.and)(Ef._`typeof ${t} == "number"`,e,r?Ef._`isFinite(${t})`:Ef.nil)}}function Nf(e,t,r,o){if(1===e.length)return If(e[0],t,r,o);let n;const s=(0,Sf.toHash)(e);if(s.array&&s.object){const e=Ef._`typeof ${t} != "object"`;n=s.null?e:Ef._`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else n=Ef.nil;s.number&&delete s.integer;for(const e in s)n=(0,Ef.and)(n,If(e,t,r,o));return n}mf.checkDataType=If,mf.checkDataTypes=Nf;const Cf={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?Ef._`{type: ${e}}`:Ef._`{type: ${t}}`};function jf(e){const t=function(e){const{gen:t,data:r,schema:o}=e,n=(0,Sf.schemaRefOrVal)(e,o,"type");return{gen:t,keyword:"type",data:r,schema:o.type,schemaCode:n,schemaValue:n,parentSchema:o,params:{},it:e}}(e);(0,kf.reportError)(t,Cf)}mf.reportTypeError=jf;var Rf,Of={};var zf,Af,Mf={},Uf={};function Df(){if(zf)return Uf;zf=1,Object.defineProperty(Uf,"__esModule",{value:!0}),Uf.validateUnion=Uf.validateArray=Uf.usePattern=Uf.callValidateCode=Uf.schemaProperties=Uf.allSchemaProperties=Uf.noPropertyInData=Uf.propertyInData=Uf.isOwnProperty=Uf.hasPropFunc=Uf.reportMissingProp=Uf.checkMissingProp=Uf.checkReportMissingProp=void 0;const e=Zh,t=Wh,r=hf(),o=Wh;function n(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function s(t,r,o){return e._`${n(t)}.call(${r}, ${o})`}function a(t,r,o,n){const a=e._`${r}${(0,e.getProperty)(o)} === undefined`;return n?(0,e.or)(a,(0,e.not)(s(t,r,o))):a}function i(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}Uf.checkReportMissingProp=function(t,r){const{gen:o,data:n,it:s}=t;o.if(a(o,n,r,s.opts.ownProperties),()=>{t.setParams({missingProperty:e._`${r}`},!0),t.error()})},Uf.checkMissingProp=function({gen:t,data:r,it:{opts:o}},n,s){return(0,e.or)(...n.map(n=>(0,e.and)(a(t,r,n,o.ownProperties),e._`${s} = ${n}`)))},Uf.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},Uf.hasPropFunc=n,Uf.isOwnProperty=s,Uf.propertyInData=function(t,r,o,n){const a=e._`${r}${(0,e.getProperty)(o)} !== undefined`;return n?e._`${a} && ${s(t,r,o)}`:a},Uf.noPropertyInData=a,Uf.allSchemaProperties=i,Uf.schemaProperties=function(e,r){return i(r).filter(o=>!(0,t.alwaysValidSchema)(e,r[o]))},Uf.callValidateCode=function({schemaCode:t,data:o,it:{gen:n,topSchemaRef:s,schemaPath:a,errorPath:i},it:c},u,l,d){const p=d?e._`${t}, ${o}, ${s}${a}`:o,h=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,i)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&h.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const f=e._`${p}, ${n.object(...h)}`;return l!==e.nil?e._`${u}.call(${l}, ${f})`:e._`${u}(${f})`};const c=e._`new RegExp`;return Uf.usePattern=function({gen:t,it:{opts:r}},n){const s=r.unicodeRegExp?"u":"",{regExp:a}=r.code,i=a(n,s);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:e._`${"new RegExp"===a.code?c:(0,o.useFunc)(t,a)}(${n}, ${s})`})},Uf.validateArray=function(r){const{gen:o,data:n,keyword:s,it:a}=r,i=o.name("valid");if(a.allErrors){const e=o.let("valid",!0);return c(()=>o.assign(e,!1)),e}return o.var(i,!0),c(()=>o.break()),i;function c(a){const c=o.const("len",e._`${n}.length`);o.forRange("i",0,c,n=>{r.subschema({keyword:s,dataProp:n,dataPropType:t.Type.Num},i),o.if((0,e.not)(i),a)})}},Uf.validateUnion=function(r){const{gen:o,schema:n,keyword:s,it:a}=r;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(e=>(0,t.alwaysValidSchema)(a,e))&&!a.opts.unevaluated)return;const i=o.let("valid",!1),c=o.name("_valid");o.block(()=>n.forEach((t,n)=>{const a=r.subschema({keyword:s,schemaProp:n,compositeRule:!0},c);o.assign(i,e._`${i} || ${c}`);r.mergeValidEvaluated(a,c)||o.if((0,e.not)(i))})),r.result(i,()=>r.reset(),()=>r.error(!0))},Uf}function qf(){if(Af)return Mf;Af=1,Object.defineProperty(Mf,"__esModule",{value:!0}),Mf.validateKeywordUsage=Mf.validSchemaType=Mf.funcKeywordCode=Mf.macroKeywordCode=void 0;const e=Zh,t=hf(),r=Df(),o=ff();function n(t){const{gen:r,data:o,it:n}=t;r.if(n.parentData,()=>r.assign(o,e._`${n.parentData}[${n.parentDataProperty}]`))}function s(t,r,o){if(void 0===o)throw new Error(`keyword "${r}" failed to compile`);return t.scopeValue("keyword","function"==typeof o?{ref:o}:{ref:o,code:(0,e.stringify)(o)})}return Mf.macroKeywordCode=function(t,r){const{gen:o,keyword:n,schema:a,parentSchema:i,it:c}=t,u=r.macro.call(c.self,a,i,c),l=s(o,n,u);!1!==c.opts.validateSchema&&c.self.validateSchema(u,!0);const d=o.name("valid");t.subschema({schema:u,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},d),t.pass(d,()=>t.error(!0))},Mf.funcKeywordCode=function(a,i){var c;const{gen:u,keyword:l,schema:d,parentSchema:p,$data:h,it:f}=a;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(f,i);const m=!h&&i.compile?i.compile.call(f.self,d,p,f):i.validate,y=s(u,l,m),g=u.let("valid");function v(o=(i.async?e._`await `:e.nil)){const n=f.opts.passContext?t.default.this:t.default.self,s=!("compile"in i&&!h||!1===i.schema);u.assign(g,e._`${o}${(0,r.callValidateCode)(a,y,n,s)}`,i.modifying)}function _(t){var r;u.if((0,e.not)(null!==(r=i.valid)&&void 0!==r?r:g),t)}a.block$data(g,function(){if(!1===i.errors)v(),i.modifying&&n(a),_(()=>a.error());else{const r=i.async?function(){const t=u.let("ruleErrs",null);return u.try(()=>v(e._`await `),r=>u.assign(g,!1).if(e._`${r} instanceof ${f.ValidationError}`,()=>u.assign(t,e._`${r}.errors`),()=>u.throw(r))),t}():function(){const t=e._`${y}.errors`;return u.assign(t,null),v(e.nil),t}();i.modifying&&n(a),_(()=>function(r,n){const{gen:s}=r;s.if(e._`Array.isArray(${n})`,()=>{s.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${n} : ${t.default.vErrors}.concat(${n})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,o.extendErrors)(r)},()=>r.error())}(a,r))}}),a.ok(null!==(c=i.valid)&&void 0!==c?c:g)},Mf.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)},Mf.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:o},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)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 ${s}: ${a.join(",")}`);if(n.validateSchema){if(!n.validateSchema(e[s])){const e=`keyword "${s}" value is invalid at path "${o}": `+r.errorsText(n.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);r.logger.error(e)}}},Mf}var Vf,Ff={};var Lf={},Kf={exports:{}},Hf=Kf.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),Zf(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function Zf(e,t,r,o,n,s,a,i,c,u){if(o&&"object"==typeof o&&!Array.isArray(o)){for(var l in t(o,n,s,a,i,c,u),o){var d=o[l];if(Array.isArray(d)){if(l in Hf.arrayKeywords)for(var p=0;p<d.length;p++)Zf(e,t,r,d[p],n+"/"+l+"/"+p,s,n,l,o,p)}else if(l in Hf.propsKeywords){if(d&&"object"==typeof d)for(var h in d)Zf(e,t,r,d[h],n+"/"+l+"/"+Gf(h),s,n,l,o,h)}else(l in Hf.keywords||e.allKeys&&!(l in Hf.skipKeywords))&&Zf(e,t,r,d,n+"/"+l,s,n,l,o)}r(o,n,s,a,i,c,u)}}function Gf(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}Hf.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},Hf.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},Hf.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},Hf.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};var Jf=Kf.exports;Object.defineProperty(Lf,"__esModule",{value:!0}),Lf.getSchemaRefs=Lf.resolveUrl=Lf.normalizeId=Lf._getFullPath=Lf.getFullPath=Lf.inlineRef=void 0;const Wf=Wh,Bf=Vc,Qf=Jf,Yf=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);Lf.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!em(e):!!t&&tm(e)<=t)};const Xf=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function em(e){for(const t in e){if(Xf.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(em))return!0;if("object"==typeof r&&em(r))return!0}return!1}function tm(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!Yf.has(r)&&("object"==typeof e[r]&&(0,Wf.eachItem)(e[r],e=>t+=tm(e)),t===1/0))return 1/0}return t}function rm(e,t="",r){!1!==r&&(t=sm(t));const o=e.parse(t);return om(e,o)}function om(e,t){return e.serialize(t).split("#")[0]+"#"}Lf.getFullPath=rm,Lf._getFullPath=om;const nm=/#\/?$/;function sm(e){return e?e.replace(nm,""):""}Lf.normalizeId=sm,Lf.resolveUrl=function(e,t,r){return r=sm(r),e.resolve(t,r)};const am=/^[a-z_][-a-z0-9._]*$/i;var im;function cm(){if(im)return Lh;im=1,Object.defineProperty(Lh,"__esModule",{value:!0}),Lh.getData=Lh.KeywordCxt=Lh.validateFunctionCode=void 0;const e=function(){if(df)return Kh;df=1,Object.defineProperty(Kh,"__esModule",{value:!0}),Kh.boolOrEmptySchema=Kh.topBoolOrEmptySchema=void 0;const e=ff(),t=Zh,r=hf(),o={message:"boolean schema is false"};function n(t,r){const{gen:n,data:s}=t,a={gen:n,keyword:"false schema",data:s,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,e.reportError)(a,o,void 0,r)}return Kh.topBoolOrEmptySchema=function(e){const{gen:o,schema:s,validateName:a}=e;!1===s?n(e,!1):"object"==typeof s&&!0===s.$async?o.return(r.default.data):(o.assign(t._`${a}.errors`,null),o.return(!0))},Kh.boolOrEmptySchema=function(e,t){const{gen:r,schema:o}=e;!1===o?(r.var(t,!1),n(e)):r.var(t,!0)},Kh}(),t=mf,r=wf(),o=mf,n=function(){if(Rf)return Of;Rf=1,Object.defineProperty(Of,"__esModule",{value:!0}),Of.assignDefaults=void 0;const e=Zh,t=Wh;function r(r,o,n){const{gen:s,compositeRule:a,data:i,opts:c}=r;if(void 0===n)return;const u=e._`${i}${(0,e.getProperty)(o)}`;if(a)return void(0,t.checkStrictMode)(r,`default is ignored for: ${u}`);let l=e._`${u} === undefined`;"empty"===c.useDefaults&&(l=e._`${l} || ${u} === null || ${u} === ""`),s.if(l,e._`${u} = ${(0,e.stringify)(n)}`)}return Of.assignDefaults=function(e,t){const{properties:o,items:n}=e.schema;if("object"===t&&o)for(const t in o)r(e,t,o[t].default);else"array"===t&&Array.isArray(n)&&n.forEach((t,o)=>r(e,o,t.default))},Of}(),s=qf(),a=function(){if(Vf)return Ff;Vf=1,Object.defineProperty(Ff,"__esModule",{value:!0}),Ff.extendSubschemaMode=Ff.extendSubschemaData=Ff.getSubschema=void 0;const e=Zh,t=Wh;return Ff.getSubschema=function(r,{keyword:o,schemaProp:n,schema:s,schemaPath:a,errSchemaPath:i,topSchemaRef:c}){if(void 0!==o&&void 0!==s)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==o){const s=r.schema[o];return void 0===n?{schema:s,schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(o)}`,errSchemaPath:`${r.errSchemaPath}/${o}`}:{schema:s[n],schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(o)}${(0,e.getProperty)(n)}`,errSchemaPath:`${r.errSchemaPath}/${o}/${(0,t.escapeFragment)(n)}`}}if(void 0!==s){if(void 0===a||void 0===i||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:s,schemaPath:a,topSchemaRef:c,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')},Ff.extendSubschemaData=function(r,o,{dataProp:n,dataPropType:s,data:a,dataTypes:i,propertyName:c}){if(void 0!==a&&void 0!==n)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:u}=o;if(void 0!==n){const{errorPath:a,dataPathArr:i,opts:c}=o;l(u.let("data",e._`${o.data}${(0,e.getProperty)(n)}`,!0)),r.errorPath=e.str`${a}${(0,t.getErrorPath)(n,s,c.jsPropertySyntax)}`,r.parentDataProperty=e._`${n}`,r.dataPathArr=[...i,r.parentDataProperty]}function l(e){r.data=e,r.dataLevel=o.dataLevel+1,r.dataTypes=[],o.definedProperties=new Set,r.parentData=o.data,r.dataNames=[...o.dataNames,e]}void 0!==a&&(l(a instanceof e.Name?a:u.let("data",a,!0)),void 0!==c&&(r.propertyName=c)),i&&(r.dataTypes=i)},Ff.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:o,createErrors:n,allErrors:s}){void 0!==o&&(e.compositeRule=o),void 0!==n&&(e.createErrors=n),void 0!==s&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r},Ff}(),i=Zh,c=hf(),u=Lf,l=Wh,d=ff();function p({gen:e,validateName:t,schema:r,schemaEnv:o,opts:n},s){n.code.es5?e.func(t,i._`${c.default.data}, ${c.default.valCxt}`,o.$async,()=>{e.code(i._`"use strict"; ${h(r,n)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,i._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,i._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,i._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,i._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,i._`""`),e.var(c.default.parentData,i._`undefined`),e.var(c.default.parentDataProperty,i._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`{}`)})}(e,n),e.code(s)}):e.func(t,i._`${c.default.data}, ${function(e){return i._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?i._`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}(n)}`,o.$async,()=>e.code(h(r,n)).code(s))}function h(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?i._`/*# sourceURL=${r} */`:i.nil}function f(t,r){y(t)&&(g(t),m(t))?function(e,t){const{schema:r,gen:o,opts:n}=e;n.$comment&&r.$comment&&_(e);(function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.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 s=o.const("_errs",c.default.errors);v(e,s),o.var(t,i._`${s} === ${c.default.errors}`)}(t,r):(0,e.boolOrEmptySchema)(t,r)}function m({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 g(e){(0,l.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:o,self:n}=e;t.$ref&&o.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(t,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function v(e,r){if(e.opts.jtd)return w(e,[],!1,r);const o=(0,t.getSchemaTypes)(e.schema);w(e,o,!(0,t.coerceAndCheckDataType)(e,o),r)}function _({gen:e,schemaEnv:t,schema:r,errSchemaPath:o,opts:n}){const s=r.$comment;if(!0===n.$comment)e.code(i._`${c.default.self}.logger.log(${s})`);else if("function"==typeof n.$comment){const r=i.str`${o}/$comment`,n=e.scopeValue("root",{ref:t.root});e.code(i._`${c.default.self}.opts.$comment(${s}, ${r}, ${n}.schema)`)}}function w(e,t,n,s){const{gen:a,schema:u,data:d,allErrors:p,opts:h,self:f}=e,{RULES:m}=f;function y(l){(0,r.shouldUseGroup)(u,l)&&(l.type?(a.if((0,o.checkDataType)(l.type,d,h.strictNumbers)),$(e,l),1===t.length&&t[0]===l.type&&n&&(a.else(),(0,o.reportTypeError)(e)),a.endIf()):$(e,l),p||a.if(i._`${c.default.errors} === ${s||0}`))}!u.$ref||!h.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(u,m)?(h.jtd||function(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;(function(e,t){if(!t.length)return;if(!e.dataTypes.length)return void(e.dataTypes=t);t.forEach(t=>{k(e.dataTypes,t)||E(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const r=[];for(const o of e.dataTypes)k(t,o)?r.push(o):t.includes("integer")&&"number"===o&&r.push("integer");e.dataTypes=r}(e,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 o=e.self.RULES.all;for(const n in o){const s=o[n];if("object"==typeof s&&(0,r.shouldUseRule)(e.schema,s)){const{type:r}=s.definition;r.length&&!r.some(e=>b(t,e))&&E(e,`missing type "${r.join(",")}" for keyword "${n}"`)}}}(e,e.dataTypes)}(e,t),a.block(()=>{for(const e of m.rules)y(e);y(m.post)})):a.block(()=>P(e,"$ref",m.all.$ref.definition))}function $(e,t){const{gen:o,schema:s,opts:{useDefaults:a}}=e;a&&(0,n.assignDefaults)(e,t.type),o.block(()=>{for(const o of t.rules)(0,r.shouldUseRule)(s,o)&&P(e,o.keyword,o.definition,t.type)})}function b(e,t){return e.includes(t)||"number"===t&&e.includes("integer")}function k(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function E(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,l.checkStrictMode)(e,t,e.opts.strictTypes)}Lh.validateFunctionCode=function(t){y(t)&&(g(t),m(t))?function(e){const{schema:t,opts:r,gen:o}=e;p(e,()=>{r.$comment&&t.$comment&&_(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,l.checkStrictMode)(e,"default is ignored in the schema root")}(e),o.let(c.default.vErrors,null),o.let(c.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",i._`${r}.evaluated`),t.if(i._`${e.evaluated}.dynamicProps`,()=>t.assign(i._`${e.evaluated}.props`,i._`undefined`)),t.if(i._`${e.evaluated}.dynamicItems`,()=>t.assign(i._`${e.evaluated}.items`,i._`undefined`))}(e),v(e),function(e){const{gen:t,schemaEnv:r,validateName:o,ValidationError:n,opts:s}=e;r.$async?t.if(i._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(i._`new ${n}(${c.default.vErrors})`)):(t.assign(i._`${o}.errors`,c.default.vErrors),s.unevaluated&&function({gen:e,evaluated:t,props:r,items:o}){r instanceof i.Name&&e.assign(i._`${t}.props`,r);o instanceof i.Name&&e.assign(i._`${t}.items`,o)}(e),t.return(i._`${c.default.errors} === 0`))}(e)})}(t):p(t,()=>(0,e.topBoolOrEmptySchema)(t))};class S{constructor(e,t,r){if((0,s.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,l.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",I(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,s.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",c.default.errors))}result(e,t,r){this.failResult((0,i.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,i.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(i._`${t} !== undefined && (${(0,i.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?d.reportExtraError:d.reportError)(this,this.def.error,t)}$dataError(){(0,d.reportError)(this,this.def.$dataError||d.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,d.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=i.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=i.nil,t=i.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:n,def:s}=this;r.if((0,i.or)(i._`${o} === undefined`,t)),e!==i.nil&&r.assign(e,!0),(n.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==i.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:n,it:s}=this;return(0,i.or)(function(){if(r.length){if(!(t instanceof i.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return i._`${(0,o.checkDataTypes)(e,t,s.opts.strictNumbers,o.DataType.Wrong)}`}return i.nil}(),function(){if(n.validateSchema){const r=e.scopeValue("validate$data",{ref:n.validateSchema});return i._`!${r}(${t})`}return i.nil}())}subschema(e,t){const r=(0,a.getSubschema)(this.it,e);(0,a.extendSubschemaData)(r,this.it,e),(0,a.extendSubschemaMode)(r,e);const o={...this.it,...r,items:void 0,props:void 0};return f(o,t),o}mergeEvaluated(e,t){const{it:r,gen:o}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=l.mergeEvaluated.props(o,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=l.mergeEvaluated.items(o,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return o.if(t,()=>this.mergeEvaluated(e,i.Name)),!0}}function P(e,t,r,o){const n=new S(e,r,t);"code"in r?r.code(n,o):n.$data&&r.validate?(0,s.funcKeywordCode)(n,r):"macro"in r?(0,s.macroKeywordCode)(n,r):(r.compile||r.validate)&&(0,s.funcKeywordCode)(n,r)}Lh.KeywordCxt=S;const T=/^\/(?:[^~]|~0|~1)*$/,x=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function I(e,{dataLevel:t,dataNames:r,dataPathArr:o}){let n,s;if(""===e)return c.default.rootData;if("/"===e[0]){if(!T.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);n=e,s=c.default.rootData}else{const a=x.exec(e);if(!a)throw new Error(`Invalid JSON-pointer: ${e}`);const i=+a[1];if(n=a[2],"#"===n){if(i>=t)throw new Error(d("property/index",i));return o[t-i]}if(i>t)throw new Error(d("data",i));if(s=r[t-i],!n)return s}let a=s;const u=n.split("/");for(const e of u)e&&(s=i._`${s}${(0,i.getProperty)((0,l.unescapeJsonPointer)(e))}`,a=i._`${a} && ${s}`);return a;function d(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}return Lh.getData=I,Lh}Lf.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:o}=this.opts,n=sm(e[r]||t),s={"":n},a=rm(o,n,!1),i={},c=new Set;return Qf(e,{allKeys:!0},(e,t,o,n)=>{if(void 0===n)return;const d=a+t;let p=s[n];function h(t){const r=this.opts.uriResolver.resolve;if(t=sm(p?r(p,t):t),c.has(t))throw l(t);c.add(t);let o=this.refs[t];return"string"==typeof o&&(o=this.refs[o]),"object"==typeof o?u(e,o.schema,t):t!==sm(d)&&("#"===t[0]?(u(e,i[t],t),i[t]=e):this.refs[t]=d),t}function f(e){if("string"==typeof e){if(!am.test(e))throw new Error(`invalid anchor "${e}"`);h.call(this,`#${e}`)}}"string"==typeof e[r]&&(p=h.call(this,e[r])),f.call(this,e.$anchor),f.call(this,e.$dynamicAnchor),s[t]=p}),i;function u(e,t,r){if(void 0!==t&&!Bf(e,t))throw l(r)}function l(e){return new Error(`reference "${e}" resolves to more than one schema`)}};var um,lm={};function dm(){if(um)return lm;um=1,Object.defineProperty(lm,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return lm.default=e,lm}var pm,hm={};function fm(){if(pm)return hm;pm=1,Object.defineProperty(hm,"__esModule",{value:!0});const e=Lf;class t extends Error{constructor(t,r,o,n){super(n||`can't resolve reference ${o} from id ${r}`),this.missingRef=(0,e.resolveUrl)(t,r,o),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(t,this.missingRef))}}return hm.default=t,hm}var mm={};Object.defineProperty(mm,"__esModule",{value:!0}),mm.resolveSchema=mm.getCompilingSchema=mm.resolveRef=mm.compileSchema=mm.SchemaEnv=void 0;const ym=Zh,gm=dm(),vm=hf(),_m=Lf,wm=Wh,$m=cm();class bm{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,_m.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 km(e){const t=Sm.call(this,e);if(t)return t;const r=(0,_m.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:o,lines:n}=this.opts.code,{ownProperties:s}=this.opts,a=new ym.CodeGen(this.scope,{es5:o,lines:n,ownProperties:s});let i;e.$async&&(i=a.scopeValue("Error",{ref:gm.default,code:ym._`require("ajv/dist/runtime/validation_error").default`}));const c=a.scopeName("validate");e.validateName=c;const u={gen:a,allErrors:this.opts.allErrors,data:vm.default.data,parentData:vm.default.parentData,parentDataProperty:vm.default.parentDataProperty,dataNames:[vm.default.data],dataPathArr:[ym.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,ym.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:i,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:ym.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:ym._`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,$m.validateFunctionCode)(u),a.optimize(this.opts.code.optimize);const t=a.toString();l=`${a.scopeRefs(vm.default.scope)}return ${t}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const r=new Function(`${vm.default.self}`,`${vm.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{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:c,validateCode:t,scopeValues:a._values}),this.opts.unevaluated){const{props:e,items:t}=u;r.evaluated={props:e instanceof ym.Name?void 0:e,items:t instanceof ym.Name?void 0:t,dynamicProps:e instanceof ym.Name,dynamicItems:t instanceof ym.Name},r.source&&(r.source.evaluated=(0,ym.stringify)(r.evaluated))}return e.validate=r,e}catch(t){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),t}finally{this._compilations.delete(e)}}function Em(e){return(0,_m.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:km.call(this,e)}function Sm(e){for(const t of this._compilations)if(Pm(t,e))return t}function Pm(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Tm(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||xm.call(this,e,t)}function xm(e,t){const r=this.opts.uriResolver.parse(t),o=(0,_m._getFullPath)(this.opts.uriResolver,r);let n=(0,_m.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&o===n)return Nm.call(this,r,e);const s=(0,_m.normalizeId)(o),a=this.refs[s]||this.schemas[s];if("string"==typeof a){const t=xm.call(this,e,a);if("object"!=typeof(null==t?void 0:t.schema))return;return Nm.call(this,r,t)}if("object"==typeof(null==a?void 0:a.schema)){if(a.validate||km.call(this,a),s===(0,_m.normalizeId)(t)){const{schema:t}=a,{schemaId:r}=this.opts,o=t[r];return o&&(n=(0,_m.resolveUrl)(this.opts.uriResolver,n,o)),new bm({schema:t,schemaId:r,root:e,baseId:n})}return Nm.call(this,r,a)}}mm.SchemaEnv=bm,mm.compileSchema=km,mm.resolveRef=function(e,t,r){var o;r=(0,_m.resolveUrl)(this.opts.uriResolver,t,r);const n=e.refs[r];if(n)return n;let s=Tm.call(this,e,r);if(void 0===s){const n=null===(o=e.localRefs)||void 0===o?void 0:o[r],{schemaId:a}=this.opts;n&&(s=new bm({schema:n,schemaId:a,root:e,baseId:t}))}return void 0!==s?e.refs[r]=Em.call(this,s):void 0},mm.getCompilingSchema=Sm,mm.resolveSchema=xm;const Im=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Nm(e,{baseId:t,schema:r,root:o}){var n;if("/"!==(null===(n=e.fragment)||void 0===n?void 0:n[0]))return;for(const o of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;const e=r[(0,wm.unescapeFragment)(o)];if(void 0===e)return;const n="object"==typeof(r=e)&&r[this.opts.schemaId];!Im.has(o)&&n&&(t=(0,_m.resolveUrl)(this.opts.uriResolver,t,n))}let s;if("boolean"!=typeof r&&r.$ref&&!(0,wm.schemaHasRulesButRef)(r,this.RULES)){const e=(0,_m.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=xm.call(this,o,e)}const{schemaId:a}=this.opts;return s=s||new bm({schema:r,schemaId:a,root:o,baseId:t}),s.schema!==s.root.schema?s:void 0}var Cm={$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:!1},jm={};Object.defineProperty(jm,"__esModule",{value:!0});const Rm=ul;Rm.code='require("ajv/dist/runtime/uri").default',jm.default=Rm,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=cm();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Zh;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const o=dm(),n=fm(),s=yf,a=mm,i=Zh,c=Lf,u=mf,l=Wh,d=Cm,p=jm,h=(e,t)=>new RegExp(e,t);h.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],m=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."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function v(e){var t,r,o,n,s,a,i,c,u,l,d,f,m,y,g,v,_,w,$,b,k,E,S,P,T;const x=e.strict,I=null===(t=e.code)||void 0===t?void 0:t.optimize,N=!0===I||void 0===I?1:I||0,C=null!==(o=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==o?o:h,j=null!==(n=e.uriResolver)&&void 0!==n?n:p.default;return{strictSchema:null===(a=null!==(s=e.strictSchema)&&void 0!==s?s:x)||void 0===a||a,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:x)||void 0===c||c,strictTypes:null!==(l=null!==(u=e.strictTypes)&&void 0!==u?u:x)&&void 0!==l?l:"log",strictTuples:null!==(f=null!==(d=e.strictTuples)&&void 0!==d?d:x)&&void 0!==f?f:"log",strictRequired:null!==(y=null!==(m=e.strictRequired)&&void 0!==m?m:x)&&void 0!==y&&y,code:e.code?{...e.code,optimize:N,regExp:C}:{optimize:N,regExp:C},loopRequired:null!==(g=e.loopRequired)&&void 0!==g?g:200,loopEnum:null!==(v=e.loopEnum)&&void 0!==v?v:200,meta:null===(_=e.meta)||void 0===_||_,messages:null===(w=e.messages)||void 0===w||w,inlineRefs:null===($=e.inlineRefs)||void 0===$||$,schemaId:null!==(b=e.schemaId)&&void 0!==b?b:"$id",addUsedSchema:null===(k=e.addUsedSchema)||void 0===k||k,validateSchema:null===(E=e.validateSchema)||void 0===E||E,validateFormats:null===(S=e.validateFormats)||void 0===S||S,unicodeRegExp:null===(P=e.unicodeRegExp)||void 0===P||P,int32range:null===(T=e.int32range)||void 0===T||T,uriResolver:j}}class _{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:m,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 o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,s.getRules)(),w.call(this,y,e,"NOT SUPPORTED"),w.call(this,g,e,"DEPRECATED","warn"),this._metaOpts=S.call(this),e.formats&&k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&E.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),b.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let o=d;"id"===r&&(o={...d},o.id=o.$id,delete o.$id),t&&e&&this.addMetaSchema(o,o[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 o=r(t);return"$async"in r||(this.errors=r.errors),o}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 o.call(this,e,t);async function o(e,t){await s.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||a.call(this,r)}async function s(e){e&&!this.getSchema(e)&&await o.call(this,{$ref:e},!0)}async function a(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof n.default))throw t;return i.call(this,t),await c.call(this,t.missingSchema),a.call(this,e)}}function i({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 u.call(this,e);this.refs[e]||await s.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function u(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,o=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,o);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,c.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,o,!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 o=this.validate(r,e);if(!o&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return o}getSchema(e){let t;for(;"string"==typeof(t=$.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,o=new a.SchemaEnv({schema:{},schemaId:r});if(t=a.resolveSchema.call(this,o,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=$.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,c.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(x.call(this,r,t),!t)return(0,l.eachItem)(r,e=>I.call(this,e)),this;C.call(this,t);const o={...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)};return(0,l.eachItem)(r,0===o.type.length?e=>I.call(this,e,o):e=>o.type.forEach(t=>I.call(this,e,o,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 o of t){const t=o.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:o}=t.definition,s=n[e];o&&s&&(n[e]=R(s))}}return e}_removeAllSchemas(e,t){for(const r in e){const o=e[r];t&&!t.test(r)||("string"==typeof o?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,t,r,o=this.opts.validateSchema,n=this.opts.addUsedSchema){let s;const{schemaId:i}=this.opts;if("object"==typeof e)s=e[i];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 u=this._cache.get(e);if(void 0!==u)return u;r=(0,c.normalizeId)(s||r);const l=c.getSchemaRefs.call(this,e,r);return u=new a.SchemaEnv({schema:e,schemaId:i,meta:t,baseId:r,localRefs:l}),this._cache.set(u.schema,u),n&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=u),o&&this.validateSchema(e,!0),u}_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):a.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{a.compileSchema.call(this,e)}finally{this.opts=t}}}function w(e,t,r,o="error"){for(const n in e){const s=n;s in t&&this.logger[o](`${r}: option ${n}. ${e[s]}`)}}function $(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function b(){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 k(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E(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 S(){const e={...this.opts};for(const t of f)delete e[t];return e}_.ValidationError=o.default,_.MissingRefError=n.default,e.default=_;const P={log(){},warn(){},error(){}};const T=/^[a-z_$][a-z0-9_$:-]*$/i;function x(e,t){const{RULES:r}=this;if((0,l.eachItem)(e,e=>{if(r.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!T.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 I(e,t,r){var o;const n=null==t?void 0:t.post;if(r&&n)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:s}=this;let a=n?s.post:s.rules.find(({type:e})=>e===r);if(a||(a={type:r,rules:[]},s.rules.push(a)),s.keywords[e]=!0,!t)return;const i={keyword:e,definition:{...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)}};t.before?N.call(this,a,i,t.before):a.rules.push(i),s.all[e]=i,null===(o=t.implements)||void 0===o||o.forEach(e=>this.addKeyword(e))}function N(e,t,r){const o=e.rules.findIndex(e=>e.keyword===r);o>=0?e.rules.splice(o,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function C(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=R(t)),e.validateSchema=this.compile(t,!0))}const j={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function R(e){return{anyOf:[e,j]}}}(Fh);var Om={},zm={},Am={};Object.defineProperty(Am,"__esModule",{value:!0});const Mm={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Am.default=Mm;var Um={};Object.defineProperty(Um,"__esModule",{value:!0}),Um.callRef=Um.getValidate=void 0;const Dm=fm(),qm=Df(),Vm=Zh,Fm=hf(),Lm=mm,Km=Wh,Hm={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:r,it:o}=e,{baseId:n,schemaEnv:s,validateName:a,opts:i,self:c}=o,{root:u}=s;if(("#"===r||"#/"===r)&&n===u.baseId)return function(){if(s===u)return Gm(e,a,s,s.$async);const r=t.scopeValue("root",{ref:u});return Gm(e,Vm._`${r}.validate`,u,u.$async)}();const l=Lm.resolveRef.call(c,u,n,r);if(void 0===l)throw new Dm.default(o.opts.uriResolver,n,r);return l instanceof Lm.SchemaEnv?function(t){const r=Zm(e,t);Gm(e,r,t,t.$async)}(l):function(o){const n=t.scopeValue("schema",!0===i.code.source?{ref:o,code:(0,Vm.stringify)(o)}:{ref:o}),s=t.name("valid"),a=e.subschema({schema:o,dataTypes:[],schemaPath:Vm.nil,topSchemaRef:n,errSchemaPath:r},s);e.mergeEvaluated(a),e.ok(s)}(l)}};function Zm(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):Vm._`${r.scopeValue("wrapper",{ref:t})}.validate`}function Gm(e,t,r,o){const{gen:n,it:s}=e,{allErrors:a,schemaEnv:i,opts:c}=s,u=c.passContext?Fm.default.this:Vm.nil;function l(e){const t=Vm._`${e}.errors`;n.assign(Fm.default.vErrors,Vm._`${Fm.default.vErrors} === null ? ${t} : ${Fm.default.vErrors}.concat(${t})`),n.assign(Fm.default.errors,Vm._`${Fm.default.vErrors}.length`)}function d(e){var t;if(!s.opts.unevaluated)return;const o=null===(t=null==r?void 0:r.validate)||void 0===t?void 0:t.evaluated;if(!0!==s.props)if(o&&!o.dynamicProps)void 0!==o.props&&(s.props=Km.mergeEvaluated.props(n,o.props,s.props));else{const t=n.var("props",Vm._`${e}.evaluated.props`);s.props=Km.mergeEvaluated.props(n,t,s.props,Vm.Name)}if(!0!==s.items)if(o&&!o.dynamicItems)void 0!==o.items&&(s.items=Km.mergeEvaluated.items(n,o.items,s.items));else{const t=n.var("items",Vm._`${e}.evaluated.items`);s.items=Km.mergeEvaluated.items(n,t,s.items,Vm.Name)}}o?function(){if(!i.$async)throw new Error("async schema referenced by sync schema");const r=n.let("valid");n.try(()=>{n.code(Vm._`await ${(0,qm.callValidateCode)(e,t,u)}`),d(t),a||n.assign(r,!0)},e=>{n.if(Vm._`!(${e} instanceof ${s.ValidationError})`,()=>n.throw(e)),l(e),a||n.assign(r,!1)}),e.ok(r)}():e.result((0,qm.callValidateCode)(e,t,u),()=>d(t),()=>l(t))}Um.getValidate=Zm,Um.callRef=Gm,Um.default=Hm,Object.defineProperty(zm,"__esModule",{value:!0});const Jm=Um,Wm=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Am.default,Jm.default];zm.default=Wm;var Bm={},Qm={};Object.defineProperty(Qm,"__esModule",{value:!0});const Ym=Zh,Xm=Ym.operators,ey={maximum:{okStr:"<=",ok:Xm.LTE,fail:Xm.GT},minimum:{okStr:">=",ok:Xm.GTE,fail:Xm.LT},exclusiveMaximum:{okStr:"<",ok:Xm.LT,fail:Xm.GTE},exclusiveMinimum:{okStr:">",ok:Xm.GT,fail:Xm.LTE}},ty={message:({keyword:e,schemaCode:t})=>Ym.str`must be ${ey[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Ym._`{comparison: ${ey[e].okStr}, limit: ${t}}`},ry={keyword:Object.keys(ey),type:"number",schemaType:"number",$data:!0,error:ty,code(e){const{keyword:t,data:r,schemaCode:o}=e;e.fail$data(Ym._`${r} ${ey[t].fail} ${o} || isNaN(${r})`)}};Qm.default=ry;var oy={};Object.defineProperty(oy,"__esModule",{value:!0});const ny=Zh,sy={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>ny.str`must be multiple of ${e}`,params:({schemaCode:e})=>ny._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:o,it:n}=e,s=n.opts.multipleOfPrecision,a=t.let("res"),i=s?ny._`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:ny._`${a} !== parseInt(${a})`;e.fail$data(ny._`(${o} === 0 || (${a} = ${r}/${o}, ${i}))`)}};oy.default=sy;var ay={},iy={};function cy(e){const t=e.length;let r,o=0,n=0;for(;n<t;)o++,r=e.charCodeAt(n++),r>=55296&&r<=56319&&n<t&&(r=e.charCodeAt(n),56320==(64512&r)&&n++);return o}Object.defineProperty(iy,"__esModule",{value:!0}),iy.default=cy,cy.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(ay,"__esModule",{value:!0});const uy=Zh,ly=Wh,dy=iy,py={message:({keyword:e,schemaCode:t})=>uy.str`must NOT have ${"maxLength"===e?"more":"fewer"} than ${t} characters`,params:({schemaCode:e})=>uy._`{limit: ${e}}`},hy={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:py,code(e){const{keyword:t,data:r,schemaCode:o,it:n}=e,s="maxLength"===t?uy.operators.GT:uy.operators.LT,a=!1===n.opts.unicode?uy._`${r}.length`:uy._`${(0,ly.useFunc)(e.gen,dy.default)}(${r})`;e.fail$data(uy._`${a} ${s} ${o}`)}};ay.default=hy;var fy={};Object.defineProperty(fy,"__esModule",{value:!0});const my=Df(),yy=Zh,gy={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>yy.str`must match pattern "${e}"`,params:({schemaCode:e})=>yy._`{pattern: ${e}}`},code(e){const{data:t,$data:r,schema:o,schemaCode:n,it:s}=e,a=s.opts.unicodeRegExp?"u":"",i=r?yy._`(new RegExp(${n}, ${a}))`:(0,my.usePattern)(e,o);e.fail$data(yy._`!${i}.test(${t})`)}};fy.default=gy;var vy={};Object.defineProperty(vy,"__esModule",{value:!0});const _y=Zh,wy={message:({keyword:e,schemaCode:t})=>_y.str`must NOT have ${"maxProperties"===e?"more":"fewer"} than ${t} properties`,params:({schemaCode:e})=>_y._`{limit: ${e}}`},$y={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:wy,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxProperties"===t?_y.operators.GT:_y.operators.LT;e.fail$data(_y._`Object.keys(${r}).length ${n} ${o}`)}};vy.default=$y;var by={};Object.defineProperty(by,"__esModule",{value:!0});const ky=Df(),Ey=Zh,Sy=Wh,Py={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>Ey.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>Ey._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:r,schemaCode:o,data:n,$data:s,it:a}=e,{opts:i}=a;if(!s&&0===r.length)return;const c=r.length>=i.loopRequired;if(a.allErrors?function(){if(c||s)e.block$data(Ey.nil,u);else for(const t of r)(0,ky.checkReportMissingProp)(e,t)}():function(){const a=t.let("missing");if(c||s){const r=t.let("valid",!0);e.block$data(r,()=>function(r,s){e.setParams({missingProperty:r}),t.forOf(r,o,()=>{t.assign(s,(0,ky.propertyInData)(t,n,r,i.ownProperties)),t.if((0,Ey.not)(s),()=>{e.error(),t.break()})},Ey.nil)}(a,r)),e.ok(r)}else t.if((0,ky.checkMissingProp)(e,r,a)),(0,ky.reportMissingProp)(e,a),t.else()}(),i.strictRequired){const t=e.parentSchema.properties,{definedProperties:o}=e.it;for(const e of r)if(void 0===(null==t?void 0:t[e])&&!o.has(e)){const t=`required property "${e}" is not defined at "${a.schemaEnv.baseId+a.errSchemaPath}" (strictRequired)`;(0,Sy.checkStrictMode)(a,t,a.opts.strictRequired)}}function u(){t.forOf("prop",o,r=>{e.setParams({missingProperty:r}),t.if((0,ky.noPropertyInData)(t,n,r,i.ownProperties),()=>e.error())})}}};by.default=Py;var Ty={};Object.defineProperty(Ty,"__esModule",{value:!0});const xy=Zh,Iy={message:({keyword:e,schemaCode:t})=>xy.str`must NOT have ${"maxItems"===e?"more":"fewer"} than ${t} items`,params:({schemaCode:e})=>xy._`{limit: ${e}}`},Ny={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Iy,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxItems"===t?xy.operators.GT:xy.operators.LT;e.fail$data(xy._`${r}.length ${n} ${o}`)}};Ty.default=Ny;var Cy={},jy={};Object.defineProperty(jy,"__esModule",{value:!0});const Ry=Vc;Ry.code='require("ajv/dist/runtime/equal").default',jy.default=Ry,Object.defineProperty(Cy,"__esModule",{value:!0});const Oy=mf,zy=Zh,Ay=Wh,My=jy,Uy={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>zy.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>zy._`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:r,$data:o,schema:n,parentSchema:s,schemaCode:a,it:i}=e;if(!o&&!n)return;const c=t.let("valid"),u=s.items?(0,Oy.getSchemaTypes)(s.items):[];function l(o,n){const s=t.name("item"),a=(0,Oy.checkDataTypes)(u,s,i.opts.strictNumbers,Oy.DataType.Wrong),l=t.const("indices",zy._`{}`);t.for(zy._`;${o}--;`,()=>{t.let(s,zy._`${r}[${o}]`),t.if(a,zy._`continue`),u.length>1&&t.if(zy._`typeof ${s} == "string"`,zy._`${s} += "_"`),t.if(zy._`typeof ${l}[${s}] == "number"`,()=>{t.assign(n,zy._`${l}[${s}]`),e.error(),t.assign(c,!1).break()}).code(zy._`${l}[${s}] = ${o}`)})}function d(o,n){const s=(0,Ay.useFunc)(t,My.default),a=t.name("outer");t.label(a).for(zy._`;${o}--;`,()=>t.for(zy._`${n} = ${o}; ${n}--;`,()=>t.if(zy._`${s}(${r}[${o}], ${r}[${n}])`,()=>{e.error(),t.assign(c,!1).break(a)})))}e.block$data(c,function(){const o=t.let("i",zy._`${r}.length`),n=t.let("j");e.setParams({i:o,j:n}),t.assign(c,!0),t.if(zy._`${o} > 1`,()=>(u.length>0&&!u.some(e=>"object"===e||"array"===e)?l:d)(o,n))},zy._`${a} === false`),e.ok(c)}};Cy.default=Uy;var Dy={};Object.defineProperty(Dy,"__esModule",{value:!0});const qy=Zh,Vy=Wh,Fy=jy,Ly={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>qy._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:o,schemaCode:n,schema:s}=e;o||s&&"object"==typeof s?e.fail$data(qy._`!${(0,Vy.useFunc)(t,Fy.default)}(${r}, ${n})`):e.fail(qy._`${s} !== ${r}`)}};Dy.default=Ly;var Ky={};Object.defineProperty(Ky,"__esModule",{value:!0});const Hy=Zh,Zy=Wh,Gy=jy,Jy={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>Hy._`{allowedValues: ${e}}`},code(e){const{gen:t,data:r,$data:o,schema:n,schemaCode:s,it:a}=e;if(!o&&0===n.length)throw new Error("enum must have non-empty array");const i=n.length>=a.opts.loopEnum;let c;const u=()=>null!=c?c:c=(0,Zy.useFunc)(t,Gy.default);let l;if(i||o)l=t.let("valid"),e.block$data(l,function(){t.assign(l,!1),t.forOf("v",s,e=>t.if(Hy._`${u()}(${r}, ${e})`,()=>t.assign(l,!0).break()))});else{if(!Array.isArray(n))throw new Error("ajv implementation error");const e=t.const("vSchema",s);l=(0,Hy.or)(...n.map((t,o)=>function(e,t){const o=n[t];return"object"==typeof o&&null!==o?Hy._`${u()}(${r}, ${e}[${t}])`:Hy._`${r} === ${o}`}(e,o)))}e.pass(l)}};Ky.default=Jy,Object.defineProperty(Bm,"__esModule",{value:!0});const Wy=oy,By=ay,Qy=fy,Yy=vy,Xy=by,eg=Ty,tg=Cy,rg=Dy,og=Ky,ng=[Qm.default,Wy.default,By.default,Qy.default,Yy.default,Xy.default,eg.default,tg.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},rg.default,og.default];Bm.default=ng;var sg={},ag={};Object.defineProperty(ag,"__esModule",{value:!0}),ag.validateAdditionalItems=void 0;const ig=Zh,cg=Wh,ug={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>ig.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>ig._`{limit: ${e}}`},code(e){const{parentSchema:t,it:r}=e,{items:o}=t;Array.isArray(o)?lg(e,o):(0,cg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function lg(e,t){const{gen:r,schema:o,data:n,keyword:s,it:a}=e;a.items=!0;const i=r.const("len",ig._`${n}.length`);if(!1===o)e.setParams({len:t.length}),e.pass(ig._`${i} <= ${t.length}`);else if("object"==typeof o&&!(0,cg.alwaysValidSchema)(a,o)){const o=r.var("valid",ig._`${i} <= ${t.length}`);r.if((0,ig.not)(o),()=>function(o){r.forRange("i",t.length,i,t=>{e.subschema({keyword:s,dataProp:t,dataPropType:cg.Type.Num},o),a.allErrors||r.if((0,ig.not)(o),()=>r.break())})}(o)),e.ok(o)}}ag.validateAdditionalItems=lg,ag.default=ug;var dg={},pg={};Object.defineProperty(pg,"__esModule",{value:!0}),pg.validateTuple=void 0;const hg=Zh,fg=Wh,mg=Df(),yg={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return gg(e,"additionalItems",t);r.items=!0,(0,fg.alwaysValidSchema)(r,t)||e.ok((0,mg.validateArray)(e))}};function gg(e,t,r=e.schema){const{gen:o,parentSchema:n,data:s,keyword:a,it:i}=e;!function(e){const{opts:o,errSchemaPath:n}=i,s=r.length,c=s===e.minItems&&(s===e.maxItems||!1===e[t]);if(o.strictTuples&&!c){const e=`"${a}" is ${s}-tuple, but minItems or maxItems/${t} are not specified or different at path "${n}"`;(0,fg.checkStrictMode)(i,e,o.strictTuples)}}(n),i.opts.unevaluated&&r.length&&!0!==i.items&&(i.items=fg.mergeEvaluated.items(o,r.length,i.items));const c=o.name("valid"),u=o.const("len",hg._`${s}.length`);r.forEach((t,r)=>{(0,fg.alwaysValidSchema)(i,t)||(o.if(hg._`${u} > ${r}`,()=>e.subschema({keyword:a,schemaProp:r,dataProp:r},c)),e.ok(c))})}pg.validateTuple=gg,pg.default=yg,Object.defineProperty(dg,"__esModule",{value:!0});const vg=pg,_g={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,vg.validateTuple)(e,"items")};dg.default=_g;var wg={};Object.defineProperty(wg,"__esModule",{value:!0});const $g=Zh,bg=Wh,kg=Df(),Eg=ag,Sg={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>$g.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>$g._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:o}=e,{prefixItems:n}=r;o.items=!0,(0,bg.alwaysValidSchema)(o,t)||(n?(0,Eg.validateAdditionalItems)(e,n):e.ok((0,kg.validateArray)(e)))}};wg.default=Sg;var Pg={};Object.defineProperty(Pg,"__esModule",{value:!0});const Tg=Zh,xg=Wh,Ig={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?Tg.str`must contain at least ${e} valid item(s)`:Tg.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?Tg._`{minContains: ${e}}`:Tg._`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:r,parentSchema:o,data:n,it:s}=e;let a,i;const{minContains:c,maxContains:u}=o;s.opts.next?(a=void 0===c?1:c,i=u):a=1;const l=t.const("len",Tg._`${n}.length`);if(e.setParams({min:a,max:i}),void 0===i&&0===a)return void(0,xg.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==i&&a>i)return(0,xg.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,xg.alwaysValidSchema)(s,r)){let t=Tg._`${l} >= ${a}`;return void 0!==i&&(t=Tg._`${t} && ${l} <= ${i}`),void e.pass(t)}s.items=!0;const d=t.name("valid");function p(){const e=t.name("_valid"),r=t.let("count",0);h(e,()=>t.if(e,()=>function(e){t.code(Tg._`${e}++`),void 0===i?t.if(Tg._`${e} >= ${a}`,()=>t.assign(d,!0).break()):(t.if(Tg._`${e} > ${i}`,()=>t.assign(d,!1).break()),1===a?t.assign(d,!0):t.if(Tg._`${e} >= ${a}`,()=>t.assign(d,!0)))}(r)))}function h(r,o){t.forRange("i",0,l,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:xg.Type.Num,compositeRule:!0},r),o()})}void 0===i&&1===a?h(d,()=>t.if(d,()=>t.break())):0===a?(t.let(d,!0),void 0!==i&&t.if(Tg._`${n}.length > 0`,p)):(t.let(d,!1),p()),e.result(d,()=>e.reset())}};Pg.default=Ig;var Ng={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Zh,r=Wh,o=Df();e.error={message:({params:{property:e,depsCount:r,deps:o}})=>t.str`must have ${1===r?"property":"properties"} ${o} when property ${e} is present`,params:({params:{property:e,depsCount:r,deps:o,missingProperty:n}})=>t._`{property: ${e},
11
11
  missingProperty: ${n},
12
12
  depsCount: ${r},
13
- deps: ${o}}`};const n={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const o in e){if("__proto__"===o)continue;(Array.isArray(e[o])?t:r)[o]=e[o]}return[t,r]}(e);s(e,t),a(e,r)}};function s(e,r=e.schema){const{gen:n,data:s,it:a}=e;if(0===Object.keys(r).length)return;const i=n.let("missing");for(const c in r){const u=r[c];if(0===u.length)continue;const l=(0,o.propertyInData)(n,s,c,a.opts.ownProperties);e.setParams({property:c,depsCount:u.length,deps:u.join(", ")}),a.allErrors?n.if(l,()=>{for(const t of u)(0,o.checkReportMissingProp)(e,t)}):(n.if(t._`${l} && (${(0,o.checkMissingProp)(e,u,i)})`),(0,o.reportMissingProp)(e,i),n.else())}}function a(e,t=e.schema){const{gen:n,data:s,keyword:a,it:i}=e,c=n.name("valid");for(const u in t)(0,r.alwaysValidSchema)(i,t[u])||(n.if((0,o.propertyInData)(n,s,u,i.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:u},c);e.mergeValidEvaluated(t,c)},()=>n.var(c,!0)),e.ok(c))}e.validatePropertyDeps=s,e.validateSchemaDeps=a,e.default=n}(Ng);var Cg={};Object.defineProperty(Cg,"__esModule",{value:!0});const jg=Zh,Rg=Wh,Og={message:"property name must be valid",params:({params:e})=>jg._`{propertyName: ${e.propertyName}}`},zg={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Og,code(e){const{gen:t,schema:r,data:o,it:n}=e;if((0,Rg.alwaysValidSchema)(n,r))return;const s=t.name("valid");t.forIn("key",o,r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},s),t.if((0,jg.not)(s),()=>{e.error(!0),n.allErrors||t.break()})}),e.ok(s)}};Cg.default=zg;var Ag={};Object.defineProperty(Ag,"__esModule",{value:!0});const Mg=Df(),Ug=Zh,Dg=hf(),qg=Wh,Vg={message:"must NOT have additional properties",params:({params:e})=>Ug._`{additionalProperty: ${e.additionalProperty}}`},Fg={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Vg,code(e){const{gen:t,schema:r,parentSchema:o,data:n,errsCount:s,it:a}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:i,opts:c}=a;if(a.props=!0,"all"!==c.removeAdditional&&(0,qg.alwaysValidSchema)(a,r))return;const u=(0,Mg.allSchemaProperties)(o.properties),l=(0,Mg.allSchemaProperties)(o.patternProperties);function d(e){t.code(Ug._`delete ${n}[${e}]`)}function p(o){if("all"===c.removeAdditional||c.removeAdditional&&!1===r)d(o);else{if(!1===r)return e.setParams({additionalProperty:o}),e.error(),void(i||t.break());if("object"==typeof r&&!(0,qg.alwaysValidSchema)(a,r)){const r=t.name("valid");"failing"===c.removeAdditional?(h(o,r,!1),t.if((0,Ug.not)(r),()=>{e.reset(),d(o)})):(h(o,r),i||t.if((0,Ug.not)(r),()=>t.break()))}}}function h(t,r,o){const n={keyword:"additionalProperties",dataProp:t,dataPropType:qg.Type.Str};!1===o&&Object.assign(n,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(n,r)}t.forIn("key",n,r=>{u.length||l.length?t.if(function(r){let n;if(u.length>8){const e=(0,qg.schemaRefOrVal)(a,o.properties,"properties");n=(0,Mg.isOwnProperty)(t,e,r)}else n=u.length?(0,Ug.or)(...u.map(e=>Ug._`${r} === ${e}`)):Ug.nil;return l.length&&(n=(0,Ug.or)(n,...l.map(t=>Ug._`${(0,Mg.usePattern)(e,t)}.test(${r})`))),(0,Ug.not)(n)}(r),()=>p(r)):p(r)}),e.ok(Ug._`${s} === ${Dg.default.errors}`)}};Ag.default=Fg;var Lg={};Object.defineProperty(Lg,"__esModule",{value:!0});const Kg=cm(),Hg=Df(),Zg=Wh,Gg=Ag,Jg={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:o,data:n,it:s}=e;"all"===s.opts.removeAdditional&&void 0===o.additionalProperties&&Gg.default.code(new Kg.KeywordCxt(s,Gg.default,"additionalProperties"));const a=(0,Hg.allSchemaProperties)(r);for(const e of a)s.definedProperties.add(e);s.opts.unevaluated&&a.length&&!0!==s.props&&(s.props=Zg.mergeEvaluated.props(t,(0,Zg.toHash)(a),s.props));const i=a.filter(e=>!(0,Zg.alwaysValidSchema)(s,r[e]));if(0===i.length)return;const c=t.name("valid");for(const r of i)u(r)?l(r):(t.if((0,Hg.propertyInData)(t,n,r,s.opts.ownProperties)),l(r),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(r),e.ok(c);function u(e){return s.opts.useDefaults&&!s.compositeRule&&void 0!==r[e].default}function l(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},c)}}};Lg.default=Jg;var Wg={};Object.defineProperty(Wg,"__esModule",{value:!0});const Bg=Df(),Qg=Zh,Yg=Wh,Xg=Wh,ev={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:o,parentSchema:n,it:s}=e,{opts:a}=s,i=(0,Bg.allSchemaProperties)(r),c=i.filter(e=>(0,Yg.alwaysValidSchema)(s,r[e]));if(0===i.length||c.length===i.length&&(!s.opts.unevaluated||!0===s.props))return;const u=a.strictSchema&&!a.allowMatchingProperties&&n.properties,l=t.name("valid");!0===s.props||s.props instanceof Qg.Name||(s.props=(0,Xg.evaluatedPropsToName)(t,s.props));const{props:d}=s;function p(e){for(const t in u)new RegExp(e).test(t)&&(0,Yg.checkStrictMode)(s,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function h(r){t.forIn("key",o,o=>{t.if(Qg._`${(0,Bg.usePattern)(e,r)}.test(${o})`,()=>{const n=c.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:o,dataPropType:Xg.Type.Str},l),s.opts.unevaluated&&!0!==d?t.assign(Qg._`${d}[${o}]`,!0):n||s.allErrors||t.if((0,Qg.not)(l),()=>t.break())})})}!function(){for(const e of i)u&&p(e),s.allErrors?h(e):(t.var(l,!0),h(e),t.if(l))}()}};Wg.default=ev;var tv={};Object.defineProperty(tv,"__esModule",{value:!0});const rv=Wh,ov={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:o}=e;if((0,rv.alwaysValidSchema)(o,r))return void e.fail();const n=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),e.failResult(n,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};tv.default=ov;var nv={};Object.defineProperty(nv,"__esModule",{value:!0});const sv={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Df().validateUnion,error:{message:"must match a schema in anyOf"}};nv.default=sv;var av={};Object.defineProperty(av,"__esModule",{value:!0});const iv=Zh,cv=Wh,uv={message:"must match exactly one schema in oneOf",params:({params:e})=>iv._`{passingSchemas: ${e.passing}}`},lv={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:uv,code(e){const{gen:t,schema:r,parentSchema:o,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&o.discriminator)return;const s=r,a=t.let("valid",!1),i=t.let("passing",null),c=t.name("_valid");e.setParams({passing:i}),t.block(function(){s.forEach((r,o)=>{let s;(0,cv.alwaysValidSchema)(n,r)?t.var(c,!0):s=e.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},c),o>0&&t.if(iv._`${c} && ${a}`).assign(a,!1).assign(i,iv._`[${i}, ${o}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(i,o),s&&e.mergeEvaluated(s,iv.Name)})})}),e.result(a,()=>e.reset(),()=>e.error(!0))}};av.default=lv;var dv={};Object.defineProperty(dv,"__esModule",{value:!0});const pv=Wh,hv={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const n=t.name("valid");r.forEach((t,r)=>{if((0,pv.alwaysValidSchema)(o,t))return;const s=e.subschema({keyword:"allOf",schemaProp:r},n);e.ok(n),e.mergeEvaluated(s)})}};dv.default=hv;var fv={};Object.defineProperty(fv,"__esModule",{value:!0});const mv=Zh,yv=Wh,gv={message:({params:e})=>mv.str`must match "${e.ifClause}" schema`,params:({params:e})=>mv._`{failingKeyword: ${e.ifClause}}`},vv={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:gv,code(e){const{gen:t,parentSchema:r,it:o}=e;void 0===r.then&&void 0===r.else&&(0,yv.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const n=_v(o,"then"),s=_v(o,"else");if(!n&&!s)return;const a=t.let("valid",!0),i=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);e.mergeEvaluated(t)}(),e.reset(),n&&s){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(i,c("then",r),c("else",r))}else n?t.if(i,c("then")):t.if((0,mv.not)(i),c("else"));function c(r,o){return()=>{const n=e.subschema({keyword:r},i);t.assign(a,i),e.mergeValidEvaluated(n,a),o?t.assign(o,mv._`${r}`):e.setParams({ifClause:r})}}e.pass(a,()=>e.error(!0))}};function _v(e,t){const r=e.schema[t];return void 0!==r&&!(0,yv.alwaysValidSchema)(e,r)}fv.default=vv;var wv={};Object.defineProperty(wv,"__esModule",{value:!0});const $v=Wh,bv={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,$v.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};wv.default=bv,Object.defineProperty(sg,"__esModule",{value:!0});const kv=ag,Ev=dg,Sv=pg,Pv=wg,Tv=Pg,xv=Ng,Iv=Cg,Nv=Ag,Cv=Lg,jv=Wg,Rv=tv,Ov=nv,zv=av,Av=dv,Mv=fv,Uv=wv;sg.default=function(e=!1){const t=[Rv.default,Ov.default,zv.default,Av.default,Mv.default,Uv.default,Iv.default,Nv.default,xv.default,Cv.default,jv.default];return e?t.push(Ev.default,Pv.default):t.push(kv.default,Sv.default),t.push(Tv.default),t};var Dv={},qv={};Object.defineProperty(qv,"__esModule",{value:!0});const Vv=Zh,Fv={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>Vv.str`must match format "${e}"`,params:({schemaCode:e})=>Vv._`{format: ${e}}`},code(e,t){const{gen:r,data:o,$data:n,schema:s,schemaCode:a,it:i}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=i;c.validateFormats&&(n?function(){const n=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),s=r.const("fDef",Vv._`${n}[${a}]`),i=r.let("fType"),u=r.let("format");r.if(Vv._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(i,Vv._`${s}.type || "string"`).assign(u,Vv._`${s}.validate`),()=>r.assign(i,Vv._`"string"`).assign(u,s)),e.fail$data((0,Vv.or)(!1===c.strictSchema?Vv.nil:Vv._`${a} && !${u}`,function(){const e=l.$async?Vv._`(${s}.async ? await ${u}(${o}) : ${u}(${o}))`:Vv._`${u}(${o})`,r=Vv._`(typeof ${u} == "function" ? ${e} : ${u}.test(${o}))`;return Vv._`${u} && ${u} !== true && ${i} === ${t} && !${r}`}()))}():function(){const n=d.formats[s];if(!n)return void function(){if(!1===c.strictSchema)return void d.logger.warn(e());throw new Error(e());function e(){return`unknown format "${s}" ignored in schema at path "${u}"`}}();if(!0===n)return;const[a,i,p]=function(e){const t=e instanceof RegExp?(0,Vv.regexpCode)(e):c.code.formats?Vv._`${c.code.formats}${(0,Vv.getProperty)(s)}`:void 0,o=r.scopeValue("formats",{key:s,ref:e,code:t});if("object"==typeof e&&!(e instanceof RegExp))return[e.type||"string",e.validate,Vv._`${o}.validate`];return["string",e,o]}(n);a===t&&e.pass(function(){if("object"==typeof n&&!(n instanceof RegExp)&&n.async){if(!l.$async)throw new Error("async format in sync schema");return Vv._`await ${p}(${o})`}return"function"==typeof i?Vv._`${p}(${o})`:Vv._`${p}.test(${o})`}())}())}};qv.default=Fv,Object.defineProperty(Dv,"__esModule",{value:!0});const Lv=[qv.default];Dv.default=Lv;var Kv={};Object.defineProperty(Kv,"__esModule",{value:!0}),Kv.contentVocabulary=Kv.metadataVocabulary=void 0,Kv.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Kv.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(Om,"__esModule",{value:!0});const Hv=Bm,Zv=sg,Gv=Dv,Jv=Kv,Wv=[zm.default,Hv.default,(0,Zv.default)(),Gv.default,Jv.metadataVocabulary,Jv.contentVocabulary];Om.default=Wv;var Bv,Qv={},Yv={};Object.defineProperty(Yv,"__esModule",{value:!0}),Yv.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(Bv||(Yv.DiscrError=Bv={})),Object.defineProperty(Qv,"__esModule",{value:!0});const Xv=Zh,e_=Yv,t_=mm,r_=fm(),o_=Wh,n_={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===e_.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>Xv._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},code(e){const{gen:t,data:r,schema:o,parentSchema:n,it:s}=e,{oneOf:a}=n;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const i=o.propertyName;if("string"!=typeof i)throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");const c=t.let("valid",!1),u=t.const("tag",Xv._`${r}${(0,Xv.getProperty)(i)}`);function l(r){const o=t.name("valid"),n=e.subschema({keyword:"oneOf",schemaProp:r},o);return e.mergeEvaluated(n,Xv.Name),o}t.if(Xv._`typeof ${u} == "string"`,()=>function(){const r=function(){var e;const t={},r=c(n);let o=!0;for(let t=0;t<a.length;t++){let n=a[t];if((null==n?void 0:n.$ref)&&!(0,o_.schemaHasRulesButRef)(n,s.self.RULES)){const e=n.$ref;if(n=t_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,e),n instanceof t_.SchemaEnv&&(n=n.schema),void 0===n)throw new r_.default(s.opts.uriResolver,s.baseId,e)}const l=null===(e=null==n?void 0:n.properties)||void 0===e?void 0:e[i];if("object"!=typeof l)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);o=o&&(r||c(n)),u(l,t)}if(!o)throw new Error(`discriminator: "${i}" must be required`);return t;function c({required:e}){return Array.isArray(e)&&e.includes(i)}function u(e,t){if(e.const)l(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`);for(const r of e.enum)l(r,t)}}function l(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${i}" values must be unique strings`);t[e]=r}}();t.if(!1);for(const e in r)t.elseIf(Xv._`${u} === ${e}`),t.assign(c,l(r[e]));t.else(),e.error(!1,{discrError:e_.DiscrError.Mapping,tag:u,tagName:i}),t.endIf()}(),()=>e.error(!1,{discrError:e_.DiscrError.Tag,tag:u,tagName:i})),e.ok(c)}};Qv.default=n_;var s_={$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:!0,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:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},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:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},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:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},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:!0};!function(e,t){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 r=Fh,o=Om,n=Qv,s=s_,a=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),o.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(n.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(e,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=cm();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=Zh;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 d=dm();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var p=fm();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}(Vh,Vh.exports);var a_=Vh.exports;!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=a_,r=Zh,o=r.operators,n={formatMaximum:{okStr:"<=",ok:o.LTE,fail:o.GT},formatMinimum:{okStr:">=",ok:o.GTE,fail:o.LT},formatExclusiveMaximum:{okStr:"<",ok:o.LT,fail:o.GTE},formatExclusiveMinimum:{okStr:">",ok:o.GT,fail:o.LTE}},s={message:({keyword:e,schemaCode:t})=>r.str`should be ${n[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>r._`{comparison: ${n[e].okStr}, limit: ${t}}`};e.formatLimitDefinition={keyword:Object.keys(n),type:"string",schemaType:"string",$data:!0,error:s,code(e){const{gen:o,data:s,schemaCode:a,keyword:i,it:c}=e,{opts:u,self:l}=c;if(!u.validateFormats)return;const d=new t.KeywordCxt(c,l.RULES.all.format.definition,"format");function p(e){return r._`${e}.compare(${s}, ${a}) ${n[i].fail} 0`}d.$data?function(){const t=o.scopeValue("formats",{ref:l.formats,code:u.code.formats}),n=o.const("fmt",r._`${t}[${d.schemaCode}]`);e.fail$data((0,r.or)(r._`typeof ${n} != "object"`,r._`${n} instanceof RegExp`,r._`typeof ${n}.compare != "function"`,p(n)))}():function(){const t=d.schema,n=l.formats[t];if(!n||!0===n)return;if("object"!=typeof n||n instanceof RegExp||"function"!=typeof n.compare)throw new Error(`"${i}": format "${t}" does not define "compare" function`);const s=o.scopeValue("formats",{key:t,ref:n,code:u.code.formats?r._`${u.code.formats}${(0,r.getProperty)(t)}`:void 0});e.fail$data(p(s))}()},dependencies:["format"]};e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)}(qh),function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Dh,o=qh,n=Zh,s=new n.Name("fullFormats"),a=new n.Name("fastFormats"),i=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,r.fullFormats,s),e;const[n,i]="fast"===t.mode?[r.fastFormats,a]:[r.fullFormats,s];return c(e,t.formats||r.formatNames,n,i),t.keywords&&(0,o.default)(e),e};function c(e,t,r,o){var s,a;null!==(s=(a=e.opts.code).formats)&&void 0!==s||(a.formats=n._`require("ajv-formats/dist/formats").${o}`);for(const o of t)e.addFormat(o,r[o])}i.get=(e,t="full")=>{const o=("fast"===t?r.fastFormats:r.fullFormats)[e];if(!o)throw new Error(`Unknown format "${e}"`);return o},e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i}(Uh,Uh.exports);var i_=ji(Uh.exports);class c_{constructor(e){this._ajv=e??function(){const e=new Mh({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return i_(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 u_{constructor(e){this._client=e}async*callToolStream(e,t=Oa,r){const o=this._client,n={...r,task:r?.task??(o.isToolTask(e.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:e},t,n),a=o.getToolOutputValidator(e.name);for await(const t of s){if("result"===t.type&&a){const r=t.result;if(!r.structuredContent&&!r.isError)return void(yield{type:"error",error:new Si(as.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)});if(r.structuredContent)try{const e=a(r.structuredContent);if(!e.valid)return void(yield{type:"error",error:new Si(as.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)})}catch(e){return e instanceof Si?void(yield{type:"error",error:e}):void(yield{type:"error",error:new Si(as.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)})}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}function l_(e,t){if(e&&null!==t&&"object"==typeof t){if("object"===e.type&&e.properties&&"object"==typeof e.properties){const r=t,o=e.properties;for(const e of Object.keys(o)){const t=o[e];void 0===r[e]&&Object.prototype.hasOwnProperty.call(t,"default")&&(r[e]=t.default),void 0!==r[e]&&l_(t,r[e])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)"boolean"!=typeof r&&l_(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)"boolean"!=typeof r&&l_(r,t)}}class d_ extends Ni{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new c_,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Ma,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",xa,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",ia,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new u_(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 o=e,n=t[o];if(void 0===n)continue;const s=r[o];Ci(s)&&Ci(n)?r[o]={...s,...n}:r[o]=n}return r}(this._capabilities,e)}setRequestHandler(e,t){const r=so(e),o=r?.method;if(!o)throw new Error("Schema is missing a method literal");let n;if(oo(o)){const e=o,t=e._zod?.def;n=t?.value??e.value}else{const e=o,t=e._def;n=t?.value??e.value}if("string"!=typeof n)throw new Error("Schema method literal must be a string");const s=n;if("elicitation/create"===s){const r=async(e,r)=>{const o=no(pi,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Si(as.InvalidParams,`Invalid elicitation request: ${e}`)}const{params:n}=o.data;n.mode=n.mode??"form";const{supportsFormMode:s,supportsUrlMode:a}=function(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=void 0!==e.form,r=void 0!==e.url;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}(this._capabilities.elicitation);if("form"===n.mode&&!s)throw new Si(as.InvalidParams,"Client does not support form-mode elicitation requests");if("url"===n.mode&&!a)throw new Si(as.InvalidParams,"Client does not support URL-mode elicitation requests");const i=await Promise.resolve(t(e,r));if(n.task){const e=no(zs,i);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Si(as.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const c=no(mi,i);if(!c.success){const e=c.error instanceof Error?c.error.message:String(c.error);throw new Si(as.InvalidParams,`Invalid elicitation result: ${e}`)}const u=c.data,l="form"===n.mode?n.requestedSchema:void 0;if("form"===n.mode&&"accept"===u.action&&u.content&&l&&this._capabilities.elicitation?.form?.applyDefaults)try{l_(l,u.content)}catch{}return u};return super.setRequestHandler(e,r)}if("sampling/createMessage"===s){const r=async(e,r)=>{const o=no(Ya,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Si(as.InvalidParams,`Invalid sampling request: ${e}`)}const{params:n}=o.data,s=await Promise.resolve(t(e,r));if(n.task){const e=no(zs,s);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Si(as.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const a=no(n.tools||n.toolChoice?ei:Xa,s);if(!a.success){const e=a.error instanceof Error?a.error.message:String(a.error);throw new Si(as.InvalidParams,`Invalid sampling result: ${e}`)}return a.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),void 0===e.sessionId)try{const r=await this.request({method:"initialize",params:{protocolVersion:Mn,capabilities:this._capabilities,clientInfo:this._clientInfo}},Es,t);if(void 0===r)throw new Error(`Server sent invalid initialize result: ${r}`);if(!Un.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if("notifications/roots/list_changed"===e)if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client 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})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`)}(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&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._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},us,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},wi,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},us,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},Ta,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},ga,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},ea,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},ra,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},aa,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},us,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},us,t)}async callTool(e,t=Oa,r){if(this.isToolTaskRequired(e.name))throw new Si(as.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:e},t,r),n=this.getToolOutputValidator(e.name);if(n){if(!o.structuredContent&&!o.isError)throw new Si(as.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const e=n(o.structuredContent);if(!e.valid)throw new Si(as.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){if(e instanceof Si)throw e;throw new Si(as.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}isToolTask(e){return!!this._serverCapabilities?.tasks?.requests?.tools?.call&&this._cachedKnownTaskTools.has(e)}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}const e=t.execution?.taskSupport;"required"!==e&&"optional"!==e||this._cachedKnownTaskTools.add(t.name),"required"===e&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Ra,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,o){const n=Ua.safeParse(r);if(!n.success)throw new Error(`Invalid ${e} listChanged options: ${n.error.message}`);if("function"!=typeof r.onChanged)throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:s,debounceMs:a}=n.data,{onChanged:i}=r,c=async()=>{if(s)try{const e=await o();i(null,e)}catch(e){const t=e instanceof Error?e:new Error(String(e));i(t,null)}else i(null,null)};this.setNotificationHandler(t,()=>{if(a){const t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);const r=setTimeout(c,a);this._listChangedDebounceTimers.set(e,r)}else c()})}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function p_(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}const h_=Gr(xo,f_).superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:An,message:"URL must be parseable",fatal:!0}),ae}).refine(e=>{const t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"});var f_;const m_=cn({resource:ko().url(),authorization_servers:nn(h_).optional(),jwks_uri:ko().url().optional(),scopes_supported:nn(ko()).optional(),bearer_methods_supported:nn(ko()).optional(),resource_signing_alg_values_supported:nn(ko()).optional(),resource_name:ko().optional(),resource_documentation:ko().optional(),resource_policy_uri:ko().url().optional(),resource_tos_uri:ko().url().optional(),tls_client_certificate_bound_access_tokens:Wo().optional(),authorization_details_types_supported:nn(ko()).optional(),dpop_signing_alg_values_supported:nn(ko()).optional(),dpop_bound_access_tokens_required:Wo().optional()}),y_=cn({issuer:ko(),authorization_endpoint:h_,token_endpoint:h_,registration_endpoint:h_.optional(),scopes_supported:nn(ko()).optional(),response_types_supported:nn(ko()),response_modes_supported:nn(ko()).optional(),grant_types_supported:nn(ko()).optional(),token_endpoint_auth_methods_supported:nn(ko()).optional(),token_endpoint_auth_signing_alg_values_supported:nn(ko()).optional(),service_documentation:h_.optional(),revocation_endpoint:h_.optional(),revocation_endpoint_auth_methods_supported:nn(ko()).optional(),revocation_endpoint_auth_signing_alg_values_supported:nn(ko()).optional(),introspection_endpoint:ko().optional(),introspection_endpoint_auth_methods_supported:nn(ko()).optional(),introspection_endpoint_auth_signing_alg_values_supported:nn(ko()).optional(),code_challenge_methods_supported:nn(ko()).optional(),client_id_metadata_document_supported:Wo().optional()}),g_=an({...cn({issuer:ko(),authorization_endpoint:h_,token_endpoint:h_,userinfo_endpoint:h_.optional(),jwks_uri:h_,registration_endpoint:h_.optional(),scopes_supported:nn(ko()).optional(),response_types_supported:nn(ko()),response_modes_supported:nn(ko()).optional(),grant_types_supported:nn(ko()).optional(),acr_values_supported:nn(ko()).optional(),subject_types_supported:nn(ko()),id_token_signing_alg_values_supported:nn(ko()),id_token_encryption_alg_values_supported:nn(ko()).optional(),id_token_encryption_enc_values_supported:nn(ko()).optional(),userinfo_signing_alg_values_supported:nn(ko()).optional(),userinfo_encryption_alg_values_supported:nn(ko()).optional(),userinfo_encryption_enc_values_supported:nn(ko()).optional(),request_object_signing_alg_values_supported:nn(ko()).optional(),request_object_encryption_alg_values_supported:nn(ko()).optional(),request_object_encryption_enc_values_supported:nn(ko()).optional(),token_endpoint_auth_methods_supported:nn(ko()).optional(),token_endpoint_auth_signing_alg_values_supported:nn(ko()).optional(),display_values_supported:nn(ko()).optional(),claim_types_supported:nn(ko()).optional(),claims_supported:nn(ko()).optional(),service_documentation:ko().optional(),claims_locales_supported:nn(ko()).optional(),ui_locales_supported:nn(ko()).optional(),claims_parameter_supported:Wo().optional(),request_parameter_supported:Wo().optional(),request_uri_parameter_supported:Wo().optional(),require_request_uri_registration:Wo().optional(),op_policy_uri:h_.optional(),op_tos_uri:h_.optional(),client_id_metadata_document_supported:Wo().optional()}).shape,...y_.pick({code_challenge_methods_supported:!0}).shape}),v_=an({access_token:ko(),id_token:ko().optional(),token_type:ko(),expires_in:function(e){return function(e,t){return new e({type:"number",coerce:!0,checks:[],...Se(t)})}(Ko,e)}().optional(),scope:ko().optional(),refresh_token:ko().optional()}).strip(),__=an({error:ko(),error_description:ko().optional(),error_uri:ko().optional()}),w_=h_.optional().or(wn("").transform(()=>{})),$_=an({redirect_uris:nn(h_),token_endpoint_auth_method:ko().optional(),grant_types:nn(ko()).optional(),response_types:nn(ko()).optional(),client_name:ko().optional(),client_uri:h_.optional(),logo_uri:w_,scope:ko().optional(),contacts:nn(ko()).optional(),tos_uri:w_,policy_uri:ko().optional(),jwks_uri:h_.optional(),jwks:new Yo({type:"any"}).optional(),software_id:ko().optional(),software_version:ko().optional(),software_statement:ko().optional()}).strip(),b_=an({client_id:ko(),client_secret:ko().optional(),client_id_issued_at:Ho().optional(),client_secret_expires_at:Ho().optional()}).strip(),k_=$_.merge(b_);an({error:ko(),error_description:ko().optional()}).strip(),an({token:ko(),token_type_hint:ko().optional()}).strip();class E_ extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class S_ extends E_{}S_.errorCode="invalid_request";class P_ extends E_{}P_.errorCode="invalid_client";class T_ extends E_{}T_.errorCode="invalid_grant";class x_ extends E_{}x_.errorCode="unauthorized_client";class I_ extends E_{}I_.errorCode="unsupported_grant_type";class N_ extends E_{}N_.errorCode="invalid_scope";class C_ extends E_{}C_.errorCode="access_denied";class j_ extends E_{}j_.errorCode="server_error";class R_ extends E_{}R_.errorCode="temporarily_unavailable";class O_ extends E_{}O_.errorCode="unsupported_response_type";class z_ extends E_{}z_.errorCode="unsupported_token_type";class A_ extends E_{}A_.errorCode="invalid_token";class M_ extends E_{}M_.errorCode="method_not_allowed";class U_ extends E_{}U_.errorCode="too_many_requests";class D_ extends E_{}D_.errorCode="invalid_client_metadata";class q_ extends E_{}q_.errorCode="insufficient_scope";class V_ extends E_{}V_.errorCode="invalid_target";const F_={[S_.errorCode]:S_,[P_.errorCode]:P_,[T_.errorCode]:T_,[x_.errorCode]:x_,[I_.errorCode]:I_,[N_.errorCode]:N_,[C_.errorCode]:C_,[j_.errorCode]:j_,[R_.errorCode]:R_,[O_.errorCode]:O_,[z_.errorCode]:z_,[A_.errorCode]:A_,[M_.errorCode]:M_,[U_.errorCode]:U_,[D_.errorCode]:D_,[q_.errorCode]:q_,[V_.errorCode]:V_};class L_ extends Error{constructor(e){super(e??"Unauthorized")}}const K_="code",H_="S256";function Z_(e,t,r,o){const{client_id:n,client_secret:s}=t;switch(e){case"client_secret_basic":return void function(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}(n,s,r);case"client_secret_post":return void function(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}(n,s,o);case"none":return void function(e,t){t.set("client_id",e)}(n,o);default:throw new Error(`Unsupported client authentication method: ${e}`)}}async function G_(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=__.parse(JSON.parse(r)),{error:t,error_description:o,error_uri:n}=e;return new(F_[t]||j_)(o||"",n)}catch(e){return new j_(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function J_(e,t){try{return await W_(e,t)}catch(r){if(r instanceof P_||r instanceof x_)return await(e.invalidateCredentials?.("all")),await W_(e,t);if(r instanceof T_)return await(e.invalidateCredentials?.("tokens")),await W_(e,t);throw r}}async function W_(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:n,fetchFn:s}){let a,i;try{a=await async function(e,t,r=fetch){const o=await async function(e,t,r,o){const n=new URL(e),s=o?.protocolVersion??Mn;let a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{const e=function(e,t="",r={}){t.endsWith("/")&&(t=t.slice(0,-1));return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,n.pathname);a=new URL(e,o?.metadataServerUrl??n),a.search=n.search}let i=await X_(a,s,r);if(!o?.metadataUrl&&function(e,t){return!e||e.status>=400&&e.status<500&&"/"!==t}(i,n.pathname)){const e=new URL(`/.well-known/${t}`,n);i=await X_(e,s,r)}return i}(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||404===o.status)throw await(o?.body?.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await(o.body?.cancel()),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return m_.parse(await o.json())}(t,{resourceMetadataUrl:n},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",t));const c=await async function(e,t,r){const o=function(e){const t="string"==typeof e?new URL(e):new URL(e.href);return t.hash="",t}(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!function({requestedResource:e,configuredResource:t}){const r="string"==typeof e?new URL(e):new URL(e.href),o="string"==typeof t?new URL(t):new URL(t.href);if(r.origin!==o.origin)return!1;if(r.pathname.length<o.pathname.length)return!1;const n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(s)}({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}(t,e,a),l=await async function(e,{fetchFn:t=fetch,protocolVersion:r=Mn}={}){const o={"MCP-Protocol-Version":r,Accept:"application/json"},n=function(e){const t="string"==typeof e?new URL(e):e,r="/"!==t.pathname,o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;n.endsWith("/")&&(n=n.slice(0,-1));return o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"}),o.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}(e);for(const{url:e,type:r}of n){const n=await Y_(e,o,t);if(n){if(!n.ok){if(await(n.body?.cancel()),n.status>=400&&n.status<500)continue;throw new Error(`HTTP ${n.status} trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`)}return"oauth"===r?y_.parse(await n.json()):g_.parse(await n.json())}}return}(i,{fetchFn:s});let d=await Promise.resolve(e.clientInformation());if(!d){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const t=!0===l?.client_id_metadata_document_supported,o=e.clientMetadataUrl;if(o&&!function(e){if(!e)return!1;try{const t=new URL(e);return"https:"===t.protocol&&"/"!==t.pathname}catch{return!1}}(o))throw new D_(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${o}`);if(t&&o)d={client_id:o},await(e.saveClientInformation?.(d));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const t=await async function(e,{metadata:t,clientMetadata:r,fetchFn:o}){let n;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(t.registration_endpoint)}else n=new URL("/register",e);const s=await(o??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await G_(s);return k_.parse(await s.json())}(i,{metadata:l,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(t),d=t}}const p=!e.redirectUrl;if(void 0!==r||p){const t=await async function(e,t,{metadata:r,resource:o,authorizationCode:n,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a));if(!i){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");i=function(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}(n,await e.codeVerifier(),e.redirectUrl)}const c=await e.clientInformation();return ew(t,{metadata:r,tokenRequestParams:i,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:s})}(e,i,{metadata:l,resource:c,authorizationCode:r,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}const h=await e.tokens();if(h?.refresh_token)try{const t=await async function(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),c=await ew(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:n,fetchFn:a});return{refresh_token:o,...c}}(i,{metadata:l,clientInformation:d,refreshToken:h.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof E_&&!(e instanceof j_))throw e}const f=e.state?await e.state():void 0,{authorizationUrl:m,codeVerifier:y}=await async function(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(K_))throw new Error(`Incompatible auth server: does not support response type ${K_}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(H_))throw new Error(`Incompatible auth server: does not support code challenge method ${H_}`)}else i=new URL("/authorize",e);const c=await u(),l=c.code_verifier,d=c.code_challenge;i.searchParams.set("response_type",K_),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",d),i.searchParams.set("code_challenge_method",H_),i.searchParams.set("redirect_uri",String(o)),s&&i.searchParams.set("state",s);n&&i.searchParams.set("scope",n);n?.includes("offline_access")&&i.searchParams.append("prompt","consent");a&&i.searchParams.set("resource",a.href);return{authorizationUrl:i,codeVerifier:l}}(i,{metadata:l,clientInformation:d,state:f,redirectUrl:e.redirectUrl,scope:o||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(y),await e.redirectToAuthorization(m),"REDIRECT"}function B_(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,o]=t.split(" ");if("bearer"!==r.toLowerCase()||!o)return{};const n=Q_(e,"resource_metadata")||void 0;let s;if(n)try{s=new URL(n)}catch{}return{resourceMetadataUrl:s,scope:Q_(e,"scope")||void 0,error:Q_(e,"error")||void 0}}function Q_(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),n=r.match(o);return n?n[1]||n[2]:null}async function Y_(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Y_(e,void 0,r):void 0;throw o}}async function X_(e,t,r=fetch){const o={"MCP-Protocol-Version":t};return await Y_(e,o,r)}async function ew(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:s,fetchFn:a}){const i=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),n)await n(c,r,i,t);else if(o){const e=function(e,t){const r=void 0!==e.client_secret;return 0===t.length?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&(o=e.token_endpoint_auth_method,["client_secret_basic","client_secret_post","none"].includes(o))&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none";var o}(o,t?.token_endpoint_auth_methods_supported??[]);Z_(e,o,c,r)}const u=await(a??fetch)(i,{method:"POST",headers:c,body:r});if(!u.ok)throw await G_(u);return v_.parse(await u.json())}class tw extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function rw(e){}function ow(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=rw,onError:r=rw,onRetry:o=rw,onComment:n}=e;let s,a="",i=!0,c="",u="";function l(e){if(""===e)return c.length>0&&t({id:s,event:u||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),s=void 0,c="",void(u="");if(e.startsWith(":"))return void(n&&n(e.slice(e.startsWith(": ")?2:1)));const r=e.indexOf(":");if(-1!==r){const t=e.slice(0,r),o=" "===e[r+1]?2:1;return void d(t,e.slice(r+o),e)}d(e,"",e)}function d(e,t,n){switch(e){case"event":u=t;break;case"data":c=`${c}${t}\n`;break;case"id":s=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?o(parseInt(t,10)):r(new tw(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:n}));break;default:r(new tw(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:n}))}}return{feed:function(e){const t=i?e.replace(/^\xEF\xBB\xBF/,""):e,[r,o]=function(e){const t=[];let r="",o=0;for(;o<e.length;){const n=e.indexOf("\r",o),s=e.indexOf("\n",o);let a=-1;if(-1!==n&&-1!==s?a=Math.min(n,s):-1!==n?a=n:-1!==s&&(a=s),-1===a){r=e.slice(o);break}{const r=e.slice(o,a);t.push(r),o=a+1,"\r"===e[o-1]&&"\n"===e[o]&&o++}}return[t,r]}(`${a}${t}`);for(const e of r)l(e);a=o,i=!1},reset:function(e={}){a&&e.consume&&l(a),i=!0,s=void 0,c="",u="",a=""}}}class nw extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let o;super({start(n){o=ow({onEvent:e=>{n.enqueue(e)},onError(t){"terminate"===e?n.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:r})},transform(e){o.feed(e)}})}}const sw={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class aw extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class iw{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=function(e=fetch,t){return t?async(r,o)=>{const n={...t,...o,headers:o?.headers?{...p_(t.headers),...p_(o.headers)}:t.headers};return e(r,n)}:e}(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??sw}async _authThenStart(){if(!this._authProvider)throw new L_("No auth provider");let e;try{e=await J_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new L_;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=p_(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){const{resumptionToken:t}=e;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);const o=await(this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!o.ok){if(await(o.body?.cancel()),401===o.status&&this._authProvider)return await this._authThenStart();if(405===o.status)return;throw new aw(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(void 0!==this._serverRetryMs)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){const r=this._reconnectionOptions.maxRetries;if(t>=r)return void this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));const o=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},o)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:o,replayMessageId:n}=t;let s,a=!1,i=!1;(async()=>{try{const t=e.pipeThrough(new TextDecoderStream).pipeThrough(new nw({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){const{value:e,done:r}=await t.read();if(r)break;if(e.id&&(s=e.id,a=!0,o?.(e.id)),e.data&&(!e.event||"message"===e.event))try{const t=cs.parse(JSON.parse(e.data));ss(t)&&(i=!0,void 0!==n&&(t.id=n)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(r||a)&&!i&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:n},0)}catch(e){this.onerror?.(new Error(`SSE stream disconnected: ${e}`));if((r||a)&&!i&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:n},0)}catch(e){this.onerror?.(new Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new L_("No auth provider");if("AUTHORIZED"!==await J_(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new L_("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{const{resumptionToken:o,onresumptiontoken:n}=t||{};if(o)return void this._startOrAuthSse({resumptionToken:o,replayMessageId:rs(e)?e.id:void 0}).catch(e=>this.onerror?.(e));const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),c=i.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!i.ok){const t=await i.text().catch(()=>null);if(401===i.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new aw(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:t,scope:r}=B_(i);this._resourceMetadataUrl=t,this._scope=r;if("AUTHORIZED"!==await J_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new L_;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===i.status&&this._authProvider){const{resourceMetadataUrl:t,scope:r,error:o}=B_(i);if("insufficient_scope"===o){const o=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===o)throw new aw(403,"Server returned 403 after trying upscoping");r&&(this._scope=r),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=o??void 0;if("AUTHORIZED"!==await J_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch}))throw new L_;return this.send(e)}}throw new aw(i.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===i.status)return await(i.body?.cancel()),r=e,void(Ss.safeParse(r).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e)));const u=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,l=i.headers.get("content-type");if(u)if(l?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:n},!1);else{if(!l?.includes("application/json"))throw await(i.body?.cancel()),new aw(-1,`Unexpected content type: ${l}`);{const e=await i.json(),t=Array.isArray(e)?e.map(e=>cs.parse(e)):[cs.parse(e)];for(const e of t)this.onmessage?.(e)}}else await(i.body?.cancel())}catch(e){throw this.onerror?.(e),e}var r}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._url,t);if(await(r.body?.cancel()),!r.ok&&405!==r.status)throw new aw(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}const cw=M("quickstart");async function uw(e,t,r={}){const{serverId:o,serverSlug:n,proxyBaseUrl:s="http://proxy-ingress:8080",transport:a="streamable-http"}=r,i=o||n||t;let c;try{c=await e.getServer(i)}catch(e){if(e instanceof g&&404===e.statusCode)throw new v(i);throw e}const u=c.slug||i;let l;if(z(e.token)){l=`${O(e.token).baseUrl}/mcp/${u}`}else{cw.warn("Token has no organization information, using static config for MCP connection");l=`${R().baseUrl}/mcp/${u}`}return[{url:l,transport:a,headers:{Accept:"application/json, text/event-stream",Authorization:`Bearer ${e.token}`,"x-barndoor-session-id":lw()}},l]}function lw(){if(I&&"function"==typeof n.randomUUID)return n.randomUUID();if("undefined"!=typeof globalThis&&globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e;if(I&&"function"==typeof n.randomBytes)e=n.randomBytes(16);else{if("undefined"==typeof globalThis||!globalThis.crypto?.getRandomValues)throw new Error("Secure random generator not available for UUID.");e=new Uint8Array(16),globalThis.crypto.getRandomValues(e)}const t=e??new Uint8Array(0);if(t.length<16)throw new Error("Secure random generator not available for UUID.");const r=t[6],o=t[8];t[6]=15&r|64,t[8]=63&o|128;const s=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${s.substring(0,8)}-${s.substring(8,12)}-${s.substring(12,16)}-${s.substring(16,20)}-${s.substring(20)}`}const dw=function(){try{if("undefined"!=typeof process&&process.versions?.node){const e=a.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(e).href:d&&"SCRIPT"===d.tagName.toUpperCase()&&d.src||new URL("index.js",document.baseURI).href),r=t.dirname(e),o=t.join(r,"..","package.json");return JSON.parse(l.readFileSync(o,"utf8")).version}return'"0.4.3"'}catch(e){return console.warn("Could not read version from package.json:",e),"0.1.0"}}();exports.AUTH_CONFIG=T,exports.AgentToken=P,exports.AuthenticationError=h,exports.BarndoorConfig=C,exports.BarndoorError=p,exports.BarndoorSDK=se,exports.ConfigurationError=w,exports.ConnectionError=y,exports.HTTPError=g,exports.OAuthError=_,exports.PKCEManager=te,exports.ServerDetail=S,exports.ServerNotFoundError=v,exports.ServerSummary=E,exports.TimeoutError=$,exports.TokenError=f,exports.TokenExpiredError=m,exports.TokenManager=Y,exports.TokenValidationError=class extends f{},exports.checkTokenOrganization=function(e){return j(e)},exports.clearCachedToken=async function(){const e=W();await e.clearToken()},exports.clearOidcConfigCache=function(){D.clear()},exports.createScopedLogger=M,exports.debug=function(e,...t){A.debug(e,...t)},exports.ensureServerConnected=async function(e,t,r={}){const{timeout:o=90}=r;cw.info(`Ensuring ${t} server is connected`);try{await e.ensureServerConnected(t,{pollSeconds:o}),cw.info(`Server ${t} connected successfully`)}catch(e){throw e instanceof v?cw.error(`Server '${t}' not found`):cw.error(`Failed to connect to ${t}:`,e),e}},exports.error=function(e,...t){A.error(e,...t)},exports.getDynamicConfig=O,exports.getLogger=function(){return A},exports.getOidcConfig=q,exports.getStaticConfig=R,exports.hasOrganizationInfo=z,exports.info=function(e,...t){A.info(e,...t)},exports.isBrowser=x,exports.isNode=I,exports.isTokenActive=async function(e){try{const e=W(),t=await e.loadToken();if(!t?.access_token)return!1;const r=R(),o=(await q(r.authIssuer)).userinfo_endpoint,n=fetch(o,{headers:{Authorization:`Bearer ${t.access_token}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(1e4)}:{}});return(await F(n,1e4)).ok}catch(e){return!1}},exports.isTokenActiveWithRefresh=async function(e){try{const t=new Y(e||"");return await t.getValidToken(),!0}catch(e){return U.warn("Token validation/refresh failed:",e),!1}},exports.loadUserToken=X,exports.loginInteractive=async function(t={}){if(!I)throw new Error("Interactive login is only available in Node.js environment");cw.info("Starting interactive login flow");const r=R();let o;o=t.authIssuer?t.authIssuer:t.authDomain?t.authDomain.startsWith("http")?t.authDomain:`https://${t.authDomain}`:r.authIssuer;const{clientId:n=r.clientId,clientSecret:s=r.clientSecret,audience:a=r.apiAudience,baseUrl:u,port:l=52765}=t;if(!n||!s)throw new Error("AGENT_CLIENT_ID / AGENT_CLIENT_SECRET not set – create a .env file or export in the shell");const d=await X();if(d)try{let e;z(d)?e=O(d):(cw.warn("Cached token has no organization information, using static config"),e=R());const t=new se(e.baseUrl,{token:d});return await t.validateCachedToken(),cw.info("Using cached valid token"),t}catch(e){cw.info("Cached token invalid, starting OAuth flow")}else cw.info("No cached token, starting OAuth flow");const p="undefined"!=typeof process&&!(!process.env||"1"!==process.env.BARNDOOR_MANUAL_CODE&&"true"!==process.env.BARNDOOR_MANUAL_CODE);let h,f=null;if(p){const e=process.env&&process.env.BARNDOOR_REDIRECT_HOST||"127.0.0.1";h=e.startsWith("http")?`${e}:${l}/cb`:`http://${e}:${l}/cb`}else{const e=ne(l);h=e[0],f=e[1]}const m=new te,y=await m.buildAuthorizationUrl({clientId:n,redirectUri:h,audience:a,issuer:o});cw.info(`Auth URL: ${y}`);const g=e.platform();let v,_;try{v=new URL(y)}catch{throw new Error("Invalid auth URL")}if("https:"!==v.protocol&&("http:"!==v.protocol||"localhost"!==v.hostname&&"127.0.0.1"!==v.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===g?i.spawn("open",[y],{detached:!0,stdio:"ignore"}).unref():"win32"===g?i.spawn("powershell",["-NoProfile","Start-Process",y],{detached:!0,stdio:"ignore"}).unref():i.spawn("xdg-open",[y],{detached:!0,stdio:"ignore"}).unref(),cw.info("Please complete login in your browser…")}catch(e){cw.warn("Failed to open browser automatically. Please visit:",y)}if(p){const e=await new Promise(e=>{const t=c.createInterface({input:process.stdin,output:process.stdout});t.question("Paste the full redirected URL (or just the code= value): ",r=>{t.close(),e(r.trim())})});try{const t=new URL(e);_=t.searchParams.get("code")||e}catch{_=e}}else{const e=new Promise((e,t)=>{setTimeout(()=>{t(new Error(`OAuth callback timeout after 2 minutes. This usually means the callback URL is not registered in Auth0. Please add "${h}" to Allowed Callback URLs in your Auth0 application settings.`))},12e4)});_=(await Promise.race([f,e]))[0]}const w=await m.exchangeCodeForToken({clientId:n,clientSecret:s,code:_,redirectUri:h,issuer:o});let $;if(await ee(w),u)$=u;else if(z(w.access_token)){$=O(w.access_token).baseUrl}else cw.warn("New token has no organization information, using static config"),$=R().baseUrl;return new se($,{token:w.access_token})},exports.makeMcpClient=async function(e,t,r={}){const[o]=await uw(e,t,r),n=o,s=new d_({name:"barndoor-js-sdk",version:"0.1.0"}),a=new iw(new URL(n.url),{requestInit:{headers:n.headers}});return await s.connect(a),s},exports.makeMcpConnectionParams=uw,exports.saveUserToken=ee,exports.setLogger=function(e){A=e},exports.setTokenLogger=function(e){console.warn("setTokenLogger is deprecated. Use setLogger from the main logging module instead.")},exports.startLocalCallbackServer=ne,exports.validateToken=async function(e,t){try{const t=R(),r=await B(e,t.authIssuer,t.apiAudience);if(r===exports.JWTVerificationResult.VALID)return{valid:!0};if(r===exports.JWTVerificationResult.INVALID)try{const r=(await q(t.authIssuer)).userinfo_endpoint,o=fetch(r,{headers:{Authorization:`Bearer ${e}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(5e3)}:{}});return{valid:(await F(o,5e3)).ok}}catch(e){return U.warn("Remote token validation failed:",e),{valid:!1}}return{valid:!1}}catch(e){return U.warn("Token validation failed:",e),{valid:!1}}},exports.verifyJWTLocal=B,exports.version=dw,exports.warn=function(e,...t){A.warn(e,...t)};
13
+ deps: ${o}}`};const n={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const o in e){if("__proto__"===o)continue;(Array.isArray(e[o])?t:r)[o]=e[o]}return[t,r]}(e);s(e,t),a(e,r)}};function s(e,r=e.schema){const{gen:n,data:s,it:a}=e;if(0===Object.keys(r).length)return;const i=n.let("missing");for(const c in r){const u=r[c];if(0===u.length)continue;const l=(0,o.propertyInData)(n,s,c,a.opts.ownProperties);e.setParams({property:c,depsCount:u.length,deps:u.join(", ")}),a.allErrors?n.if(l,()=>{for(const t of u)(0,o.checkReportMissingProp)(e,t)}):(n.if(t._`${l} && (${(0,o.checkMissingProp)(e,u,i)})`),(0,o.reportMissingProp)(e,i),n.else())}}function a(e,t=e.schema){const{gen:n,data:s,keyword:a,it:i}=e,c=n.name("valid");for(const u in t)(0,r.alwaysValidSchema)(i,t[u])||(n.if((0,o.propertyInData)(n,s,u,i.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:u},c);e.mergeValidEvaluated(t,c)},()=>n.var(c,!0)),e.ok(c))}e.validatePropertyDeps=s,e.validateSchemaDeps=a,e.default=n}(Ng);var Cg={};Object.defineProperty(Cg,"__esModule",{value:!0});const jg=Zh,Rg=Wh,Og={message:"property name must be valid",params:({params:e})=>jg._`{propertyName: ${e.propertyName}}`},zg={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Og,code(e){const{gen:t,schema:r,data:o,it:n}=e;if((0,Rg.alwaysValidSchema)(n,r))return;const s=t.name("valid");t.forIn("key",o,r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},s),t.if((0,jg.not)(s),()=>{e.error(!0),n.allErrors||t.break()})}),e.ok(s)}};Cg.default=zg;var Ag={};Object.defineProperty(Ag,"__esModule",{value:!0});const Mg=Df(),Ug=Zh,Dg=hf(),qg=Wh,Vg={message:"must NOT have additional properties",params:({params:e})=>Ug._`{additionalProperty: ${e.additionalProperty}}`},Fg={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Vg,code(e){const{gen:t,schema:r,parentSchema:o,data:n,errsCount:s,it:a}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:i,opts:c}=a;if(a.props=!0,"all"!==c.removeAdditional&&(0,qg.alwaysValidSchema)(a,r))return;const u=(0,Mg.allSchemaProperties)(o.properties),l=(0,Mg.allSchemaProperties)(o.patternProperties);function d(e){t.code(Ug._`delete ${n}[${e}]`)}function p(o){if("all"===c.removeAdditional||c.removeAdditional&&!1===r)d(o);else{if(!1===r)return e.setParams({additionalProperty:o}),e.error(),void(i||t.break());if("object"==typeof r&&!(0,qg.alwaysValidSchema)(a,r)){const r=t.name("valid");"failing"===c.removeAdditional?(h(o,r,!1),t.if((0,Ug.not)(r),()=>{e.reset(),d(o)})):(h(o,r),i||t.if((0,Ug.not)(r),()=>t.break()))}}}function h(t,r,o){const n={keyword:"additionalProperties",dataProp:t,dataPropType:qg.Type.Str};!1===o&&Object.assign(n,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(n,r)}t.forIn("key",n,r=>{u.length||l.length?t.if(function(r){let n;if(u.length>8){const e=(0,qg.schemaRefOrVal)(a,o.properties,"properties");n=(0,Mg.isOwnProperty)(t,e,r)}else n=u.length?(0,Ug.or)(...u.map(e=>Ug._`${r} === ${e}`)):Ug.nil;return l.length&&(n=(0,Ug.or)(n,...l.map(t=>Ug._`${(0,Mg.usePattern)(e,t)}.test(${r})`))),(0,Ug.not)(n)}(r),()=>p(r)):p(r)}),e.ok(Ug._`${s} === ${Dg.default.errors}`)}};Ag.default=Fg;var Lg={};Object.defineProperty(Lg,"__esModule",{value:!0});const Kg=cm(),Hg=Df(),Zg=Wh,Gg=Ag,Jg={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:o,data:n,it:s}=e;"all"===s.opts.removeAdditional&&void 0===o.additionalProperties&&Gg.default.code(new Kg.KeywordCxt(s,Gg.default,"additionalProperties"));const a=(0,Hg.allSchemaProperties)(r);for(const e of a)s.definedProperties.add(e);s.opts.unevaluated&&a.length&&!0!==s.props&&(s.props=Zg.mergeEvaluated.props(t,(0,Zg.toHash)(a),s.props));const i=a.filter(e=>!(0,Zg.alwaysValidSchema)(s,r[e]));if(0===i.length)return;const c=t.name("valid");for(const r of i)u(r)?l(r):(t.if((0,Hg.propertyInData)(t,n,r,s.opts.ownProperties)),l(r),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(r),e.ok(c);function u(e){return s.opts.useDefaults&&!s.compositeRule&&void 0!==r[e].default}function l(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},c)}}};Lg.default=Jg;var Wg={};Object.defineProperty(Wg,"__esModule",{value:!0});const Bg=Df(),Qg=Zh,Yg=Wh,Xg=Wh,ev={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:o,parentSchema:n,it:s}=e,{opts:a}=s,i=(0,Bg.allSchemaProperties)(r),c=i.filter(e=>(0,Yg.alwaysValidSchema)(s,r[e]));if(0===i.length||c.length===i.length&&(!s.opts.unevaluated||!0===s.props))return;const u=a.strictSchema&&!a.allowMatchingProperties&&n.properties,l=t.name("valid");!0===s.props||s.props instanceof Qg.Name||(s.props=(0,Xg.evaluatedPropsToName)(t,s.props));const{props:d}=s;function p(e){for(const t in u)new RegExp(e).test(t)&&(0,Yg.checkStrictMode)(s,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function h(r){t.forIn("key",o,o=>{t.if(Qg._`${(0,Bg.usePattern)(e,r)}.test(${o})`,()=>{const n=c.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:o,dataPropType:Xg.Type.Str},l),s.opts.unevaluated&&!0!==d?t.assign(Qg._`${d}[${o}]`,!0):n||s.allErrors||t.if((0,Qg.not)(l),()=>t.break())})})}!function(){for(const e of i)u&&p(e),s.allErrors?h(e):(t.var(l,!0),h(e),t.if(l))}()}};Wg.default=ev;var tv={};Object.defineProperty(tv,"__esModule",{value:!0});const rv=Wh,ov={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:o}=e;if((0,rv.alwaysValidSchema)(o,r))return void e.fail();const n=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),e.failResult(n,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};tv.default=ov;var nv={};Object.defineProperty(nv,"__esModule",{value:!0});const sv={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Df().validateUnion,error:{message:"must match a schema in anyOf"}};nv.default=sv;var av={};Object.defineProperty(av,"__esModule",{value:!0});const iv=Zh,cv=Wh,uv={message:"must match exactly one schema in oneOf",params:({params:e})=>iv._`{passingSchemas: ${e.passing}}`},lv={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:uv,code(e){const{gen:t,schema:r,parentSchema:o,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&o.discriminator)return;const s=r,a=t.let("valid",!1),i=t.let("passing",null),c=t.name("_valid");e.setParams({passing:i}),t.block(function(){s.forEach((r,o)=>{let s;(0,cv.alwaysValidSchema)(n,r)?t.var(c,!0):s=e.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},c),o>0&&t.if(iv._`${c} && ${a}`).assign(a,!1).assign(i,iv._`[${i}, ${o}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(i,o),s&&e.mergeEvaluated(s,iv.Name)})})}),e.result(a,()=>e.reset(),()=>e.error(!0))}};av.default=lv;var dv={};Object.defineProperty(dv,"__esModule",{value:!0});const pv=Wh,hv={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const n=t.name("valid");r.forEach((t,r)=>{if((0,pv.alwaysValidSchema)(o,t))return;const s=e.subschema({keyword:"allOf",schemaProp:r},n);e.ok(n),e.mergeEvaluated(s)})}};dv.default=hv;var fv={};Object.defineProperty(fv,"__esModule",{value:!0});const mv=Zh,yv=Wh,gv={message:({params:e})=>mv.str`must match "${e.ifClause}" schema`,params:({params:e})=>mv._`{failingKeyword: ${e.ifClause}}`},vv={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:gv,code(e){const{gen:t,parentSchema:r,it:o}=e;void 0===r.then&&void 0===r.else&&(0,yv.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const n=_v(o,"then"),s=_v(o,"else");if(!n&&!s)return;const a=t.let("valid",!0),i=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);e.mergeEvaluated(t)}(),e.reset(),n&&s){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(i,c("then",r),c("else",r))}else n?t.if(i,c("then")):t.if((0,mv.not)(i),c("else"));function c(r,o){return()=>{const n=e.subschema({keyword:r},i);t.assign(a,i),e.mergeValidEvaluated(n,a),o?t.assign(o,mv._`${r}`):e.setParams({ifClause:r})}}e.pass(a,()=>e.error(!0))}};function _v(e,t){const r=e.schema[t];return void 0!==r&&!(0,yv.alwaysValidSchema)(e,r)}fv.default=vv;var wv={};Object.defineProperty(wv,"__esModule",{value:!0});const $v=Wh,bv={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,$v.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};wv.default=bv,Object.defineProperty(sg,"__esModule",{value:!0});const kv=ag,Ev=dg,Sv=pg,Pv=wg,Tv=Pg,xv=Ng,Iv=Cg,Nv=Ag,Cv=Lg,jv=Wg,Rv=tv,Ov=nv,zv=av,Av=dv,Mv=fv,Uv=wv;sg.default=function(e=!1){const t=[Rv.default,Ov.default,zv.default,Av.default,Mv.default,Uv.default,Iv.default,Nv.default,xv.default,Cv.default,jv.default];return e?t.push(Ev.default,Pv.default):t.push(kv.default,Sv.default),t.push(Tv.default),t};var Dv={},qv={};Object.defineProperty(qv,"__esModule",{value:!0});const Vv=Zh,Fv={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>Vv.str`must match format "${e}"`,params:({schemaCode:e})=>Vv._`{format: ${e}}`},code(e,t){const{gen:r,data:o,$data:n,schema:s,schemaCode:a,it:i}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=i;c.validateFormats&&(n?function(){const n=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),s=r.const("fDef",Vv._`${n}[${a}]`),i=r.let("fType"),u=r.let("format");r.if(Vv._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(i,Vv._`${s}.type || "string"`).assign(u,Vv._`${s}.validate`),()=>r.assign(i,Vv._`"string"`).assign(u,s)),e.fail$data((0,Vv.or)(!1===c.strictSchema?Vv.nil:Vv._`${a} && !${u}`,function(){const e=l.$async?Vv._`(${s}.async ? await ${u}(${o}) : ${u}(${o}))`:Vv._`${u}(${o})`,r=Vv._`(typeof ${u} == "function" ? ${e} : ${u}.test(${o}))`;return Vv._`${u} && ${u} !== true && ${i} === ${t} && !${r}`}()))}():function(){const n=d.formats[s];if(!n)return void function(){if(!1===c.strictSchema)return void d.logger.warn(e());throw new Error(e());function e(){return`unknown format "${s}" ignored in schema at path "${u}"`}}();if(!0===n)return;const[a,i,p]=function(e){const t=e instanceof RegExp?(0,Vv.regexpCode)(e):c.code.formats?Vv._`${c.code.formats}${(0,Vv.getProperty)(s)}`:void 0,o=r.scopeValue("formats",{key:s,ref:e,code:t});if("object"==typeof e&&!(e instanceof RegExp))return[e.type||"string",e.validate,Vv._`${o}.validate`];return["string",e,o]}(n);a===t&&e.pass(function(){if("object"==typeof n&&!(n instanceof RegExp)&&n.async){if(!l.$async)throw new Error("async format in sync schema");return Vv._`await ${p}(${o})`}return"function"==typeof i?Vv._`${p}(${o})`:Vv._`${p}.test(${o})`}())}())}};qv.default=Fv,Object.defineProperty(Dv,"__esModule",{value:!0});const Lv=[qv.default];Dv.default=Lv;var Kv={};Object.defineProperty(Kv,"__esModule",{value:!0}),Kv.contentVocabulary=Kv.metadataVocabulary=void 0,Kv.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Kv.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(Om,"__esModule",{value:!0});const Hv=Bm,Zv=sg,Gv=Dv,Jv=Kv,Wv=[zm.default,Hv.default,(0,Zv.default)(),Gv.default,Jv.metadataVocabulary,Jv.contentVocabulary];Om.default=Wv;var Bv,Qv={},Yv={};Object.defineProperty(Yv,"__esModule",{value:!0}),Yv.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(Bv||(Yv.DiscrError=Bv={})),Object.defineProperty(Qv,"__esModule",{value:!0});const Xv=Zh,e_=Yv,t_=mm,r_=fm(),o_=Wh,n_={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===e_.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>Xv._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},code(e){const{gen:t,data:r,schema:o,parentSchema:n,it:s}=e,{oneOf:a}=n;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const i=o.propertyName;if("string"!=typeof i)throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");const c=t.let("valid",!1),u=t.const("tag",Xv._`${r}${(0,Xv.getProperty)(i)}`);function l(r){const o=t.name("valid"),n=e.subschema({keyword:"oneOf",schemaProp:r},o);return e.mergeEvaluated(n,Xv.Name),o}t.if(Xv._`typeof ${u} == "string"`,()=>function(){const r=function(){var e;const t={},r=c(n);let o=!0;for(let t=0;t<a.length;t++){let n=a[t];if((null==n?void 0:n.$ref)&&!(0,o_.schemaHasRulesButRef)(n,s.self.RULES)){const e=n.$ref;if(n=t_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,e),n instanceof t_.SchemaEnv&&(n=n.schema),void 0===n)throw new r_.default(s.opts.uriResolver,s.baseId,e)}const l=null===(e=null==n?void 0:n.properties)||void 0===e?void 0:e[i];if("object"!=typeof l)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);o=o&&(r||c(n)),u(l,t)}if(!o)throw new Error(`discriminator: "${i}" must be required`);return t;function c({required:e}){return Array.isArray(e)&&e.includes(i)}function u(e,t){if(e.const)l(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`);for(const r of e.enum)l(r,t)}}function l(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${i}" values must be unique strings`);t[e]=r}}();t.if(!1);for(const e in r)t.elseIf(Xv._`${u} === ${e}`),t.assign(c,l(r[e]));t.else(),e.error(!1,{discrError:e_.DiscrError.Mapping,tag:u,tagName:i}),t.endIf()}(),()=>e.error(!1,{discrError:e_.DiscrError.Tag,tag:u,tagName:i})),e.ok(c)}};Qv.default=n_;var s_={$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:!0,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:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},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:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},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:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},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:!0};!function(e,t){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 r=Fh,o=Om,n=Qv,s=s_,a=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),o.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(n.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(e,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=cm();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=Zh;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 d=dm();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var p=fm();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}(Vh,Vh.exports);var a_=Vh.exports;!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=a_,r=Zh,o=r.operators,n={formatMaximum:{okStr:"<=",ok:o.LTE,fail:o.GT},formatMinimum:{okStr:">=",ok:o.GTE,fail:o.LT},formatExclusiveMaximum:{okStr:"<",ok:o.LT,fail:o.GTE},formatExclusiveMinimum:{okStr:">",ok:o.GT,fail:o.LTE}},s={message:({keyword:e,schemaCode:t})=>r.str`should be ${n[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>r._`{comparison: ${n[e].okStr}, limit: ${t}}`};e.formatLimitDefinition={keyword:Object.keys(n),type:"string",schemaType:"string",$data:!0,error:s,code(e){const{gen:o,data:s,schemaCode:a,keyword:i,it:c}=e,{opts:u,self:l}=c;if(!u.validateFormats)return;const d=new t.KeywordCxt(c,l.RULES.all.format.definition,"format");function p(e){return r._`${e}.compare(${s}, ${a}) ${n[i].fail} 0`}d.$data?function(){const t=o.scopeValue("formats",{ref:l.formats,code:u.code.formats}),n=o.const("fmt",r._`${t}[${d.schemaCode}]`);e.fail$data((0,r.or)(r._`typeof ${n} != "object"`,r._`${n} instanceof RegExp`,r._`typeof ${n}.compare != "function"`,p(n)))}():function(){const t=d.schema,n=l.formats[t];if(!n||!0===n)return;if("object"!=typeof n||n instanceof RegExp||"function"!=typeof n.compare)throw new Error(`"${i}": format "${t}" does not define "compare" function`);const s=o.scopeValue("formats",{key:t,ref:n,code:u.code.formats?r._`${u.code.formats}${(0,r.getProperty)(t)}`:void 0});e.fail$data(p(s))}()},dependencies:["format"]};e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)}(qh),function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Dh,o=qh,n=Zh,s=new n.Name("fullFormats"),a=new n.Name("fastFormats"),i=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,r.fullFormats,s),e;const[n,i]="fast"===t.mode?[r.fastFormats,a]:[r.fullFormats,s];return c(e,t.formats||r.formatNames,n,i),t.keywords&&(0,o.default)(e),e};function c(e,t,r,o){var s,a;null!==(s=(a=e.opts.code).formats)&&void 0!==s||(a.formats=n._`require("ajv-formats/dist/formats").${o}`);for(const o of t)e.addFormat(o,r[o])}i.get=(e,t="full")=>{const o=("fast"===t?r.fastFormats:r.fullFormats)[e];if(!o)throw new Error(`Unknown format "${e}"`);return o},e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i}(Uh,Uh.exports);var i_=ji(Uh.exports);class c_{constructor(e){this._ajv=e??function(){const e=new Mh({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return i_(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 u_{constructor(e){this._client=e}async*callToolStream(e,t=Oa,r){const o=this._client,n={...r,task:r?.task??(o.isToolTask(e.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:e},t,n),a=o.getToolOutputValidator(e.name);for await(const t of s){if("result"===t.type&&a){const r=t.result;if(!r.structuredContent&&!r.isError)return void(yield{type:"error",error:new Si(as.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)});if(r.structuredContent)try{const e=a(r.structuredContent);if(!e.valid)return void(yield{type:"error",error:new Si(as.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)})}catch(e){return e instanceof Si?void(yield{type:"error",error:e}):void(yield{type:"error",error:new Si(as.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)})}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}function l_(e,t){if(e&&null!==t&&"object"==typeof t){if("object"===e.type&&e.properties&&"object"==typeof e.properties){const r=t,o=e.properties;for(const e of Object.keys(o)){const t=o[e];void 0===r[e]&&Object.prototype.hasOwnProperty.call(t,"default")&&(r[e]=t.default),void 0!==r[e]&&l_(t,r[e])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)"boolean"!=typeof r&&l_(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)"boolean"!=typeof r&&l_(r,t)}}class d_ extends Ni{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new c_,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Ma,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",xa,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",ia,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new u_(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 o=e,n=t[o];if(void 0===n)continue;const s=r[o];Ci(s)&&Ci(n)?r[o]={...s,...n}:r[o]=n}return r}(this._capabilities,e)}setRequestHandler(e,t){const r=so(e),o=r?.method;if(!o)throw new Error("Schema is missing a method literal");let n;if(oo(o)){const e=o,t=e._zod?.def;n=t?.value??e.value}else{const e=o,t=e._def;n=t?.value??e.value}if("string"!=typeof n)throw new Error("Schema method literal must be a string");const s=n;if("elicitation/create"===s){const r=async(e,r)=>{const o=no(pi,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Si(as.InvalidParams,`Invalid elicitation request: ${e}`)}const{params:n}=o.data;n.mode=n.mode??"form";const{supportsFormMode:s,supportsUrlMode:a}=function(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=void 0!==e.form,r=void 0!==e.url;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}(this._capabilities.elicitation);if("form"===n.mode&&!s)throw new Si(as.InvalidParams,"Client does not support form-mode elicitation requests");if("url"===n.mode&&!a)throw new Si(as.InvalidParams,"Client does not support URL-mode elicitation requests");const i=await Promise.resolve(t(e,r));if(n.task){const e=no(zs,i);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Si(as.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const c=no(mi,i);if(!c.success){const e=c.error instanceof Error?c.error.message:String(c.error);throw new Si(as.InvalidParams,`Invalid elicitation result: ${e}`)}const u=c.data,l="form"===n.mode?n.requestedSchema:void 0;if("form"===n.mode&&"accept"===u.action&&u.content&&l&&this._capabilities.elicitation?.form?.applyDefaults)try{l_(l,u.content)}catch{}return u};return super.setRequestHandler(e,r)}if("sampling/createMessage"===s){const r=async(e,r)=>{const o=no(Ya,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Si(as.InvalidParams,`Invalid sampling request: ${e}`)}const{params:n}=o.data,s=await Promise.resolve(t(e,r));if(n.task){const e=no(zs,s);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Si(as.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const a=no(n.tools||n.toolChoice?ei:Xa,s);if(!a.success){const e=a.error instanceof Error?a.error.message:String(a.error);throw new Si(as.InvalidParams,`Invalid sampling result: ${e}`)}return a.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),void 0===e.sessionId)try{const r=await this.request({method:"initialize",params:{protocolVersion:Mn,capabilities:this._capabilities,clientInfo:this._clientInfo}},Es,t);if(void 0===r)throw new Error(`Server sent invalid initialize result: ${r}`);if(!Un.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if("notifications/roots/list_changed"===e)if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client 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})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`)}(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&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._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},us,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},wi,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},us,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},Ta,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},ga,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},ea,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},ra,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},aa,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},us,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},us,t)}async callTool(e,t=Oa,r){if(this.isToolTaskRequired(e.name))throw new Si(as.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:e},t,r),n=this.getToolOutputValidator(e.name);if(n){if(!o.structuredContent&&!o.isError)throw new Si(as.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const e=n(o.structuredContent);if(!e.valid)throw new Si(as.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){if(e instanceof Si)throw e;throw new Si(as.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}isToolTask(e){return!!this._serverCapabilities?.tasks?.requests?.tools?.call&&this._cachedKnownTaskTools.has(e)}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}const e=t.execution?.taskSupport;"required"!==e&&"optional"!==e||this._cachedKnownTaskTools.add(t.name),"required"===e&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Ra,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,o){const n=Ua.safeParse(r);if(!n.success)throw new Error(`Invalid ${e} listChanged options: ${n.error.message}`);if("function"!=typeof r.onChanged)throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:s,debounceMs:a}=n.data,{onChanged:i}=r,c=async()=>{if(s)try{const e=await o();i(null,e)}catch(e){const t=e instanceof Error?e:new Error(String(e));i(t,null)}else i(null,null)};this.setNotificationHandler(t,()=>{if(a){const t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);const r=setTimeout(c,a);this._listChangedDebounceTimers.set(e,r)}else c()})}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function p_(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}const h_=Gr(xo,f_).superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:An,message:"URL must be parseable",fatal:!0}),ae}).refine(e=>{const t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"});var f_;const m_=cn({resource:ko().url(),authorization_servers:nn(h_).optional(),jwks_uri:ko().url().optional(),scopes_supported:nn(ko()).optional(),bearer_methods_supported:nn(ko()).optional(),resource_signing_alg_values_supported:nn(ko()).optional(),resource_name:ko().optional(),resource_documentation:ko().optional(),resource_policy_uri:ko().url().optional(),resource_tos_uri:ko().url().optional(),tls_client_certificate_bound_access_tokens:Wo().optional(),authorization_details_types_supported:nn(ko()).optional(),dpop_signing_alg_values_supported:nn(ko()).optional(),dpop_bound_access_tokens_required:Wo().optional()}),y_=cn({issuer:ko(),authorization_endpoint:h_,token_endpoint:h_,registration_endpoint:h_.optional(),scopes_supported:nn(ko()).optional(),response_types_supported:nn(ko()),response_modes_supported:nn(ko()).optional(),grant_types_supported:nn(ko()).optional(),token_endpoint_auth_methods_supported:nn(ko()).optional(),token_endpoint_auth_signing_alg_values_supported:nn(ko()).optional(),service_documentation:h_.optional(),revocation_endpoint:h_.optional(),revocation_endpoint_auth_methods_supported:nn(ko()).optional(),revocation_endpoint_auth_signing_alg_values_supported:nn(ko()).optional(),introspection_endpoint:ko().optional(),introspection_endpoint_auth_methods_supported:nn(ko()).optional(),introspection_endpoint_auth_signing_alg_values_supported:nn(ko()).optional(),code_challenge_methods_supported:nn(ko()).optional(),client_id_metadata_document_supported:Wo().optional()}),g_=an({...cn({issuer:ko(),authorization_endpoint:h_,token_endpoint:h_,userinfo_endpoint:h_.optional(),jwks_uri:h_,registration_endpoint:h_.optional(),scopes_supported:nn(ko()).optional(),response_types_supported:nn(ko()),response_modes_supported:nn(ko()).optional(),grant_types_supported:nn(ko()).optional(),acr_values_supported:nn(ko()).optional(),subject_types_supported:nn(ko()),id_token_signing_alg_values_supported:nn(ko()),id_token_encryption_alg_values_supported:nn(ko()).optional(),id_token_encryption_enc_values_supported:nn(ko()).optional(),userinfo_signing_alg_values_supported:nn(ko()).optional(),userinfo_encryption_alg_values_supported:nn(ko()).optional(),userinfo_encryption_enc_values_supported:nn(ko()).optional(),request_object_signing_alg_values_supported:nn(ko()).optional(),request_object_encryption_alg_values_supported:nn(ko()).optional(),request_object_encryption_enc_values_supported:nn(ko()).optional(),token_endpoint_auth_methods_supported:nn(ko()).optional(),token_endpoint_auth_signing_alg_values_supported:nn(ko()).optional(),display_values_supported:nn(ko()).optional(),claim_types_supported:nn(ko()).optional(),claims_supported:nn(ko()).optional(),service_documentation:ko().optional(),claims_locales_supported:nn(ko()).optional(),ui_locales_supported:nn(ko()).optional(),claims_parameter_supported:Wo().optional(),request_parameter_supported:Wo().optional(),request_uri_parameter_supported:Wo().optional(),require_request_uri_registration:Wo().optional(),op_policy_uri:h_.optional(),op_tos_uri:h_.optional(),client_id_metadata_document_supported:Wo().optional()}).shape,...y_.pick({code_challenge_methods_supported:!0}).shape}),v_=an({access_token:ko(),id_token:ko().optional(),token_type:ko(),expires_in:function(e){return function(e,t){return new e({type:"number",coerce:!0,checks:[],...Se(t)})}(Ko,e)}().optional(),scope:ko().optional(),refresh_token:ko().optional()}).strip(),__=an({error:ko(),error_description:ko().optional(),error_uri:ko().optional()}),w_=h_.optional().or(wn("").transform(()=>{})),$_=an({redirect_uris:nn(h_),token_endpoint_auth_method:ko().optional(),grant_types:nn(ko()).optional(),response_types:nn(ko()).optional(),client_name:ko().optional(),client_uri:h_.optional(),logo_uri:w_,scope:ko().optional(),contacts:nn(ko()).optional(),tos_uri:w_,policy_uri:ko().optional(),jwks_uri:h_.optional(),jwks:new Yo({type:"any"}).optional(),software_id:ko().optional(),software_version:ko().optional(),software_statement:ko().optional()}).strip(),b_=an({client_id:ko(),client_secret:ko().optional(),client_id_issued_at:Ho().optional(),client_secret_expires_at:Ho().optional()}).strip(),k_=$_.merge(b_);an({error:ko(),error_description:ko().optional()}).strip(),an({token:ko(),token_type_hint:ko().optional()}).strip();class E_ extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class S_ extends E_{}S_.errorCode="invalid_request";class P_ extends E_{}P_.errorCode="invalid_client";class T_ extends E_{}T_.errorCode="invalid_grant";class x_ extends E_{}x_.errorCode="unauthorized_client";class I_ extends E_{}I_.errorCode="unsupported_grant_type";class N_ extends E_{}N_.errorCode="invalid_scope";class C_ extends E_{}C_.errorCode="access_denied";class j_ extends E_{}j_.errorCode="server_error";class R_ extends E_{}R_.errorCode="temporarily_unavailable";class O_ extends E_{}O_.errorCode="unsupported_response_type";class z_ extends E_{}z_.errorCode="unsupported_token_type";class A_ extends E_{}A_.errorCode="invalid_token";class M_ extends E_{}M_.errorCode="method_not_allowed";class U_ extends E_{}U_.errorCode="too_many_requests";class D_ extends E_{}D_.errorCode="invalid_client_metadata";class q_ extends E_{}q_.errorCode="insufficient_scope";class V_ extends E_{}V_.errorCode="invalid_target";const F_={[S_.errorCode]:S_,[P_.errorCode]:P_,[T_.errorCode]:T_,[x_.errorCode]:x_,[I_.errorCode]:I_,[N_.errorCode]:N_,[C_.errorCode]:C_,[j_.errorCode]:j_,[R_.errorCode]:R_,[O_.errorCode]:O_,[z_.errorCode]:z_,[A_.errorCode]:A_,[M_.errorCode]:M_,[U_.errorCode]:U_,[D_.errorCode]:D_,[q_.errorCode]:q_,[V_.errorCode]:V_};class L_ extends Error{constructor(e){super(e??"Unauthorized")}}const K_="code",H_="S256";function Z_(e,t,r,o){const{client_id:n,client_secret:s}=t;switch(e){case"client_secret_basic":return void function(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}(n,s,r);case"client_secret_post":return void function(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}(n,s,o);case"none":return void function(e,t){t.set("client_id",e)}(n,o);default:throw new Error(`Unsupported client authentication method: ${e}`)}}async function G_(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=__.parse(JSON.parse(r)),{error:t,error_description:o,error_uri:n}=e;return new(F_[t]||j_)(o||"",n)}catch(e){return new j_(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function J_(e,t){try{return await W_(e,t)}catch(r){if(r instanceof P_||r instanceof x_)return await(e.invalidateCredentials?.("all")),await W_(e,t);if(r instanceof T_)return await(e.invalidateCredentials?.("tokens")),await W_(e,t);throw r}}async function W_(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:n,fetchFn:s}){let a,i;try{a=await async function(e,t,r=fetch){const o=await async function(e,t,r,o){const n=new URL(e),s=o?.protocolVersion??Mn;let a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{const e=function(e,t="",r={}){t.endsWith("/")&&(t=t.slice(0,-1));return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,n.pathname);a=new URL(e,o?.metadataServerUrl??n),a.search=n.search}let i=await X_(a,s,r);if(!o?.metadataUrl&&function(e,t){return!e||e.status>=400&&e.status<500&&"/"!==t}(i,n.pathname)){const e=new URL(`/.well-known/${t}`,n);i=await X_(e,s,r)}return i}(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||404===o.status)throw await(o?.body?.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await(o.body?.cancel()),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return m_.parse(await o.json())}(t,{resourceMetadataUrl:n},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",t));const c=await async function(e,t,r){const o=function(e){const t="string"==typeof e?new URL(e):new URL(e.href);return t.hash="",t}(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!function({requestedResource:e,configuredResource:t}){const r="string"==typeof e?new URL(e):new URL(e.href),o="string"==typeof t?new URL(t):new URL(t.href);if(r.origin!==o.origin)return!1;if(r.pathname.length<o.pathname.length)return!1;const n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(s)}({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}(t,e,a),l=await async function(e,{fetchFn:t=fetch,protocolVersion:r=Mn}={}){const o={"MCP-Protocol-Version":r,Accept:"application/json"},n=function(e){const t="string"==typeof e?new URL(e):e,r="/"!==t.pathname,o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;n.endsWith("/")&&(n=n.slice(0,-1));return o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"}),o.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}(e);for(const{url:e,type:r}of n){const n=await Y_(e,o,t);if(n){if(!n.ok){if(await(n.body?.cancel()),n.status>=400&&n.status<500)continue;throw new Error(`HTTP ${n.status} trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`)}return"oauth"===r?y_.parse(await n.json()):g_.parse(await n.json())}}return}(i,{fetchFn:s});let d=await Promise.resolve(e.clientInformation());if(!d){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const t=!0===l?.client_id_metadata_document_supported,o=e.clientMetadataUrl;if(o&&!function(e){if(!e)return!1;try{const t=new URL(e);return"https:"===t.protocol&&"/"!==t.pathname}catch{return!1}}(o))throw new D_(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${o}`);if(t&&o)d={client_id:o},await(e.saveClientInformation?.(d));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const t=await async function(e,{metadata:t,clientMetadata:r,fetchFn:o}){let n;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(t.registration_endpoint)}else n=new URL("/register",e);const s=await(o??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await G_(s);return k_.parse(await s.json())}(i,{metadata:l,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(t),d=t}}const p=!e.redirectUrl;if(void 0!==r||p){const t=await async function(e,t,{metadata:r,resource:o,authorizationCode:n,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a));if(!i){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");i=function(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}(n,await e.codeVerifier(),e.redirectUrl)}const c=await e.clientInformation();return ew(t,{metadata:r,tokenRequestParams:i,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:s})}(e,i,{metadata:l,resource:c,authorizationCode:r,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}const h=await e.tokens();if(h?.refresh_token)try{const t=await async function(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),c=await ew(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:n,fetchFn:a});return{refresh_token:o,...c}}(i,{metadata:l,clientInformation:d,refreshToken:h.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof E_&&!(e instanceof j_))throw e}const f=e.state?await e.state():void 0,{authorizationUrl:m,codeVerifier:y}=await async function(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(K_))throw new Error(`Incompatible auth server: does not support response type ${K_}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(H_))throw new Error(`Incompatible auth server: does not support code challenge method ${H_}`)}else i=new URL("/authorize",e);const c=await u(),l=c.code_verifier,d=c.code_challenge;i.searchParams.set("response_type",K_),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",d),i.searchParams.set("code_challenge_method",H_),i.searchParams.set("redirect_uri",String(o)),s&&i.searchParams.set("state",s);n&&i.searchParams.set("scope",n);n?.includes("offline_access")&&i.searchParams.append("prompt","consent");a&&i.searchParams.set("resource",a.href);return{authorizationUrl:i,codeVerifier:l}}(i,{metadata:l,clientInformation:d,state:f,redirectUrl:e.redirectUrl,scope:o||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(y),await e.redirectToAuthorization(m),"REDIRECT"}function B_(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,o]=t.split(" ");if("bearer"!==r.toLowerCase()||!o)return{};const n=Q_(e,"resource_metadata")||void 0;let s;if(n)try{s=new URL(n)}catch{}return{resourceMetadataUrl:s,scope:Q_(e,"scope")||void 0,error:Q_(e,"error")||void 0}}function Q_(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),n=r.match(o);return n?n[1]||n[2]:null}async function Y_(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Y_(e,void 0,r):void 0;throw o}}async function X_(e,t,r=fetch){const o={"MCP-Protocol-Version":t};return await Y_(e,o,r)}async function ew(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:s,fetchFn:a}){const i=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),n)await n(c,r,i,t);else if(o){const e=function(e,t){const r=void 0!==e.client_secret;return 0===t.length?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&(o=e.token_endpoint_auth_method,["client_secret_basic","client_secret_post","none"].includes(o))&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none";var o}(o,t?.token_endpoint_auth_methods_supported??[]);Z_(e,o,c,r)}const u=await(a??fetch)(i,{method:"POST",headers:c,body:r});if(!u.ok)throw await G_(u);return v_.parse(await u.json())}class tw extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function rw(e){}function ow(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=rw,onError:r=rw,onRetry:o=rw,onComment:n}=e;let s,a="",i=!0,c="",u="";function l(e){if(""===e)return c.length>0&&t({id:s,event:u||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),s=void 0,c="",void(u="");if(e.startsWith(":"))return void(n&&n(e.slice(e.startsWith(": ")?2:1)));const r=e.indexOf(":");if(-1!==r){const t=e.slice(0,r),o=" "===e[r+1]?2:1;return void d(t,e.slice(r+o),e)}d(e,"",e)}function d(e,t,n){switch(e){case"event":u=t;break;case"data":c=`${c}${t}\n`;break;case"id":s=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?o(parseInt(t,10)):r(new tw(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:n}));break;default:r(new tw(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:n}))}}return{feed:function(e){const t=i?e.replace(/^\xEF\xBB\xBF/,""):e,[r,o]=function(e){const t=[];let r="",o=0;for(;o<e.length;){const n=e.indexOf("\r",o),s=e.indexOf("\n",o);let a=-1;if(-1!==n&&-1!==s?a=Math.min(n,s):-1!==n?a=n:-1!==s&&(a=s),-1===a){r=e.slice(o);break}{const r=e.slice(o,a);t.push(r),o=a+1,"\r"===e[o-1]&&"\n"===e[o]&&o++}}return[t,r]}(`${a}${t}`);for(const e of r)l(e);a=o,i=!1},reset:function(e={}){a&&e.consume&&l(a),i=!0,s=void 0,c="",u="",a=""}}}class nw extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let o;super({start(n){o=ow({onEvent:e=>{n.enqueue(e)},onError(t){"terminate"===e?n.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:r})},transform(e){o.feed(e)}})}}const sw={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class aw extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class iw{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=function(e=fetch,t){return t?async(r,o)=>{const n={...t,...o,headers:o?.headers?{...p_(t.headers),...p_(o.headers)}:t.headers};return e(r,n)}:e}(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??sw}async _authThenStart(){if(!this._authProvider)throw new L_("No auth provider");let e;try{e=await J_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new L_;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=p_(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){const{resumptionToken:t}=e;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);const o=await(this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!o.ok){if(await(o.body?.cancel()),401===o.status&&this._authProvider)return await this._authThenStart();if(405===o.status)return;throw new aw(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(void 0!==this._serverRetryMs)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){const r=this._reconnectionOptions.maxRetries;if(t>=r)return void this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));const o=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},o)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:o,replayMessageId:n}=t;let s,a=!1,i=!1;(async()=>{try{const t=e.pipeThrough(new TextDecoderStream).pipeThrough(new nw({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){const{value:e,done:r}=await t.read();if(r)break;if(e.id&&(s=e.id,a=!0,o?.(e.id)),e.data&&(!e.event||"message"===e.event))try{const t=cs.parse(JSON.parse(e.data));ss(t)&&(i=!0,void 0!==n&&(t.id=n)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(r||a)&&!i&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:n},0)}catch(e){this.onerror?.(new Error(`SSE stream disconnected: ${e}`));if((r||a)&&!i&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:n},0)}catch(e){this.onerror?.(new Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new L_("No auth provider");if("AUTHORIZED"!==await J_(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new L_("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{const{resumptionToken:o,onresumptiontoken:n}=t||{};if(o)return void this._startOrAuthSse({resumptionToken:o,replayMessageId:rs(e)?e.id:void 0}).catch(e=>this.onerror?.(e));const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),c=i.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!i.ok){const t=await i.text().catch(()=>null);if(401===i.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new aw(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:t,scope:r}=B_(i);this._resourceMetadataUrl=t,this._scope=r;if("AUTHORIZED"!==await J_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new L_;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===i.status&&this._authProvider){const{resourceMetadataUrl:t,scope:r,error:o}=B_(i);if("insufficient_scope"===o){const o=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===o)throw new aw(403,"Server returned 403 after trying upscoping");r&&(this._scope=r),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=o??void 0;if("AUTHORIZED"!==await J_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch}))throw new L_;return this.send(e)}}throw new aw(i.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===i.status)return await(i.body?.cancel()),r=e,void(Ss.safeParse(r).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e)));const u=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,l=i.headers.get("content-type");if(u)if(l?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:n},!1);else{if(!l?.includes("application/json"))throw await(i.body?.cancel()),new aw(-1,`Unexpected content type: ${l}`);{const e=await i.json(),t=Array.isArray(e)?e.map(e=>cs.parse(e)):[cs.parse(e)];for(const e of t)this.onmessage?.(e)}}else await(i.body?.cancel())}catch(e){throw this.onerror?.(e),e}var r}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._url,t);if(await(r.body?.cancel()),!r.ok&&405!==r.status)throw new aw(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}const cw=M("quickstart");async function uw(e,t,r={}){const{serverId:o,serverSlug:n,proxyBaseUrl:s="http://proxy-ingress:8080",transport:a="streamable-http"}=r,i=o||n||t;let c;try{c=await e.getServer(i)}catch(e){if(e instanceof g&&404===e.statusCode)throw new v(i);throw e}const u=c.slug||i;let l;if(z(e.token)){l=`${O(e.token).baseUrl}/mcp/${u}`}else{cw.warn("Token has no organization information, using static config for MCP connection");l=`${R().baseUrl}/mcp/${u}`}return[{url:l,transport:a,headers:{Accept:"application/json, text/event-stream",Authorization:`Bearer ${e.token}`,"x-barndoor-session-id":lw()}},l]}function lw(){if(I&&"function"==typeof n.randomUUID)return n.randomUUID();if("undefined"!=typeof globalThis&&globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e;if(I&&"function"==typeof n.randomBytes)e=n.randomBytes(16);else{if("undefined"==typeof globalThis||!globalThis.crypto?.getRandomValues)throw new Error("Secure random generator not available for UUID.");e=new Uint8Array(16),globalThis.crypto.getRandomValues(e)}const t=e??new Uint8Array(0);if(t.length<16)throw new Error("Secure random generator not available for UUID.");const r=t[6],o=t[8];t[6]=15&r|64,t[8]=63&o|128;const s=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${s.substring(0,8)}-${s.substring(8,12)}-${s.substring(12,16)}-${s.substring(16,20)}-${s.substring(20)}`}const dw=function(){try{if("undefined"!=typeof process&&process.versions?.node){const e=a.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(e).href:d&&"SCRIPT"===d.tagName.toUpperCase()&&d.src||new URL("index.js",document.baseURI).href),r=t.dirname(e),o=t.join(r,"..","package.json");return JSON.parse(l.readFileSync(o,"utf8")).version}return'"1.0.1"'}catch(e){return console.warn("Could not read version from package.json:",e),"0.1.0"}}();exports.AUTH_CONFIG=T,exports.AgentToken=P,exports.AuthenticationError=h,exports.BarndoorConfig=C,exports.BarndoorError=p,exports.BarndoorSDK=se,exports.ConfigurationError=w,exports.ConnectionError=y,exports.HTTPError=g,exports.OAuthError=_,exports.PKCEManager=te,exports.ServerDetail=S,exports.ServerNotFoundError=v,exports.ServerSummary=E,exports.TimeoutError=$,exports.TokenError=f,exports.TokenExpiredError=m,exports.TokenManager=Y,exports.TokenValidationError=class extends f{},exports.checkTokenOrganization=function(e){return j(e)},exports.clearCachedToken=async function(){const e=W();await e.clearToken()},exports.clearOidcConfigCache=function(){D.clear()},exports.createScopedLogger=M,exports.debug=function(e,...t){A.debug(e,...t)},exports.ensureServerConnected=async function(e,t,r={}){const{timeout:o=90}=r;cw.info(`Ensuring ${t} server is connected`);try{await e.ensureServerConnected(t,{pollSeconds:o}),cw.info(`Server ${t} connected successfully`)}catch(e){throw e instanceof v?cw.error(`Server '${t}' not found`):cw.error(`Failed to connect to ${t}:`,e),e}},exports.error=function(e,...t){A.error(e,...t)},exports.getDynamicConfig=O,exports.getLogger=function(){return A},exports.getOidcConfig=q,exports.getStaticConfig=R,exports.hasOrganizationInfo=z,exports.info=function(e,...t){A.info(e,...t)},exports.isBrowser=x,exports.isNode=I,exports.isTokenActive=async function(e){try{const e=W(),t=await e.loadToken();if(!t?.access_token)return!1;const r=R(),o=(await q(r.authIssuer)).userinfo_endpoint,n=fetch(o,{headers:{Authorization:`Bearer ${t.access_token}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(1e4)}:{}});return(await F(n,1e4)).ok}catch(e){return!1}},exports.isTokenActiveWithRefresh=async function(e){try{const t=new Y(e||"");return await t.getValidToken(),!0}catch(e){return U.warn("Token validation/refresh failed:",e),!1}},exports.loadUserToken=X,exports.loginInteractive=async function(t={}){if(!I)throw new Error("Interactive login is only available in Node.js environment");cw.info("Starting interactive login flow");const r=R();let o;o=t.authIssuer?t.authIssuer:t.authDomain?t.authDomain.startsWith("http")?t.authDomain:`https://${t.authDomain}`:r.authIssuer;const{clientId:n=r.clientId,clientSecret:s=r.clientSecret,audience:a=r.apiAudience,baseUrl:u,port:l=52765}=t;if(!n||!s)throw new Error("AGENT_CLIENT_ID / AGENT_CLIENT_SECRET not set – create a .env file or export in the shell");const d=await X();if(d)try{let e;z(d)?e=O(d):(cw.warn("Cached token has no organization information, using static config"),e=R());const t=new se(e.baseUrl,{token:d});return await t.validateCachedToken(),cw.info("Using cached valid token"),t}catch(e){cw.info("Cached token invalid, starting OAuth flow")}else cw.info("No cached token, starting OAuth flow");const p="undefined"!=typeof process&&!(!process.env||"1"!==process.env.BARNDOOR_MANUAL_CODE&&"true"!==process.env.BARNDOOR_MANUAL_CODE);let h,f=null;if(p){const e=process.env&&process.env.BARNDOOR_REDIRECT_HOST||"127.0.0.1";h=e.startsWith("http")?`${e}:${l}/cb`:`http://${e}:${l}/cb`}else{const e=ne(l);h=e[0],f=e[1]}const m=new te,y=await m.buildAuthorizationUrl({clientId:n,redirectUri:h,audience:a,issuer:o});cw.info(`Auth URL: ${y}`);const g=e.platform();let v,_;try{v=new URL(y)}catch{throw new Error("Invalid auth URL")}if("https:"!==v.protocol&&("http:"!==v.protocol||"localhost"!==v.hostname&&"127.0.0.1"!==v.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===g?i.spawn("open",[y],{detached:!0,stdio:"ignore"}).unref():"win32"===g?i.spawn("powershell",["-NoProfile","Start-Process",y],{detached:!0,stdio:"ignore"}).unref():i.spawn("xdg-open",[y],{detached:!0,stdio:"ignore"}).unref(),cw.info("Please complete login in your browser…")}catch(e){cw.warn("Failed to open browser automatically. Please visit:",y)}if(p){const e=await new Promise(e=>{const t=c.createInterface({input:process.stdin,output:process.stdout});t.question("Paste the full redirected URL (or just the code= value): ",r=>{t.close(),e(r.trim())})});try{const t=new URL(e);_=t.searchParams.get("code")||e}catch{_=e}}else{const e=new Promise((e,t)=>{setTimeout(()=>{t(new Error(`OAuth callback timeout after 2 minutes. This usually means the callback URL is not registered in Auth0. Please add "${h}" to Allowed Callback URLs in your Auth0 application settings.`))},12e4)});_=(await Promise.race([f,e]))[0]}const w=await m.exchangeCodeForToken({clientId:n,clientSecret:s,code:_,redirectUri:h,issuer:o});let $;if(await ee(w),u)$=u;else if(z(w.access_token)){$=O(w.access_token).baseUrl}else cw.warn("New token has no organization information, using static config"),$=R().baseUrl;return new se($,{token:w.access_token})},exports.makeMcpClient=async function(e,t,r={}){const[o]=await uw(e,t,r),n=o,s=new d_({name:"barndoor-js-sdk",version:"0.1.0"}),a=new iw(new URL(n.url),{requestInit:{headers:n.headers}});return await s.connect(a),s},exports.makeMcpConnectionParams=uw,exports.saveUserToken=ee,exports.setLogger=function(e){A=e},exports.setTokenLogger=function(e){console.warn("setTokenLogger is deprecated. Use setLogger from the main logging module instead.")},exports.startLocalCallbackServer=ne,exports.validateToken=async function(e,t){try{const t=R(),r=await B(e,t.authIssuer,t.apiAudience);if(r===exports.JWTVerificationResult.VALID)return{valid:!0};if(r===exports.JWTVerificationResult.INVALID)try{const r=(await q(t.authIssuer)).userinfo_endpoint,o=fetch(r,{headers:{Authorization:`Bearer ${e}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(5e3)}:{}});return{valid:(await F(o,5e3)).ok}}catch(e){return U.warn("Remote token validation failed:",e),{valid:!1}}return{valid:!1}}catch(e){return U.warn("Token validation failed:",e),{valid:!1}}},exports.verifyJWTLocal=B,exports.version=dw,exports.warn=function(e,...t){A.warn(e,...t)};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@barndoor-ai/sdk",
3
- "version": "0.4.3",
3
+ "version": "1.0.1",
4
4
  "description": "TypeScript/JavaScript client for the Barndoor Platform API",
5
5
  "author": "Barndoor AI, Inc. (https://barndoor.ai)",
6
6
  "homepage": "https://barndoor.ai",