148 lines
666 KiB
JavaScript
148 lines
666 KiB
JavaScript
|
|
"use strict";var oI=Object.create;var Ji=Object.defineProperty;var iI=Object.getOwnPropertyDescriptor;var aI=Object.getOwnPropertyNames;var sI=Object.getPrototypeOf,cI=Object.prototype.hasOwnProperty;var I$=t=>{throw TypeError(t)};var uI=(t,e,r)=>e in t?Ji(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),_t=(t,e)=>{for(var r in e)Ji(t,r,{get:e[r],enumerable:!0})},Xc=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of aI(e))!cI.call(t,n)&&n!==r&&Ji(t,n,{get:()=>e[n],enumerable:!(o=iI(e,n))||o.enumerable});return t},P$=(t,e,r)=>(Xc(t,e,"default"),r&&Xc(r,e,"default")),er=(t,e,r)=>(r=t!=null?oI(sI(t)):{},Xc(e||!t||!t.__esModule?Ji(r,"default",{value:t,enumerable:!0}):r,t)),lI=t=>Xc(Ji({},"__esModule",{value:!0}),t);var zt=(t,e,r)=>uI(t,typeof e!="symbol"?e+"":e,r),T$=(t,e,r)=>e.has(t)||I$("Cannot "+r);var Hi=(t,e,r)=>(T$(t,e,"read from private field"),r?r.call(t):e.get(t)),Vp=(t,e,r)=>e.has(t)?I$("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Wi=(t,e,r,o)=>(T$(t,e,"write to private field"),o?o.call(t,r):e.set(t,r),r);var ec=z(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.regexpCode=de.getEsmExportName=de.getProperty=de.safeStringify=de.stringify=de.strConcat=de.addCodeArg=de.str=de._=de.nil=de._Code=de.Name=de.IDENTIFIER=de._CodeOrName=void 0;var Ys=class{};de._CodeOrName=Ys;de.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Hn=class extends Ys{constructor(e){if(super(),!de.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};de.Name=Hn;var Nt=class extends Ys{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,o)=>`${r}${o}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,o)=>(o instanceof Hn&&(r[o.str]=(r[o.str]||0)+1),r),{})}};de._Code=Nt;de.nil=new Nt("");function Pw(t,...e){let r=[t[0]],o=0;for(;o<e.length;)Vv(r,e[o]),r.push(t[++o]);return new Nt(r)}de._=Pw;var Lv=new Nt("+");function Tw(t,...e){let r=[Qs(t[0])],o=0;for(;o<e.length;)r.push(Lv),Vv(r,e[o]),r.push(Lv,Qs(t[++o]));return FO(r),new Nt(r)}de.str=Tw;function Vv(t,e){e instanceof Nt?t.push(...e._items):e instanceof Hn?t.push(e):t.push(WO(e))}de.addCodeArg=Vv;function FO(t){let e=1;for(;e<t.length-1;){if(t[e]===Lv){let r=JO(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function JO(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Hn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Hn))return`"${t}${e.slice(1)}`}function HO(t,e){return e.emptyStr()?t:t.emptyStr()?e:Tw`${t}${e}`}de.strConcat=HO;function WO(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Qs(Array.isArray(t)?t.join(","):t)}function BO(t){return new Nt(Qs(t))}de.stringify=BO;function Qs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}de.safeStringify=Qs;function KO(t){return typeof t=="string"&&de.IDENTIFIER.test(t)?new Nt(`.${t}`):Pw`[${t}]`}de.getProperty=KO;function GO(t){if(typeof t=="string"&&de.IDENTIFIER.test(t))return new Nt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}de.getEsmExportName=GO;function XO(t){return new Nt(t.toString())}de.regexpCode=XO});var Hv=z(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.ValueScope=mt.ValueScopeName=mt.Scope=mt.varKinds=mt.UsedValueState=void 0;var pt=ec(),Fv=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Sf;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Comple
|
||
|
|
`:""},this._extScope=e,this._scope=new Wt.Scope({parent:e}),this._nodes=[new Qv]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let o=this._extScope.value(e,r);return(this._values[o.prefix]||(this._values[o.prefix]=new Set)).add(o),o}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,o,n){let i=this._scope.toName(r);return o!==void 0&&n&&(this._constants[i.str]=o),this._leafNode(new Wv(e,i,o)),i}const(e,r,o){return this._def(Wt.varKinds.const,e,r,o)}let(e,r,o){return this._def(Wt.varKinds.let,e,r,o)}var(e,r,o){return this._def(Wt.varKinds.var,e,r,o)}assign(e,r,o){return this._leafNode(new Pf(e,r,o))}add(e,r){return this._leafNode(new Bv(e,re.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ue.nil&&this._leafNode(new Yv(e)),this}object(...e){let r=["{"];for(let[o,n]of e)r.length>1&&r.push(","),r.push(o),(o!==n||this.opts.es5)&&(r.push(":"),(0,ue.addCodeArg)(r,n));return r.push("}"),new ue._Code(r)}if(e,r,o){if(this._blockNode(new Wn(e)),r&&o)this.code(r).else().code(o).endIf();else if(r)this.code(r).endIf();else if(o)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Wn(e))}else(){return this._elseNode(new mi)}endIf(){return this._endBlockNode(Wn,mi)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new e_(e),r)}forRange(e,r,o,n,i=this.opts.es5?Wt.varKinds.var:Wt.varKinds.let){let a=this._scope.toName(e);return this._for(new t_(i,a,r,o),()=>n(a))}forOf(e,r,o,n=Wt.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let a=r instanceof ue.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ue._)`${a}.length`,c=>{this.var(i,(0,ue._)`${a}[${c}]`),o(i)})}return this._for(new Tf("of",n,i,r),()=>o(i))}forIn(e,r,o,n=this.opts.es5?Wt.varKinds.var:Wt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ue._)`Object.keys(${r})`,o);let i=this._scope.toName(e);return this._for(new Tf("in",n,i,r),()=>o(i))}endFor(){return this._endBlockNode(Bn)}label(e){return this._leafNode(new Kv(e))}break(e){return this._leafNode(new Gv(e))}return(e){let r=new nc;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(nc)}try(e,r,o){if(!r&&!o)throw new Error('CodeGen: "try" without "catch" and "finally"');let n=new r_;if(this._blockNode(n),this.code(e),r){let i=this.name("e");this._currNode=n.catch=new oc(i),r(i)}return o&&(this._currNode=n.finally=new ic,this.code(o)),this._endBlockNode(oc,ic)}throw(e){return this._leafNode(new Xv(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let o=this._nodes.length-r;if(o<0||e!==void 0&&o!==e)throw new Error(`CodeGen: wrong number of nodes: ${o} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=ue.nil,o,n){return this._blockNode(new rc(e,r,o)),n&&this.code(n).endFunc(),this}endFunc(){return this._endBlockNode(rc)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let o=this._currNode;if(o instanceof e||r&&o instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Wn))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};re.CodeGen=n_;function Kn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ef(t,e){return e in
|
||
|
|
|| (${a} == "string" && ${n} && ${n} == +${n})`).assign(c,(0,Q._)`+${n}`);return;case"integer":o.elseIf((0,Q._)`${a} === "boolean" || ${n} === null
|
||
|
|
|| (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(c,(0,Q._)`+${n}`);return;case"boolean":o.elseIf((0,Q._)`${n} === "false" || ${n} === 0 || ${n} === null`).assign(c,!1).elseIf((0,Q._)`${n} === "true" || ${n} === 1`).assign(c,!0);return;case"null":o.elseIf((0,Q._)`${n} === "" || ${n} === 0 || ${n} === false`),o.assign(c,null);return;case"array":o.elseIf((0,Q._)`${a} === "string" || ${a} === "number"
|
||
|
|
|| ${a} === "boolean" || ${n} === null`).assign(c,(0,Q._)`[${n}]`)}}}function qj({gen:t,parentData:e,parentDataProperty:r},o){t.if((0,Q._)`${e} !== undefined`,()=>t.assign((0,Q._)`${e}[${r}]`,o))}function d_(t,e,r,o=_i.Correct){let n=o===_i.Correct?Q.operators.EQ:Q.operators.NEQ,i;switch(t){case"null":return(0,Q._)`${e} ${n} null`;case"array":i=(0,Q._)`Array.isArray(${e})`;break;case"object":i=(0,Q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=a((0,Q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=a();break;default:return(0,Q._)`typeof ${e} ${n} ${t}`}return o===_i.Correct?i:(0,Q.not)(i);function a(c=Q.nil){return(0,Q.and)((0,Q._)`typeof ${e} == "number"`,c,r?(0,Q._)`isFinite(${e})`:Q.nil)}}tt.checkDataType=d_;function f_(t,e,r,o){if(t.length===1)return d_(t[0],e,r,o);let n,i=(0,Hw.toHash)(t);if(i.array&&i.object){let a=(0,Q._)`typeof ${e} != "object"`;n=i.null?a:(0,Q._)`!${e} || ${a}`,delete i.null,delete i.array,delete i.object}else n=Q.nil;i.number&&delete i.integer;for(let a in i)n=(0,Q.and)(n,d_(a,e,r,o));return n}tt.checkDataTypes=f_;var Lj={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Q._)`{type: ${t}}`:(0,Q._)`{type: ${e}}`};function p_(t){let e=Vj(t);(0,Dj.reportError)(e,Lj)}tt.reportTypeError=p_;function Vj(t){let{gen:e,data:r,schema:o}=t,n=(0,Hw.schemaRefOrVal)(t,o,"type");return{gen:e,keyword:"type",data:r,schema:o.type,schemaCode:n,schemaValue:n,parentSchema:o,params:{},it:t}}});var Gw=z(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});Rf.assignDefaults=void 0;var yi=ee(),Fj=fe();function Jj(t,e){let{properties:r,items:o}=t.schema;if(e==="object"&&r)for(let n in r)Kw(t,n,r[n].default);else e==="array"&&Array.isArray(o)&&o.forEach((n,i)=>Kw(t,i,n.default))}Rf.assignDefaults=Jj;function Kw(t,e,r){let{gen:o,compositeRule:n,data:i,opts:a}=t;if(r===void 0)return;let c=(0,yi._)`${i}${(0,yi.getProperty)(e)}`;if(n){(0,Fj.checkStrictMode)(t,`default is ignored for: ${c}`);return}let u=(0,yi._)`${c} === undefined`;a.useDefaults==="empty"&&(u=(0,yi._)`${u} || ${c} === null || ${c} === ""`),o.if(u,(0,yi._)`${c} = ${(0,yi.stringify)(r)}`)}});var Ct=z(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.validateUnion=be.validateArray=be.usePattern=be.callValidateCode=be.schemaProperties=be.allSchemaProperties=be.noPropertyInData=be.propertyInData=be.isOwnProperty=be.hasPropFunc=be.reportMissingProp=be.checkMissingProp=be.checkReportMissingProp=void 0;var Se=ee(),m_=fe(),dn=zr(),Hj=fe();function Wj(t,e){let{gen:r,data:o,it:n}=t;r.if(g_(r,o,e,n.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Se._)`${e}`},!0),t.error()})}be.checkReportMissingProp=Wj;function Bj({gen:t,data:e,it:{opts:r}},o,n){return(0,Se.or)(...o.map(i=>(0,Se.and)(g_(t,e,i,r.ownProperties),(0,Se._)`${n} = ${i}`)))}be.checkMissingProp=Bj;function Kj(t,e){t.setParams({missingProperty:e},!0),t.error()}be.reportMissingProp=Kj;function Xw(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Se._)`Object.prototype.hasOwnProperty`})}be.hasPropFunc=Xw;function h_(t,e,r){return(0,Se._)`${Xw(t)}.call(${e}, ${r})`}be.isOwnProperty=h_;function Gj(t,e,r,o){let n=(0,Se._)`${e}${(0,Se.getProperty)(r)} !== undefined`;return o?(0,Se._)`${n} && ${h_(t,e,r)}`:n}be.propertyInData=Gj;function g_(t,e,r,o){let n=(0,Se._)`${e}${(0,Se.getProperty)(r)} === undefined`;return o?(0,Se.or)(n,(0,Se.not)(h_(t,e,r))):n}be.noPropertyInData=g_;function Yw(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}be.allSchemaProperties=Yw;function Xj(t,e){return Yw(e).filter(r=>!(0,m_.alwaysValidSchema)(t,e[r]))}be.schemaProperties=Xj;function Yj({schemaCode:t,data:e,it:{gen:r,topSchemaRef:o,schemaPath:n,errorPath:i},it:a},c,u,l){let d=l?(0,Se._)`${t}, ${e}, ${o}${n}`:e,s=[[dn.default.instancePath,(0,Se.strConcat)(dn.default.instancePath,i)],[dn.default.parentData,a.parentData],[dn.default.parentDataProperty,a.parentDataProperty],[dn.default.rootData,dn.default.rootData]];a.opts.dynamicRef&&s.push([dn.default.dynamicAnchors
|
||
|
|
missingProperty: ${o},
|
||
|
|
depsCount: ${e},
|
||
|
|
deps: ${r}}`};var s4={keyword:"dependencies",type:"object",schemaType:"object",error:lr.error,code(t){let[e,r]=c4(t);xS(t,e),wS(t,r)}};function c4({schema:t}){let e={},r={};for(let o in t){if(o==="__proto__")continue;let n=Array.isArray(t[o])?e:r;n[o]=t[o]}return[e,r]}function xS(t,e=t.schema){let{gen:r,data:o,it:n}=t;if(Object.keys(e).length===0)return;let i=r.let("missing");for(let a in e){let c=e[a];if(c.length===0)continue;let u=(0,Sc.propertyInData)(r,o,a,n.opts.ownProperties);t.setParams({property:a,depsCount:c.length,deps:c.join(", ")}),n.allErrors?r.if(u,()=>{for(let l of c)(0,Sc.checkReportMissingProp)(t,l)}):(r.if((0,ay._)`${u} && (${(0,Sc.checkMissingProp)(t,c,i)})`),(0,Sc.reportMissingProp)(t,i),r.else())}}lr.validatePropertyDeps=xS;function wS(t,e=t.schema){let{gen:r,data:o,keyword:n,it:i}=t,a=r.name("valid");for(let c in e)(0,a4.alwaysValidSchema)(i,e[c])||(r.if((0,Sc.propertyInData)(r,o,c,i.opts.ownProperties),()=>{let u=t.subschema({keyword:n,schemaProp:c},a);t.mergeValidEvaluated(u,a)},()=>r.var(a,!0)),t.ok(a))}lr.validateSchemaDeps=wS;lr.default=s4});var zS=z(sy=>{"use strict";Object.defineProperty(sy,"__esModule",{value:!0});var SS=ee(),u4=fe(),l4={message:"property name must be valid",params:({params:t})=>(0,SS._)`{propertyName: ${t.propertyName}}`},d4={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:l4,code(t){let{gen:e,schema:r,data:o,it:n}=t;if((0,u4.alwaysValidSchema)(n,r))return;let i=e.name("valid");e.forIn("key",o,a=>{t.setParams({propertyName:a}),t.subschema({keyword:"propertyNames",data:a,dataTypes:["string"],propertyName:a,compositeRule:!0},i),e.if((0,SS.not)(i),()=>{t.error(!0),n.allErrors||e.break()})}),t.ok(i)}};sy.default=d4});var uy=z(cy=>{"use strict";Object.defineProperty(cy,"__esModule",{value:!0});var Qf=Ct(),Gt=ee(),f4=zr(),ep=fe(),p4={message:"must NOT have additional properties",params:({params:t})=>(0,Gt._)`{additionalProperty: ${t.additionalProperty}}`},m4={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:p4,code(t){let{gen:e,schema:r,parentSchema:o,data:n,errsCount:i,it:a}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:c,opts:u}=a;if(a.props=!0,u.removeAdditional!=="all"&&(0,ep.alwaysValidSchema)(a,r))return;let l=(0,Qf.allSchemaProperties)(o.properties),d=(0,Qf.allSchemaProperties)(o.patternProperties);s(),t.ok((0,Gt._)`${i} === ${f4.default.errors}`);function s(){e.forIn("key",n,g=>{!l.length&&!d.length?m(g):e.if(f(g),()=>m(g))})}function f(g){let y;if(l.length>8){let w=(0,ep.schemaRefOrVal)(a,o.properties,"properties");y=(0,Qf.isOwnProperty)(e,w,g)}else l.length?y=(0,Gt.or)(...l.map(w=>(0,Gt._)`${g} === ${w}`)):y=Gt.nil;return d.length&&(y=(0,Gt.or)(y,...d.map(w=>(0,Gt._)`${(0,Qf.usePattern)(t,w)}.test(${g})`))),(0,Gt.not)(y)}function p(g){e.code((0,Gt._)`delete ${n}[${g}]`)}function m(g){if(u.removeAdditional==="all"||u.removeAdditional&&r===!1){p(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),c||e.break();return}if(typeof r=="object"&&!(0,ep.alwaysValidSchema)(a,r)){let y=e.name("valid");u.removeAdditional==="failing"?(h(g,y,!1),e.if((0,Gt.not)(y),()=>{t.reset(),p(g)})):(h(g,y),c||e.if((0,Gt.not)(y),()=>e.break()))}}function h(g,y,w){let k={keyword:"additionalProperties",dataProp:g,dataPropType:ep.Type.Str};w===!1&&Object.assign(k,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(k,y)}}};cy.default=m4});var TS=z(dy=>{"use strict";Object.defineProperty(dy,"__esModule",{value:!0});var h4=dc(),IS=Ct(),ly=fe(),PS=uy(),g4={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:o,data:n,it:i}=t;i.opts.removeAdditional==="all"&&o.additionalProperties===void 0&&PS.default.code(new h4.KeywordCxt(i,PS.default,"additionalProperties"));let a=(0,IS.allSchemaProperties)(r);for(let s of a)i.definedProperties.add(s);i.opts.unevaluated&&a.length&&i.props!==!0&&(i.props=ly.mergeEvaluated.props(e,(0,ly.toHash)(a),i.props));let c=a.filter(s=>!(0,ly.alwaysValidSchema)(i,r[s]));if(c.length===0)return;let
|
||
|
|
### System instructions
|
||
|
|
|
||
|
|
${t}
|
||
|
|
|
||
|
|
### Tool calling instructions
|
||
|
|
- Make sure every message contains a tool call.
|
||
|
|
- When you use a tool, you may provide a brief thought or explanation in the content field
|
||
|
|
immediately before the tool_call. Do not split this into separate messages.
|
||
|
|
- Every reply must include a tool call.
|
||
|
|
`});var Hz=z(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});Ap.Google=void 0;var zU=Wc(),Fz=Bc(),$$=class{constructor(){zt(this,"name","google")}async complete(e,r){var l,d,s,f,p,m;let o=e.messages.map(OU).flat(),{response:n,error:i}=await IU((l=r.model)!=null?l:"gemini-2.5-pro",{systemInstruction:{role:"system",parts:[{text:RU(e.systemPrompt)}]},contents:o,tools:e.tools.length>0?[{functionDeclarations:e.tools.map(PU)}]:void 0,generationConfig:{temperature:r.temperature,maxOutputTokens:r.maxTokens}},r),[a]=(d=n==null?void 0:n.candidates)!=null?d:[];if(i||!n||!a)return{result:(0,Fz.assistantMessageFromError)(i!=null?i:"No response from Google API"),usage:(0,Fz.emptyUsage)()};let c={input:(f=(s=n.usageMetadata)==null?void 0:s.promptTokenCount)!=null?f:0,output:(m=(p=n.usageMetadata)==null?void 0:p.candidatesTokenCount)!=null?m:0};return{result:TU(a),usage:c}}};Ap.Google=$$;async function IU(t,e,r){var a,c,u,l,d,s;let o={...e,tools:`${(c=(a=e.tools)==null?void 0:a.length)!=null?c:0} tools`};(u=r.debug)==null||u.call(r,"lowire:google")("Request:",JSON.stringify(o,null,2));let n=await(0,zU.fetchWithTimeout)((l=r.apiEndpoint)!=null?l:`https://generativelanguage.googleapis.com/v1beta/models/${t}:generateContent`,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":r.apiKey},body:JSON.stringify(e),signal:r.signal,timeout:r.apiTimeout});if(!n.ok)return(d=r.debug)==null||d.call(r,"lowire:google")("Response:",n.status),{error:`API error: ${n.status} ${n.statusText} ${await n.text()}`};let i=await n.json();return(s=r.debug)==null||s.call(r,"lowire:google")("Response:",JSON.stringify(i,null,2)),{response:i}}function PU(t){return{name:t.name,description:t.description,parameters:Jz(t.inputSchema)}}function Jz(t){if(!t||typeof t!="object")return t;let e=Array.isArray(t)?[...t]:{...t};delete e.additionalProperties,delete e.$schema;for(let r in e)e[r]&&typeof e[r]=="object"&&(e[r]=Jz(e[r]));return e}function TU(t){let e={code:"ok"};return t.finishReason==="MAX_TOKENS"&&(e.code="max_tokens"),{role:"assistant",content:(t.content.parts||[]).map(EU).filter(Boolean),stopReason:e}}function EU(t){return t.text?{type:"text",text:t.text,googleThoughtSignature:t.thoughtSignature}:t.functionCall?{type:"tool_call",name:t.functionCall.name,arguments:t.functionCall.args,id:`call_${Math.random().toString(36).substring(2,15)}`,googleThoughtSignature:t.thoughtSignature}:null}function OU(t){if(t.role==="user")return[{role:"user",parts:[{text:t.content}]}];if(t.role==="assistant"){let e=[],r=[];for(let o of t.content){if(o.type==="text"){e.push({text:o.text,thoughtSignature:o.googleThoughtSignature});continue}o.type==="tool_call"&&(e.push({functionCall:{name:o.name,args:o.arguments},thoughtSignature:o.googleThoughtSignature}),o.result&&r.push(...jU(o,o.result)))}return t.toolError&&r.push({role:"user",parts:[{text:t.toolError}]}),[{role:"model",parts:e},...r]}throw new Error(`Unsupported message role: ${t.role}`)}function jU(t,e){let r={},o=[],n=[];for(let a of e.content)a.type==="text"?o.push(a.text):a.type==="image"&&n.push({inline_data:{mime_type:a.mimeType,data:a.data}});o.length>0&&(r.result=o.join(`
|
||
|
|
`));let i=[{role:"function",parts:[{functionResponse:{name:t.name,response:r}}]}];return n.length>0&&i.push({role:"user",parts:n}),i}var RU=t=>`
|
||
|
|
### System instructions
|
||
|
|
|
||
|
|
${t}
|
||
|
|
|
||
|
|
### Tool calling instructions
|
||
|
|
- Make sure every message contains a tool call.
|
||
|
|
- When you use a tool, you may provide a brief thought or explanation in the content field
|
||
|
|
immediately before the tool_call. Do not split this into separate messages.
|
||
|
|
- Every reply must include a tool call.
|
||
|
|
`});var Bz=z(Zp=>{"use strict";Object.defineProperty(Zp,"__esModule",{value:!0});Zp.OpenAI=void 0;var NU=Wc(),Wz=Bc(),b$=class{constructor(){zt(this,"name","openai")}async complete(e,r){return CU(e,r)}};Zp.OpenAI=b$;async function CU(t,e){var l,d,s,f,p;let r=t.messages.map(AU).flat(),o=t.tools.map(ZU),{response:n,error:i}=await DU({model:e.model,temperature:e.temperature,input:r,instructions:VU(t.systemPrompt),tools:o.length>0?o:void 0,tool_choice:t.tools.length>0?"auto":void 0,parallel_tool_calls:!1,max_output_tokens:e.maxTokens,reasoning:LU(e.reasoning)},e);if(!n||i)return{result:(0,Wz.assistantMessageFromError)(i!=null?i:"No response from OpenAI API"),usage:(0,Wz.emptyUsage)()};let a={code:"ok"};((l=n.incomplete_details)==null?void 0:l.reason)==="max_output_tokens"&&(a.code="max_tokens");let c={role:"assistant",content:[],stopReason:a},u={input:(s=(d=n.usage)==null?void 0:d.input_tokens)!=null?s:0,output:(p=(f=n.usage)==null?void 0:f.output_tokens)!=null?p:0};if(a.code!=="ok")return{result:c,usage:u};for(let m of n.output)if(m.type==="message"&&m.role==="assistant"){c.openaiId=m.id,c.openaiStatus=m.status;for(let h of m.content)h.type==="output_text"&&c.content.push({type:"text",text:h.text})}else m.type==="function_call"&&c.content.push(qU(m));return{result:c,usage:u}}async function DU(t,e){var c,u,l,d,s;let r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},o={...t,tools:`${(u=(c=t.tools)==null?void 0:c.length)!=null?u:0} tools`};(l=e.debug)==null||l.call(e,"lowire:openai-responses")("Request:",JSON.stringify(o,null,2));let n=await(0,NU.fetchWithTimeout)((d=e.apiEndpoint)!=null?d:"https://api.openai.com/v1/responses",{method:"POST",headers:r,body:JSON.stringify(t),signal:e.signal,timeout:e.apiTimeout}),i=await n.text(),a=JSON.parse(i);if(!n.ok)try{return{error:a.error.message}}catch{return{error:i}}return(s=e.debug)==null||s.call(e,"lowire:openai-responses")("Response:",JSON.stringify(a,null,2)),{response:a}}function UU(t){if(t.type==="text")return{type:"input_text",text:t.text};if(t.type==="image")return{type:"input_image",image_url:`data:${t.mimeType};base64,${t.data}`,detail:"auto"};throw new Error(`Cannot convert content part of type ${t.type} to response content part`)}function AU(t){if(t.role==="user")return[{type:"message",role:"user",content:t.content}];if(t.role==="assistant"){let e=t.content.filter(n=>n.type==="text"),r=t.content.filter(n=>n.type==="tool_call"),o=[];if(e.length>0){let n={id:t.openaiId,status:t.openaiStatus,type:"message",role:"assistant",content:e.map(i=>({type:"output_text",text:i.text,annotations:[],logprobs:[]}))};o.push(n)}return t.toolError&&o.push({type:"message",role:"user",content:t.toolError}),o.push(...r.map(MU).flat()),o}throw new Error(`Unsupported message role: ${t.role}`)}function ZU(t){var e;return{type:"function",name:t.name,description:(e=t.description)!=null?e:null,parameters:t.inputSchema,strict:null}}function MU(t){let e=[{type:"function_call",call_id:t.id,name:t.name,arguments:JSON.stringify(t.arguments),id:t.openaiId,status:t.openaiStatus}];return t.result&&e.push({type:"function_call_output",call_id:t.id,output:t.result.content.map(UU)}),e}function qU(t){return{type:"tool_call",name:t.name,arguments:JSON.parse(t.arguments),id:t.call_id,openaiId:t.id,openaiStatus:t.status}}function LU(t){switch(t){case"none":return{effort:"none"};case"medium":return{effort:"medium"};case"high":return{effort:"high"}}}var VU=t=>`
|
||
|
|
### System instructions
|
||
|
|
|
||
|
|
${t}
|
||
|
|
|
||
|
|
### Tool calling instructions
|
||
|
|
- Make sure every message contains a tool call.
|
||
|
|
- When you use a tool, you may provide a brief thought or explanation in the content field
|
||
|
|
immediately before the tool_call. Do not split this into separate messages.
|
||
|
|
- Every reply must include a tool call.
|
||
|
|
`});var Gz=z(Mp=>{"use strict";Object.defineProperty(Mp,"__esModule",{value:!0});Mp.OpenAICompatible=void 0;var FU=Wc(),Kz=Bc(),x$=class{constructor(){zt(this,"name","openai-compatible")}async complete(e,r){return JU(e,r)}};Mp.OpenAICompatible=x$;async function JU(t,e){var d,s,f,p,m,h;let o=[{role:"system",content:YU(t.systemPrompt)},...t.messages.map(BU).flat()],n=t.tools.map(g=>KU(g)),{response:i,error:a}=await HU({model:e.model,max_completion_tokens:e.maxTokens,temperature:e.temperature,messages:o,tools:n,tool_choice:t.tools.length>0?"auto":void 0,reasoning_effort:XU(e.reasoning),parallel_tool_calls:!1},e);if(a||!i)return{result:(0,Kz.assistantMessageFromError)((d=a==null?void 0:a.message)!=null?d:"No response from OpenAI compatible API"),usage:(0,Kz.emptyUsage)()};let c={role:"assistant",content:[],stopReason:{code:"ok"}},u=(s=i.choices[0])==null?void 0:s.finish_reason;for(let g of i.choices){let y=g.message;y.content&&c.content.push({type:"text",text:y.content});for(let w of y.tool_calls||[])w.type==="function"&&c.content.push(GU(w))}u==="length"&&(c.stopReason={code:"max_tokens"});let l={input:(p=(f=i.usage)==null?void 0:f.prompt_tokens)!=null?p:0,output:(h=(m=i.usage)==null?void 0:m.completion_tokens)!=null?h:0};return{result:c,usage:l}}async function HU(t,e){var c,u,l,d,s;let r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},o={...t,tools:`${(u=(c=t.tools)==null?void 0:c.length)!=null?u:0} tools`};(l=e.debug)==null||l.call(e,"lowire:openai")("Request:",JSON.stringify(o,null,2));let n=await(0,FU.fetchWithTimeout)((d=e.apiEndpoint)!=null?d:"https://api.openai.com/v1/chat/completions",{method:"POST",headers:r,body:JSON.stringify(t),signal:e.signal,timeout:e.apiTimeout}),i=await n.text(),a=JSON.parse(i);if(!n.ok)try{return{error:a}}catch{return{error:{type:"unknown",message:i}}}return(s=e.debug)==null||s.call(e,"lowire:openai")("Response:",JSON.stringify(a,null,2)),{response:a}}function WU(t){if(t.type==="text")return{type:"text",text:t.text};if(t.type==="image")return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}};throw new Error(`Cannot convert content part of type ${t.type} to text content part`)}function BU(t){if(t.role==="user")return[{role:"user",content:t.content}];if(t.role==="assistant"){let e={role:"assistant"},r=t.content.filter(a=>a.type==="text"),o=t.content.filter(a=>a.type==="tool_call");r.length===1?e.content=r[0].text:e.content=r;let n=[],i=[];for(let a of o)n.push({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.arguments)}}),a.result&&i.push({role:"tool",tool_call_id:a.id,content:a.result.content.map(WU)});return n.length>0&&(e.tool_calls=n),t.toolError&&i.push({role:"user",content:[{type:"text",text:t.toolError}]}),[e,...i]}throw new Error(`Unsupported message role: ${t.role}`)}function KU(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}}function GU(t){return{type:"tool_call",name:t.type==="function"?t.function.name:t.custom.name,arguments:JSON.parse(t.type==="function"?t.function.arguments:t.custom.input),id:t.id}}function XU(t){switch(t){case"none":return"none";case"medium":return"medium";case"high":return"high"}}var YU=t=>`
|
||
|
|
### System instructions
|
||
|
|
|
||
|
|
${t}
|
||
|
|
|
||
|
|
### Tool calling instructions
|
||
|
|
- Make sure every message contains a tool call.
|
||
|
|
- When you use a tool, you may provide a brief thought or explanation in the content field
|
||
|
|
immediately before the tool_call. Do not split this into separate messages.
|
||
|
|
- Every reply must include a tool call.
|
||
|
|
`});var Xz=z(w$=>{"use strict";Object.defineProperty(w$,"__esModule",{value:!0});w$.getProvider=nA;var QU=Vz(),eA=Hz(),tA=Bz(),rA=Gz();function nA(t){if(t==="openai")return new tA.OpenAI;if(t==="openai-compatible")return new rA.OpenAICompatible;if(t==="anthropic")return new QU.Anthropic;if(t==="google")return new eA.Google;throw new Error(`Unknown loop LLM: ${t}`)}});var Yz=z(Kc=>{"use strict";var oA=Kc&&Kc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Kc,"__esModule",{value:!0});Kc.cachedComplete=aA;var iA=oA(require("crypto"));async function aA(t,e,r,o){let n=cA(e,o.secrets),i=await sA(t,n,r,o);return uA(i,o.secrets)}async function sA(t,e,r,o){var c;if(!r)return await t.complete(e,o);let n={conversation:o.cacheMode==="lax"?{...e,tools:[]}:e,maxTokens:o.maxTokens,reasoning:o.reasoning,temperature:o.temperature},i=lA(JSON.stringify(n));if(!process.env.LOWIRE_NO_CACHE&&r.input[i])return r.output[i]=r.input[i],(c=r.input[i])!=null?c:r.output[i];if(!process.env.LOWIRE_NO_CACHE&&r.output[i])return r.output[i];if(process.env.LOWIRE_FORCE_CACHE)throw new Error("Cache missing but LOWIRE_FORCE_CACHE is set"+JSON.stringify(e,null,2));let a=await t.complete(e,o);return r.output[i]=a,a}function cA(t,e={}){let r=JSON.stringify(t);for(let[o,n]of Object.entries(e))r=r.replaceAll(n,`%${o}%`);return JSON.parse(r)}function uA(t,e={}){let r=JSON.stringify(t);for(let[o,n]of Object.entries(e))r=r.replaceAll(`%${o}%`,n);return JSON.parse(r)}function lA(t){let e=iA.default.createHash("sha1");return e.update(t),e.digest("hex")}});var k$=z(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.jsxs=void 0;Gc.jsx=Qz;function Qz(t,e){let{children:r,...o}=e||{},n=Object.entries(o),i=(Array.isArray(r)?r.flat():r?[r]:[]).filter(c=>c&&!!c.trim()),a=[`${t}:`];for(let[c,u]of n)a.push(` ${c}: ${u}`);for(let c of i){let u=c.split(`
|
||
|
|
`).map(l=>` ${l}`).join(`
|
||
|
|
`);a.push(u)}return a.join(`
|
||
|
|
`)}Gc.jsxs=Qz});var tI=z(S$=>{"use strict";Object.defineProperty(S$,"__esModule",{value:!0});S$.summarizeConversation=dA;var lo=k$(),eI=k$();function dA(t,e,r){var c,u,l,d,s;let o=["## Task",t],n={},i=e.messages.filter(f=>f.role==="assistant");for(let f=0;f<i.length-1;++f){f===0&&(o.push(""),o.push("## History")),o.push("");let p=i[f].content.filter(g=>g.type==="text").map(g=>g.text).join(`
|
||
|
|
`),m=i[f].content.filter(g=>g.type==="tool_call");for(let g of m)if(g.result)for(let[y,w]of Object.entries(((c=g.result._meta)==null?void 0:c["dev.lowire/state"])||{}))n[y]=w;let h=i[f];o.push((0,lo.jsxs)("step",{turn:f+1,children:[(0,lo.jsx)("title",{children:p}),m.map(g=>(0,lo.jsxs)("tool-call",{children:[(0,lo.jsx)("name",{children:g.name}),Object.keys(g.arguments).length>0&&(0,lo.jsx)("arguments",{children:Object.entries(g.arguments).map(([y,w])=>(0,eI.jsx)(y,{children:[JSON.stringify(w)]}))})]})),m.map(g=>{var y,w;return((w=(y=g.result)==null?void 0:y._meta)==null?void 0:w["dev.lowire/history"])||[]}).flat().map(g=>(0,eI.jsx)(g.category,{children:[g.content]})),h.toolError&&(0,lo.jsx)("error",{children:h.toolError})]}))}let a=i[i.length-1];if(a)for(let f of a.content.filter(p=>p.type==="tool_call"))for(let p of Object.keys(((l=(u=f.result)==null?void 0:u._meta)==null?void 0:l["dev.lowire/state"])||{}))delete n[p];for(let[f,p]of Object.entries(n))o.push(""),o.push((0,lo.jsx)("state",{name:f,children:p}));return(d=r.debug)==null||d.call(r,"lowire:summary")(o.join(`
|
||
|
|
`)),(s=r.debug)==null||s.call(r,"lowire:summary")(JSON.stringify(a,null,2)),{summary:o.join(`
|
||
|
|
`),lastMessage:a}}});var rI=z(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});qp.Loop=void 0;var fA=Xz(),pA=Yz(),mA=tI(),z$=class{constructor(e){zt(this,"_provider");zt(this,"_loopOptions");zt(this,"_cacheOutput",{});this._provider=(0,fA.getProvider)(e.api),this._loopOptions=e}async run(e,r={}){var d,s,f,p,m,h,g,y,w,k;let o={...this._loopOptions,...r},n=[...(o.tools||[]).map(hA)],i={systemPrompt:gA,messages:[{role:"user",content:e}],tools:n},a=o.debug,c={tokens:o.maxTokens,toolCalls:o.maxToolCalls,toolCallRetries:o.maxToolCallRetries},u={input:0,output:0};a==null||a("lowire:loop")(`Starting ${this._provider.name} loop
|
||
|
|
${e}`);let l=o.maxTurns||100;for(let b=0;b<l;++b){if(o.maxTokens&&c.tokens!==void 0&&c.tokens<=0)return{status:"error",error:`Budget tokens ${o.maxTokens} exhausted`,usage:u,turns:b};a==null||a("lowire:loop")(`Turn ${b+1} of (max ${l})`);let x=o.cache?{input:o.cache,output:this._cacheOutput}:void 0,D=o.summarize?this._summarizeConversation(e,i,o):i;if(await((d=o.onBeforeTurn)==null?void 0:d.call(o,{conversation:D,totalUsage:u,budgetTokens:c.tokens})),(s=o.signal)!=null&&s.aborted)return{status:"break",usage:u,turns:b};a==null||a("lowire:loop")("Request",JSON.stringify({...D,tools:`${D.tools.length} tools`},null,2));let V=Math.floor(JSON.stringify(D).length/4);if(c.tokens!==void 0&&V>=c.tokens)return{status:"error",error:`Input token estimate ${V} exceeds budget ${c.tokens}`,usage:u,turns:b};let{result:K,usage:se}=await(0,pA.cachedComplete)(this._provider,D,x,{...o,maxTokens:c.tokens!==void 0?c.tokens-V:void 0,signal:o.signal});if(K.stopReason.code==="error")return{status:"error",error:K.stopReason.message,usage:u,turns:b};if(K.stopReason.code==="max_tokens")return{status:"error",error:"Max tokens exhausted",usage:u,turns:b};let De=K.content.filter(je=>je.type==="text").map(je=>je.text).join(`
|
||
|
|
`);if(u.input+=se.input,u.output+=se.output,c.tokens!==void 0&&(c.tokens-=se.input+se.output),a==null||a("lowire:loop")("Usage",`input: ${se.input}, output: ${se.output}`),a==null||a("lowire:loop")("Assistant",De,JSON.stringify(K.content,null,2)),await((f=o.onAfterTurn)==null?void 0:f.call(o,{assistantMessage:K,totalUsage:u,budgetTokens:c.tokens})),(p=o.signal)!=null&&p.aborted)return{status:"break",usage:u,turns:b};i.messages.push(K);let Oe=K.content.filter(je=>je.type==="tool_call");if(Oe.length===0){K.toolError='Error: tool call is expected in every assistant message. Call the "report_result" tool when the task is complete.';continue}for(let je of Oe){if(c.toolCalls!==void 0&&--c.toolCalls<0)return{status:"error",error:`Failed to perform step, max tool calls (${o.maxToolCalls}) reached`,usage:u,turns:b};let{name:At,arguments:A}=je;a==null||a("lowire:loop")("Call tool",At,JSON.stringify(A,null,2));let ke=await((m=o.onBeforeToolCall)==null?void 0:m.call(o,{assistantMessage:K,toolCall:je}));if((h=o.signal)!=null&&h.aborted)return{status:"break",usage:u,turns:b};if(ke==="disallow"){je.result={content:[{type:"text",text:"Tool call is disallowed."}],isError:!0};continue}try{let Ie=await o.callTool({name:At,arguments:{...A,_meta:{"dev.lowire/intent":De,"dev.lowire/history":!0,"dev.lowire/state":!0}}}),rt=Ie.content.filter(bn=>bn.type==="text").map(bn=>bn.text).join(`
|
||
|
|
`);a==null||a("lowire:loop")("Tool result",rt,JSON.stringify(Ie,null,2));let St=await((g=o.onAfterToolCall)==null?void 0:g.call(o,{assistantMessage:K,toolCall:je,result:Ie}));if((y=o.signal)!=null&&y.aborted)return{status:"break",usage:u,turns:b};if(St==="disallow"){je.result={content:[{type:"text",text:"Tool result is disallowed to be reported."}],isError:!0};continue}if(je.result=Ie,A._is_done&&!Ie.isError)return{result:Ie,status:"ok",usage:u,turns:b}}catch(Ie){let rt=`Error while executing tool "${At}": ${Ie instanceof Error?Ie.message:String(Ie)}
|
||
|
|
|
||
|
|
Please try to recover and complete the task.`;if(await((w=o.onToolCallError)==null?void 0:w.call(o,{assistantMessage:K,toolCall:je,error:Ie})),(k=o.signal)!=null&&k.aborted)return{status:"break",usage:u,turns:b};je.result={content:[{type:"text",text:rt}],isError:!0}}}let Qt=Oe.some(je=>{var At;return(At=je.result)==null?void 0:At.isError});if(Qt||(c.toolCallRetries=o.maxToolCallRetries),Qt&&c.toolCallRetries!==void 0&&--c.toolCallRetries<0)return{status:"error",error:`Failed to perform action after ${o.maxToolCallRetries} tool call retries`,usage:u,turns:b}}return{status:"error",error:"Failed to perform step, max attempts reached",usage:u,turns:l}}_summarizeConversation(e,r,o){let{summary:n,lastMessage:i}=(0,mA.summarizeConversation)(e,r,o);return{...r,messages:[{role:"user",content:n},...i?[i]:[]]}}cache(){return this._cacheOutput}};qp.Loop=z$;function hA(t){let e={...t.inputSchema};return e.properties={...e.properties,_is_done:{type:"boolean",description:"Whether the task is complete. If false, agentic loop will continue to perform the task."}},e.required=[...e.required||[],"_is_done"],{...t,inputSchema:e}}var gA=`
|
||
|
|
- You are an autonomous agent designed to complete tasks by interacting with tools.
|
||
|
|
- Perform the user task.
|
||
|
|
- If you see text surrounded by %, it is a secret and you should preserve it as such. It will be replaced with the actual value before the tool call.
|
||
|
|
`});var _A={};_t(_A,{CallToolRequestSchema:()=>Bs,Client:()=>dp,ListRootsRequestSchema:()=>Nv,ListToolsRequestSchema:()=>zv,Loop:()=>Fi.Loop,PingRequestSchema:()=>ui,ProgressNotificationSchema:()=>li,SSEClientTransport:()=>$p,SSEServerTransport:()=>xp,Server:()=>pp,StdioClientTransport:()=>Sp,StdioServerTransport:()=>zp,StreamableHTTPClientTransport:()=>Cp,StreamableHTTPServerTransport:()=>Rp,z:()=>Lp,zodToJsonSchema:()=>wf});module.exports=lI(_A);var ie;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{let i={};for(let a of n)i[a]=a;return i},t.getValidEnumValues=n=>{let i=t.objectKeys(n).filter(c=>typeof n[n[c]]!="number"),a={};for(let c of i)a[c]=n[c];return t.objectValues(a)},t.objectValues=n=>t.objectKeys(n).map(function(i){return n[i]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&i.push(a);return i},t.find=(n,i)=>{for(let a of n)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function o(n,i=" | "){return n.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=o,t.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(ie||(ie={}));var E$;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(E$||(E$={}));var U=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),pr=t=>{switch(typeof t){case"undefined":return U.undefined;case"string":return U.string;case"number":return Number.isNaN(t)?U.nan:U.number;case"boolean":return U.boolean;case"function":return U.function;case"bigint":return U.bigint;case"symbol":return U.symbol;case"object":return Array.isArray(t)?U.array:t===null?U.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?U.promise:typeof Map!="undefined"&&t instanceof Map?U.map:typeof Set!="undefined"&&t instanceof Set?U.set:typeof Date!="undefined"&&t instanceof Date?U.date:U.object;default:return U.unknown}};var P=ie.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var yt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=o=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(i){return i.message},o={_errors:[]},n=i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(n);else if(a.code==="invalid_return_type")n(a.returnTypeError);else if(a.code==="invalid_arguments")n(a.argumentsError);else if(a.path.length===0)o._errors.push(r(a));else{let c=o,u=0;for(;u<a.path.length;){let l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(r(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}};return n(this),o}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ie.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r=Object.create(null),o=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(e(n))}else o.push(e(n));return{formErrors:o,fieldErrors:r}}get formErrors(){return this.flatten()}};yt.create=t=>new yt(t);var dI=(t,e)=>{let r;switch(t.code){case P.invalid_type:t.received===U.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case P.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ie.jsonStringifyReplacer)}`;break;case P.unrecog
|
||
|
|
`)}var Eo=t=>(e,r,o,n)=>{var c;let i=o?Object.assign(o,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new qt;if(a.issues.length){let u=new((c=n==null?void 0:n.Err)!=null?c:t)(a.issues.map(l=>dt(l,i,Pe())));throw ru(u,n==null?void 0:n.callee),u}return a.value},Pn=Eo(ft),Oo=t=>async(e,r,o,n)=>{var c;let i=o?Object.assign(o,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let u=new((c=n==null?void 0:n.Err)!=null?c:t)(a.issues.map(l=>dt(l,i,Pe())));throw ru(u,n==null?void 0:n.callee),u}return a.value},Tn=Oo(ft),jo=t=>(e,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new qt;return i.issues.length?{success:!1,error:new(t!=null?t:pa)(i.issues.map(a=>dt(a,n,Pe())))}:{success:!0,data:i.value}},qr=jo(ft),Ro=t=>async(e,r,o)=>{let n=o?Object.assign(o,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(a=>dt(a,n,Pe())))}:{success:!0,data:i.value}},En=Ro(ft),ou=t=>(e,r,o)=>{let n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Eo(t)(e,r,n)},H$=ou(ft),iu=t=>(e,r,o)=>Eo(t)(e,r,o),W$=iu(ft),au=t=>async(e,r,o)=>{let n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Oo(t)(e,r,n)},B$=au(ft),su=t=>async(e,r,o)=>Oo(t)(e,r,o),K$=su(ft),cu=t=>(e,r,o)=>{let n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return jo(t)(e,r,n)},G$=cu(ft),uu=t=>(e,r,o)=>jo(t)(e,r,o),X$=uu(ft),lu=t=>async(e,r,o)=>{let n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Ro(t)(e,r,n)},Y$=lu(ft),du=t=>async(e,r,o)=>Ro(t)(e,r,o),Q$=du(ft);var Ke={};_t(Ke,{base64:()=>bm,base64url:()=>fu,bigint:()=>Im,boolean:()=>Tm,browserEmail:()=>dP,cidrv4:()=>ym,cidrv6:()=>$m,cuid:()=>am,cuid2:()=>sm,date:()=>wm,datetime:()=>Sm,domain:()=>mP,duration:()=>fm,e164:()=>xm,email:()=>mm,emoji:()=>hm,extendedDuration:()=>oP,guid:()=>pm,hex:()=>hP,hostname:()=>pP,html5Email:()=>cP,idnEmail:()=>lP,integer:()=>Pm,ipv4:()=>gm,ipv6:()=>vm,ksuid:()=>lm,lowercase:()=>jm,mac:()=>_m,md5_base64:()=>vP,md5_base64url:()=>_P,md5_hex:()=>gP,nanoid:()=>dm,null:()=>Em,number:()=>pu,rfc5322Email:()=>uP,sha1_base64:()=>$P,sha1_base64url:()=>bP,sha1_hex:()=>yP,sha256_base64:()=>wP,sha256_base64url:()=>kP,sha256_hex:()=>xP,sha384_base64:()=>zP,sha384_base64url:()=>IP,sha384_hex:()=>SP,sha512_base64:()=>TP,sha512_base64url:()=>EP,sha512_hex:()=>PP,string:()=>zm,time:()=>km,ulid:()=>cm,undefined:()=>Om,unicodeEmail:()=>eb,uppercase:()=>Rm,uuid:()=>On,uuid4:()=>iP,uuid6:()=>aP,uuid7:()=>sP,xid:()=>um});var am=/^[cC][^\s-]{8,}$/,sm=/^[0-9a-z]+$/,cm=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,um=/^[0-9a-vA-V]{20}$/,lm=/^[A-Za-z0-9]{27}$/,dm=/^[a-zA-Z0-9_-]{21}$/,fm=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,oP=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,pm=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,On=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,iP=On(4),aP=On(6),sP=On(7),mm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,cP=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,uP=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,eb=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,lP
|
||
|
|
`).filter(a=>a),n=Math.min(...o.map(a=>a.length-a.trimStart().length)),i=o.map(a=>a.slice(n)).map(a=>" ".repeat(this.indent*2)+a);for(let a of i)this.content.push(a)}compile(){var i;let e=Function,r=this==null?void 0:this.args,n=[...((i=this==null?void 0:this.content)!=null?i:[""]).map(a=>` ${a}`)];return new e(...r,n.join(`
|
||
|
|
`))}};var Ym={major:4,minor:3,patch:5};var W=_("$ZodType",(t,e)=>{var n,i,a;var r;t!=null||(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Ym;let o=[...(n=t._zod.def.checks)!=null?n:[]];t._zod.traits.has("$ZodCheck")&&o.unshift(t);for(let c of o)for(let u of c._zod.onattach)u(t);if(o.length===0)(i=(r=t._zod).deferred)!=null||(r.deferred=[]),(a=t._zod.deferred)==null||a.push(()=>{t._zod.run=t._zod.parse});else{let c=(l,d,s)=>{let f=Mr(l),p;for(let m of d){if(m._zod.def.when){if(!m._zod.def.when(l))continue}else if(f)continue;let h=l.issues.length,g=m._zod.check(l);if(g instanceof Promise&&(s==null?void 0:s.async)===!1)throw new qt;if(p||g instanceof Promise)p=(p!=null?p:Promise.resolve()).then(async()=>{await g,l.issues.length!==h&&(f||(f=Mr(l,h)))});else{if(l.issues.length===h)continue;f||(f=Mr(l,h))}}return p?p.then(()=>l):l},u=(l,d,s)=>{if(Mr(l))return l.aborted=!0,l;let f=c(d,o,s);if(f instanceof Promise){if(s.async===!1)throw new qt;return f.then(p=>t._zod.parse(p,s))}return t._zod.parse(f,s)};t._zod.run=(l,d)=>{if(d.skipChecks)return t._zod.parse(l,d);if(d.direction==="backward"){let f=t._zod.parse({value:l.value,issues:[]},{...d,skipChecks:!0});return f instanceof Promise?f.then(p=>u(p,l,d)):u(f,l,d)}let s=t._zod.parse(l,d);if(s instanceof Promise){if(d.async===!1)throw new qt;return s.then(f=>c(f,o,d))}return c(s,o,d)}}Y(t,"~standard",()=>({validate:c=>{var u;try{let l=qr(t,c);return l.success?{value:l.data}:{issues:(u=l.error)==null?void 0:u.issues}}catch{return En(t,c).then(d=>{var s;return d.success?{value:d.data}:{issues:(s=d.error)==null?void 0:s.issues}})}},vendor:"zod",version:1}))}),_r=_("$ZodString",(t,e)=>{var r,o,n;W.init(t,e),t._zod.pattern=(n=[...(o=(r=t==null?void 0:t._zod.bag)==null?void 0:r.patterns)!=null?o:[]].pop())!=null?n:zm(t._zod.bag),t._zod.parse=(i,a)=>{if(e.coerce)try{i.value=String(i.value)}catch{}return typeof i.value=="string"||i.issues.push({expected:"string",code:"invalid_type",input:i.value,inst:t}),i}}),me=_("$ZodStringFormat",(t,e)=>{No.init(t,e),_r.init(t,e)}),bu=_("$ZodGUID",(t,e)=>{var r;(r=e.pattern)!=null||(e.pattern=pm),me.init(t,e)}),xu=_("$ZodUUID",(t,e)=>{var r,o;if(e.version){let i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(i===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);(r=e.pattern)!=null||(e.pattern=On(i))}else(o=e.pattern)!=null||(e.pattern=On());me.init(t,e)}),wu=_("$ZodEmail",(t,e)=>{var r;(r=e.pattern)!=null||(e.pattern=mm),me.init(t,e)}),ku=_("$ZodURL",(t,e)=>{me.init(t,e),t._zod.check=r=>{try{let o=r.value.trim(),n=new URL(o);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=n.href:r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Su=_("$ZodEmoji",(t,e)=>{var r;(r=e.pattern)!=null||(e.pattern=hm()),me.init(t,e)}),zu=_("$ZodNanoID",(t,e)=>{var r;(r=e.pattern)!=null||(e.pattern=dm),me.init(t,e)}),Iu=_("$ZodCUID",(t,e)=>{var r;(r=e.pattern)!=null||(e.pattern=am),me.init(t,e)}),Pu=_("$ZodCUID2",(t,e)=>{var r;(r=e.pattern)!=null||(e.pattern=sm),me.init(t,e)}),Tu=_("$ZodULID",(t,e)=>{var r;(r=e.pattern)!=null||(e.pattern=cm),me.init(t,e)}),Eu=_("$ZodXID",(t,e)=>{var r;(r=e.pattern)!=null||(e.pattern=um),me.init(t,e)}),Ou=_("$ZodKSUID",(t,e)=>{var r;(r=e.pattern)!=null||(e.pattern=lm),me.init(t,e)}),ya=_("$ZodISODateTime",(t,e)=>{var r;(r=e.pattern)!=null||(e.pattern=Sm(e)),me.init(t,e)}),$a=_("$ZodISODate",(t,e)=>{var r;(r=e.pattern)!=null||(e.pattern=wm),me.init(t,e)}),ba=_("$ZodISOTime",(t,e)=>{var r;(r=e.pattern)!=null||(e.pattern=km(e)),me.init(t,e)}),xa=_("$ZodISODuration",(t,e)=>{var r;(r=e.pattern)!=null||(e.pattern=fm),me.in
|
||
|
|
if (${x}.issues.length) {
|
||
|
|
if (${D} in input) {
|
||
|
|
payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
|
||
|
|
...iss,
|
||
|
|
path: iss.path ? [${D}, ...iss.path] : [${D}]
|
||
|
|
})));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (${x}.value === undefined) {
|
||
|
|
if (${D} in input) {
|
||
|
|
newResult[${D}] = undefined;
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
newResult[${D}] = ${x}.value;
|
||
|
|
}
|
||
|
|
|
||
|
|
`):p.write(`
|
||
|
|
if (${x}.issues.length) {
|
||
|
|
payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
|
||
|
|
...iss,
|
||
|
|
path: iss.path ? [${D}, ...iss.path] : [${D}]
|
||
|
|
})));
|
||
|
|
}
|
||
|
|
|
||
|
|
if (${x}.value === undefined) {
|
||
|
|
if (${D} in input) {
|
||
|
|
newResult[${D}] = undefined;
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
newResult[${D}] = ${x}.value;
|
||
|
|
}
|
||
|
|
|
||
|
|
`)}p.write("payload.value = newResult;"),p.write("return payload;");let w=p.compile();return(b,x)=>w(f,b,x)},i,a=Sn,c=!aa.jitless,l=c&&tm.value,d=e.catchall,s;t._zod.parse=(f,p)=>{s!=null||(s=o.value);let m=f.value;return a(m)?c&&l&&(p==null?void 0:p.async)===!1&&p.jitless!==!0?(i||(i=n(e.shape)),f=i(f,p),d?$b([],m,f,p,s,t):f):r(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),f)}});function sb(t,e,r,o){for(let i of t)if(i.issues.length===0)return e.value=i.value,e;let n=t.filter(i=>!Mr(i));return n.length===1?(e.value=n[0].value,n[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(i=>i.issues.map(a=>dt(a,o,Pe())))}),e)}var Uo=_("$ZodUnion",(t,e)=>{W.init(t,e),Y(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Y(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Y(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Y(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>ua(i.source)).join("|")})$`)}});let r=e.options.length===1,o=e.options[0]._zod.run;t._zod.parse=(n,i)=>{if(r)return o(n,i);let a=!1,c=[];for(let u of e.options){let l=u._zod.run({value:n.value,issues:[]},i);if(l instanceof Promise)c.push(l),a=!0;else{if(l.issues.length===0)return l;c.push(l)}}return a?Promise.all(c).then(u=>sb(u,n,t,i)):sb(c,n,t,i)}});function cb(t,e,r,o){let n=t.filter(i=>i.issues.length===0);return n.length===1?(e.value=n[0].value,e):(n.length===0?e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(i=>i.issues.map(a=>dt(a,o,Pe())))}):e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:[],inclusive:!1}),e)}var Yu=_("$ZodXor",(t,e)=>{Uo.init(t,e),e.inclusive=!1;let r=e.options.length===1,o=e.options[0]._zod.run;t._zod.parse=(n,i)=>{if(r)return o(n,i);let a=!1,c=[];for(let u of e.options){let l=u._zod.run({value:n.value,issues:[]},i);l instanceof Promise?(c.push(l),a=!0):c.push(l)}return a?Promise.all(c).then(u=>cb(u,n,t,i)):cb(c,n,t,i)}}),Qu=_("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Uo.init(t,e);let r=t._zod.parse;Y(t._zod,"propValues",()=>{let n={};for(let i of e.options){let a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[c,u]of Object.entries(a)){n[c]||(n[c]=new Set);for(let l of u)n[c].add(l)}}return n});let o=Po(()=>{var a;let n=e.options,i=new Map;for(let c of n){let u=(a=c._zod.propValues)==null?void 0:a[e.discriminator];if(!u||u.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(c)}"`);for(let l of u){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,c)}}return i});t._zod.parse=(n,i)=>{let a=n.value;if(!Sn(a))return n.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),n;let c=o.value.get(a==null?void 0:a[e.discriminator]);return c?c._zod.run(n,i):e.unionFallback?r(n,i):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,input:a,path:[e.discriminator],inst:t}),n)}}),el=_("$ZodIntersection",(t,e)=>{W.init(t,e),t._zod.parse=(r,o)=>{let n=r.value,i=e.left._zod.run({value:n,issues:[]},o),a=e.right._zod.run({value:n,issues:[]},o);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([u,l])=>ub(r,u,l)):ub(r,i,a)}});function Qm(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Zr(t)&&Zr(e)){let r=Object.keys(e),o=Object.keys(t).filter(i=>r.indexOf(i)!==-1),n={...t,...e};for(let i of o){let a=Qm(t[i],e[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n[i]=a.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<t.length;o++){let n=t[o],i=e[o],a=Qm(n,i);if(!a.valid)return{valid:!1,mergeErr
|
||
|
|
|
||
|
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of t.seen.entries()){let s=d[1];if(e===d[0]){i(d);continue}if(t.external){let p=(u=t.external.registry.get(d[0]))==null?void 0:u.id;if(e!==d[0]&&p){i(d);continue}}if((l=t.metadataRegistry.get(d[0]))==null?void 0:l.id){i(d);continue}if(s.cycle){i(d);continue}if(s.count>1&&t.reused==="ref"){i(d);continue}}}function tn(t,e){var a,c,u,l,d;let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=s=>{var y,w,k;let f=t.seen.get(s);if(f.ref===null)return;let p=(y=f.def)!=null?y:f.schema,m={...p},h=f.ref;if(f.ref=null,h){o(h);let b=t.seen.get(h),x=b.schema;if(x.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(p.allOf=(w=p.allOf)!=null?w:[],p.allOf.push(x)):Object.assign(p,x),Object.assign(p,m),s._zod.parent===h)for(let V in p)V==="$ref"||V==="allOf"||V in m||delete p[V];if(x.$ref)for(let V in p)V==="$ref"||V==="allOf"||V in b.def&&JSON.stringify(p[V])===JSON.stringify(b.def[V])&&delete p[V]}let g=s._zod.parent;if(g&&g!==h){o(g);let b=t.seen.get(g);if(b!=null&&b.schema.$ref&&(p.$ref=b.schema.$ref,b.def))for(let x in p)x==="$ref"||x==="allOf"||x in b.def&&JSON.stringify(p[x])===JSON.stringify(b.def[x])&&delete p[x]}t.override({zodSchema:s,jsonSchema:p,path:(k=f.path)!=null?k:[]})};for(let s of[...t.seen.entries()].reverse())o(s[0]);let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,(a=t.external)!=null&&a.uri){let s=(c=t.external.registry.get(e))==null?void 0:c.id;if(!s)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(s)}Object.assign(n,(u=r.def)!=null?u:r.schema);let i=(d=(l=t.external)==null?void 0:l.defs)!=null?d:{};for(let s of t.seen.entries()){let f=s[1];f.def&&f.defId&&(i[f.defId]=f.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?n.$defs=i:n.definitions=i);try{let s=JSON.parse(JSON.stringify(n));return Object.defineProperty(s,"~standard",{value:{...e["~standard"],jsonSchema:{input:Bo(e,"input",t.processors),output:Bo(e,"output",t.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function ot(t,e){let r=e!=null?e:{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return ot(o.element,r);if(o.type==="set")return ot(o.valueType,r);if(o.type==="lazy")return ot(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return ot(o.innerType,r);if(o.type==="intersection")return ot(o.left,r)||ot(o.right,r);if(o.type==="record"||o.type==="map")return ot(o.keyType,r)||ot(o.valueType,r);if(o.type==="pipe")return ot(o.in,r)||ot(o.out,r);if(o.type==="object"){for(let n in o.shape)if(ot(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(ot(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(ot(n,r))return!0;return!!(o.rest&&ot(o.rest,r))}return!1}var oh=(t,e={})=>r=>{let o=Qr({...r,processors:e});return he(t,o),en(o,t),tn(o,t)},Bo=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o!=null?o:{},a=Qr({...n!=null?n:{},target:i,io:e,processors:r});return he(t,a),en(a,t),tn(a,t)};var KT={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ih=(t,e,r,o)=>{var d;let n=r;n.type="string";let{minimum:i,maximum:a,format:c,patterns:u,contentEncoding:l}=t._zod.bag;if(typeof i=="number"&&(n.minLength=i),typeof a=="number"&&(n.maxLength=a),c&&(n.format=(d=KT[c])!=null?d:c,n.format===""&&delete n.format,c==="time"&&delete n.format),l&&(n.contentEncoding=l),u&&u.size>0){let s=[...u];s.length===1?n.pattern=s[0].source:s.length>1&&(n.allOf=[...s.map(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}
|
||
|
|
]))`;continue}else if(o[l]==="$"){n+=`($|(?=[\r
|
||
|
|
]))`;continue}}if(r.s&&o[l]==="."){n+=a?`${o[l]}\r
|
||
|
|
`:`[${o[l]}\r
|
||
|
|
]`;continue}n+=o[l],o[l]==="\\"?i=!0:a&&o[l]==="]"?a=!1:!a&&o[l]==="["&&(a=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return n}function xf(t,e){var o,n,i,a,c,u,l;if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&((o=t.keyType)==null?void 0:o._def.typeName)===E.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((d,s)=>{var f;return{...d,[s]:(f=H(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]}))!=null?f:Te(e)}},{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:(n=H(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?n:e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(((i=t.keyType)==null?void 0:i._def.typeName)===E.ZodString&&((a=t.keyType._def.checks)!=null&&a.length)){let{type:d,...s}=bf(t.keyType._def,e);return{...r,propertyNames:s}}else{if(((c=t.keyType)==null?void 0:c._def.typeName)===E.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(((u=t.keyType)==null?void 0:u._def.typeName)===E.ZodBranded&&t.keyType._def.type._def.typeName===E.ZodString&&((l=t.keyType._def.type._def.checks)!=null&&l.length)){let{type:d,...s}=$f(t.keyType._def,e);return{...r,propertyNames:s}}}return r}function uw(t,e){if(e.mapStrategy==="record")return xf(t,e);let r=H(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Te(e),o=H(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Te(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function lw(t){let e=t.values,o=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),n=Array.from(new Set(o.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function dw(t){return t.target==="openAi"?void 0:{not:Te({...t,currentPath:[...t.currentPath,"not"]})}}function fw(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Xs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function mw(t,e){if(e.target==="openApi3")return pw(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(o=>o._def.typeName in Xs&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((n,i)=>{let a=Xs[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){let o=r.reduce((n,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(o.length===r.length){let n=o.filter((i,a,c)=>c.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(i=>!o.includes(i))],[])};return pw(t,e)}var pw=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((o,n)=>H(o._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!e.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function hw(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Xs[t.innerType._def.typeName],nullable:!0}:{type:[Xs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=H(t.innerType._def,{...e,currentPath:[...e.currentPath]});return o&&"$ref"in o?{allOf:[o],nullable:
|
||
|
|
`;break;case"id":c=g.includes("\0")?void 0:g;break;case"retry":/^\d+$/.test(g)?o(parseInt(g,10)):r(new mp(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:y}));break;default:r(new mp(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:g,line:y}));break}}function p(){u.length>0&&e({id:c,event:l||void 0,data:u.endsWith(`
|
||
|
|
`)?u.slice(0,-1):u}),c=void 0,u="",l=""}function m(h={}){i&&h.consume&&s(i),a=!0,c=void 0,u="",l="",i=""}return{feed:d,reset:m}}function CC(t){let e=[],r="",o=0;for(;o<t.length;){let n=t.indexOf("\r",o),i=t.indexOf(`
|
||
|
|
`,o),a=-1;if(n!==-1&&i!==-1?a=Math.min(n,i):n!==-1?a=n:i!==-1&&(a=i),a===-1){r=t.slice(o);break}else{let c=t.slice(o,a);e.push(c),o=a+1,t[o-1]==="\r"&&t[o]===`
|
||
|
|
`&&o++}}return[e,r]}var vp=class extends Event{constructor(e,r){var o,n;super(e),this.code=(o=r==null?void 0:r.code)!=null?o:void 0,this.message=(n=r==null?void 0:r.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,o){return o(h0(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(h0(this),r)}};function DC(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Cy(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Cy).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Cy(t.cause)}`:t.message:`${t}`}function h0(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var v0=t=>{throw TypeError(t)},Vy=(t,e,r)=>e.has(t)||v0("Cannot "+r),oe=(t,e,r)=>(Vy(t,e,"read from private field"),r?r.call(t):e.get(t)),Ze=(t,e,r)=>e.has(t)?v0("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Ee=(t,e,r,o)=>(Vy(t,e,"write to private field"),e.set(t,r),r),Tr=(t,e,r)=>(Vy(t,e,"access private method"),r),vt,ro,Oi,gp,_p,Tc,Ni,Ec,vn,ji,Ci,Ri,Ic,Yt,Dy,Uy,Ay,g0,Zy,My,Pc,qy,Ly,no=class extends EventTarget{constructor(e,r){var o,n;super(),Ze(this,Yt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Ze(this,vt),Ze(this,ro),Ze(this,Oi),Ze(this,gp),Ze(this,_p),Ze(this,Tc),Ze(this,Ni),Ze(this,Ec,null),Ze(this,vn),Ze(this,ji),Ze(this,Ci,null),Ze(this,Ri,null),Ze(this,Ic,null),Ze(this,Uy,async i=>{var a;oe(this,ji).reset();let{body:c,redirected:u,status:l,headers:d}=i;if(l===204){Tr(this,Yt,Pc).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Ee(this,Oi,new URL(i.url)):Ee(this,Oi,void 0),l!==200){Tr(this,Yt,Pc).call(this,`Non-200 status code (${l})`,l);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){Tr(this,Yt,Pc).call(this,'Invalid content type, expected "text/event-stream"',l);return}if(oe(this,vt)===this.CLOSED)return;Ee(this,vt,this.OPEN);let s=new Event("open");if((a=oe(this,Ic))==null||a.call(this,s),this.dispatchEvent(s),typeof c!="object"||!c||!("getReader"in c)){Tr(this,Yt,Pc).call(this,"Invalid response body, expected a web ReadableStream",l),this.close();return}let f=new TextDecoder,p=c.getReader(),m=!0;do{let{done:h,value:g}=await p.read();g&&oe(this,ji).feed(f.decode(g,{stream:!h})),h&&(m=!1,oe(this,ji).reset(),Tr(this,Yt,qy).call(this))}while(m)}),Ze(this,Ay,i=>{Ee(this,vn,void 0),!(i.name==="AbortError"||i.type==="aborted")&&Tr(this,Yt,qy).call(this,Cy(i))}),Ze(this,Zy,i=>{typeof i.id=="string"&&Ee(this,Ec,i.id);let a=new MessageEvent(i.event||"message",{data:i.data,origin:oe(this,Oi)?oe(this,Oi).origin:oe(this,ro).origin,lastEventId:i.id||""});oe(this,Ri)&&(!i.event||i.event==="message")&&oe(this,Ri).call(this,a),this.dispatchEvent(a)}),Ze(this,My,i=>{Ee(this,Tc,i)}),Ze(this,Ly,()=>{Ee(this,Ni,void 0),oe(this,vt)===this.CONNECTING&&Tr(this,Yt,Dy).call(this)});try{if(e instanceof URL)Ee(this,ro,e);else if(typeof e=="string")Ee(this,ro,new URL(e,UC()));else throw new Error("Invalid URL")}catch{throw DC("An invalid or illegal string was specified")}Ee(this,ji,hp({onEvent:oe(this,Zy),onRetry:oe(this,My)})),Ee(this,vt,this.CONNECTING),Ee(this,Tc,3e3),Ee(this,_p,(o=r==null?void 0:r.fetch)!=null?o:globalThis.fetch),Ee(this,gp,(n=r==null?void 0:r.withCredentials)!=null?n:!1),Tr(this,Yt,Dy).call(this)}get readyState(){return oe(this,vt)}get url(){return oe(this,ro).href}get withCredentials(){return oe(this,gp)}get onerror(){return oe(this,Ci)}set onerror(e){Ee(this,Ci,e)}get onmessage(){return oe(this,Ri)}set onmessage(e){Ee(this,Ri,e)}get onopen(){return oe(this,Ic)}set onopen(e){Ee(this,Ic,e)}addEventListener(e,r,o){let n=r;super.addEventListener(e,n,o)}removeEventListener(e,r,o){let n=r;super.removeEventListener(e,n,o)}close(){oe(this,Ni)&&clearTimeout(oe(this,Ni)),oe(this,vt)!==this.CLOSED&&(oe(this,vn)&&oe(this,vn).abort(),Ee(this,vt,this.CLOSED),Ee(this,vn,void 0))}};vt=new WeakMap,ro=new WeakMap,Oi=new WeakMap,gp=new WeakMap,_p=new WeakMap,Tc=new WeakMap
|
||
|
|
data: ${o}
|
||
|
|
|
||
|
|
`),this._sseResponse=this.res,this.res.on("close",()=>{var n;this._sseResponse=void 0,(n=this.onclose)==null||n.call(this)})}async handlePostMessage(e,r,o){var u,l,d,s;if(!this._sseResponse){let f="SSE connection not established";throw r.writeHead(500).end(f),new Error(f)}let n=this.validateRequestHeaders(e);if(n){r.writeHead(403).end(n),(u=this.onerror)==null||u.call(this,new Error(n));return}let i=e.auth,a={headers:e.headers},c;try{let f=L0.default.parse((l=e.headers["content-type"])!=null?l:"");if(f.type!=="application/json")throw new Error(`Unsupported content-type: ${f.type}`);c=o!=null?o:await Qy(e,{limit:xD,encoding:(d=f.parameters.charset)!=null?d:"utf-8"})}catch(f){r.writeHead(400).end(String(f)),(s=this.onerror)==null||s.call(this,f);return}try{await this.handleMessage(typeof c=="string"?JSON.parse(c):c,{requestInfo:a,authInfo:i})}catch{r.writeHead(400).end(`Invalid message: ${c}`);return}r.writeHead(202).end("Accepted")}async handleMessage(e,r){var n,i;let o;try{o=kt.parse(e)}catch(a){throw(n=this.onerror)==null||n.call(this,a),a}(i=this.onmessage)==null||i.call(this,o,r)}async close(){var e,r;(e=this._sseResponse)==null||e.end(),this._sseResponse=void 0,(r=this.onclose)==null||r.call(this)}async send(e){if(!this._sseResponse)throw new Error("Not connected");this._sseResponse.write(`event: message
|
||
|
|
data: ${JSON.stringify(e)}
|
||
|
|
|
||
|
|
`)}get sessionId(){return this._sessionId}};var jz=er(Oz(),1),Vc=er(require("node:process"),1),Rz=require("node:stream");var Mi=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
||
|
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),KD(r)}clear(){this._buffer=void 0}};function KD(t){return kt.parse(JSON.parse(t))}function kp(t){return JSON.stringify(t)+`
|
||
|
|
`}var GD=Vc.default.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function XD(){let t={};for(let e of GD){let r=Vc.default.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Sp=class{constructor(e){this._readBuffer=new Mi,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Rz.PassThrough)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{var o,n,i,a,c;this._process=(0,jz.default)(this._serverParams.command,(o=this._serverParams.args)!=null?o:[],{env:{...XD(),...this._serverParams.env},stdio:["pipe","pipe",(n=this._serverParams.stderr)!=null?n:"inherit"],shell:!1,windowsHide:Vc.default.platform==="win32"&&YD(),cwd:this._serverParams.cwd}),this._process.on("error",u=>{var l;r(u),(l=this.onerror)==null||l.call(this,u)}),this._process.on("spawn",()=>{e()}),this._process.on("close",u=>{var l;this._process=void 0,(l=this.onclose)==null||l.call(this)}),(i=this._process.stdin)==null||i.on("error",u=>{var l;(l=this.onerror)==null||l.call(this,u)}),(a=this._process.stdout)==null||a.on("data",u=>{this._readBuffer.append(u),this.processReadBuffer()}),(c=this._process.stdout)==null||c.on("error",u=>{var l;(l=this.onerror)==null||l.call(this,u)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,r;return this._stderrStream?this._stderrStream:(r=(e=this._process)==null?void 0:e.stderr)!=null?r:null}get pid(){var e,r;return(r=(e=this._process)==null?void 0:e.pid)!=null?r:null}processReadBuffer(){var e,r;for(;;)try{let o=this._readBuffer.readMessage();if(o===null)break;(e=this.onmessage)==null||e.call(this,o)}catch(o){(r=this.onerror)==null||r.call(this,o)}}async close(){var e;if(this._process){let r=this._process;this._process=void 0;let o=new Promise(n=>{r.once("close",()=>{n()})});try{(e=r.stdin)==null||e.end()}catch{}if(await Promise.race([o,new Promise(n=>setTimeout(n,2e3).unref())]),r.exitCode===null){try{r.kill("SIGTERM")}catch{}await Promise.race([o,new Promise(n=>setTimeout(n,2e3).unref())])}if(r.exitCode===null)try{r.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{var n;if(!((n=this._process)!=null&&n.stdin))throw new Error("Not connected");let o=kp(e);this._process.stdin.write(o)?r():this._process.stdin.once("drain",r)})}};function YD(){return"type"in Vc.default}var l$=er(require("node:process"),1);var zp=class{constructor(e=l$.default.stdin,r=l$.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Mi,this._started=!1,this._ondata=o=>{this._readBuffer.append(o),this.processReadBuffer()},this._onerror=o=>{var n;(n=this.onerror)==null||n.call(this,o)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){var e,r;for(;;)try{let o=this._readBuffer.readMessage();if(o===null)break;(e=this.onmessage)==null||e.call(this,o)}catch(o){(r=this.onerror)==null||r.call(this,o)}}async close(){var r;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(r=this.onclose)==null||r.call(this)}send(e){return new Promise(r=>{let o=kp(e);this._stdout.write(o)?r():this._stdout.once("drain",r)})}};var Nz=require("http2"),Pp=require("http2"),p$=require("stream"),Az=er(require("crypto"),1);var co=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},QD=t=>t instanceof co?t:new co(t.message,{cause:t}),eU=global.Request,Fc=class extends eU{constructor(t,e){var r,o;typeof t=="object"&&Vi in t&&(t=t[Vi]()),typeof((r=e==null?void 0:e.bod
|
||
|
|
data:
|
||
|
|
|
||
|
|
`;this._retryInterval!==void 0&&(a=`id: ${i}
|
||
|
|
retry: ${this._retryInterval}
|
||
|
|
data:
|
||
|
|
|
||
|
|
`),e.enqueue(r.encode(a))}async handleGetRequest(e){let r=e.headers.get("accept");if(!(r!=null&&r.includes("text/event-stream")))return this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept text/event-stream");let o=this.validateSession(e);if(o)return o;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let l=e.headers.get("last-event-id");if(l)return this.replayEvents(l)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.createJsonErrorResponse(409,-32e3,"Conflict: Only one SSE stream is allowed per session");let i=new TextEncoder,a,c=new ReadableStream({start:l=>{a=l},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),u={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};return this.sessionId!==void 0&&(u["mcp-session-id"]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:a,encoder:i,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{a.close()}catch{}}}),new Response(c,{headers:u})}async replayEvents(e){var r;if(!this._eventStore)return this.createJsonErrorResponse(400,-32e3,"Event store not configured");try{let o;if(this._eventStore.getStreamIdForEventId){if(o=await this._eventStore.getStreamIdForEventId(e),!o)return this.createJsonErrorResponse(400,-32e3,"Invalid event ID format");if(this._streamMapping.get(o)!==void 0)return this.createJsonErrorResponse(409,-32e3,"Conflict: Stream already has an active connection")}let n={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};this.sessionId!==void 0&&(n["mcp-session-id"]=this.sessionId);let i=new TextEncoder,a,c=new ReadableStream({start:l=>{a=l},cancel:()=>{}}),u=await this._eventStore.replayEventsAfter(e,{send:async(l,d)=>{var f;if(!this.writeSSEEvent(a,i,d,l)){(f=this.onerror)==null||f.call(this,new Error("Failed replay events"));try{a.close()}catch{}}}});return this._streamMapping.set(u,{controller:a,encoder:i,cleanup:()=>{this._streamMapping.delete(u);try{a.close()}catch{}}}),new Response(c,{headers:n})}catch(o){return(r=this.onerror)==null||r.call(this,o),this.createJsonErrorResponse(500,-32e3,"Error replaying events")}}writeSSEEvent(e,r,o,n){try{let i=`event: message
|
||
|
|
`;return n&&(i+=`id: ${n}
|
||
|
|
`),i+=`data: ${JSON.stringify(o)}
|
||
|
|
|
||
|
|
`,e.enqueue(r.encode(i)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,r){var o,n,i,a,c;try{let u=e.headers.get("accept");if(!(u!=null&&u.includes("application/json"))||!u.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let l=e.headers.get("content-type");if(!l||!l.includes("application/json"))return this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let d={headers:Object.fromEntries(e.headers.entries())},s;if((r==null?void 0:r.parsedBody)!==void 0)s=r.parsedBody;else try{s=await e.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let f;try{Array.isArray(s)?f=s.map(D=>kt.parse(D)):f=[kt.parse(s)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let p=f.some(dv);if(p){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(f.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=(o=this.sessionIdGenerator)==null?void 0:o.call(this),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!p){let D=this.validateSession(e);if(D)return D;let V=this.validateProtocolVersion(e);if(V)return V}if(!f.some(ar)){for(let D of f)(n=this.onmessage)==null||n.call(this,D,{authInfo:r==null?void 0:r.authInfo,requestInfo:d});return new Response(null,{status:202})}let h=crypto.randomUUID(),g=f.find(D=>dv(D)),y=g?g.params.protocolVersion:(i=e.headers.get("mcp-protocol-version"))!=null?i:Rx;if(this._enableJsonResponse)return new Promise(D=>{var V;this._streamMapping.set(h,{resolveJson:D,cleanup:()=>{this._streamMapping.delete(h)}});for(let K of f)ar(K)&&this._requestToStreamMapping.set(K.id,h);for(let K of f)(V=this.onmessage)==null||V.call(this,K,{authInfo:r==null?void 0:r.authInfo,requestInfo:d})});let w=new TextEncoder,k,b=new ReadableStream({start:D=>{k=D},cancel:()=>{this._streamMapping.delete(h)}}),x={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(x["mcp-session-id"]=this.sessionId);for(let D of f)ar(D)&&(this._streamMapping.set(h,{controller:k,encoder:w,cleanup:()=>{this._streamMapping.delete(h);try{k.close()}catch{}}}),this._requestToStreamMapping.set(D.id,h));await this.writePrimingEvent(k,w,h,y);for(let D of f){let V,K;ar(D)&&this._eventStore&&y>="2025-11-25"&&(V=()=>{this.closeSSEStream(D.id)},K=()=>{this.closeStandaloneSSEStream()}),(a=this.onmessage)==null||a.call(this,D,{authInfo:r==null?void 0:r.authInfo,requestInfo:d,closeSSEStream:V,closeStandaloneSSEStream:K})}return new Response(b,{status:200,headers:x})}catch(u){return(c=this.onerror)==null||c.call(this,u),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(u)})}}async handleDeleteRequest(e){var n;let r=this.validateSession(e);if(r)return r;let o=this.validateProtocolVersion(e);return o||(await Promise.resolve((n=this._onsessionclosed)==null?void 0:n.call(this,this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=e.headers.get("mcp-session-id");if(!r)return this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(e){let r=e.headers.get("mcp-protocol-version");if(r!==null&&!Jn.includes(r))return this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol v
|
||
|
|
/*! Bundled license information:
|
||
|
|
|
||
|
|
bytes/index.js:
|
||
|
|
(*!
|
||
|
|
* bytes
|
||
|
|
* Copyright(c) 2012-2014 TJ Holowaychuk
|
||
|
|
* Copyright(c) 2015 Jed Watson
|
||
|
|
* MIT Licensed
|
||
|
|
*)
|
||
|
|
|
||
|
|
content-type/index.js:
|
||
|
|
(*!
|
||
|
|
* content-type
|
||
|
|
* Copyright(c) 2015 Douglas Christopher Wilson
|
||
|
|
* MIT Licensed
|
||
|
|
*)
|
||
|
|
*/
|