@swifty.js/swifty 0.0.24 → 0.0.26
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/{agent-24XMR2WX.js → agent-GAABBZRW.js} +1 -1
- package/dist/{chunk-FAJYJI6T.js → chunk-RMMK4PO5.js} +3 -3
- package/dist/{chunk-VQUWSKQQ.js → chunk-VC6OXOMP.js} +11 -11
- package/dist/lib/{agent-U42LS73D.js → agent-U7MIUCKT.js} +1 -1
- package/dist/lib/{chunk-XG6NELJH.js → chunk-RKJYTYQM.js} +10 -2
- package/dist/lib/index.js +9 -3
- package/dist/main.js +134 -134
- package/dist/{server-NJ2NXAOI.js → server-P2VE5HLJ.js} +2 -2
- package/package.json +5 -6
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
3
|
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{i as a}from"./chunk-
|
|
4
|
+
import{i as a}from"./chunk-VC6OXOMP.js";import"./chunk-MWZIARZE.js";import"./chunk-FZPTNGTU.js";import"./chunk-SIWLMWHH.js";import"./chunk-X3UA5OZL.js";export{a as Agent};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
3
|
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{b as Gl,i as fo}from"./chunk-VQUWSKQQ.js";import{a as er,b as mo}from"./chunk-MWZIARZE.js";import{a as Ue,b as xl,c as uo,d as Ao}from"./chunk-W37Y53LX.js";import{e as Hl,f as tr}from"./chunk-NR62AA5K.js";import{a as Ll}from"./chunk-QN27QEFS.js";import{a as We}from"./chunk-7MHXMDYC.js";import{A as zl,B as Ul,C as $,D as C,I as R,J as Fl,K as Ol,L as Gr,N as O,P as tt,Q as Hr,R as S,S as po,a as bl,d as Tl,e as Se,f as Rl,g as Dl,h as A,i as $l,j as J,k as K,l as Pl,m as jl,n as ne,o as _,p as k,q as le,r as re,s as ei,t as ti,u as X,v as Te,w as b,x as oe,y as Nl,z as ri}from"./chunk-SIWLMWHH.js";import{a as go,b as Yl,c as Jl,f as Wl}from"./chunk-A2VR3BC4.js";import{a as ql}from"./chunk-E55KH72M.js";import{a as ft,b as Q,d as lo}from"./chunk-X3UA5OZL.js";var os=Q(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.regexpCode=W.getEsmExportName=W.getProperty=W.safeStringify=W.stringify=W.strConcat=W.addCodeArg=W.str=W._=W.nil=W._Code=W.Name=W.IDENTIFIER=W._CodeOrName=void 0;var rs=class{};W._CodeOrName=rs;W.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Rt=class extends rs{constructor(e){if(super(),!W.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}}};W.Name=Rt;var Pe=class extends rs{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,s)=>`${r}${s}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,s)=>(s instanceof Rt&&(r[s.str]=(r[s.str]||0)+1),r),{})}};W._Code=Pe;W.nil=new Pe("");function hu(t,...e){let r=[t[0]],s=0;for(;s<e.length;)Ri(r,e[s]),r.push(t[++s]);return new Pe(r)}W._=hu;var Ti=new Pe("+");function Eu(t,...e){let r=[ss(t[0])],s=0;for(;s<e.length;)r.push(Ti),Ri(r,e[s]),r.push(Ti,ss(t[++s]));return hE(r),new Pe(r)}W.str=Eu;function Ri(t,e){e instanceof Pe?t.push(...e._items):e instanceof Rt?t.push(e):t.push(wE(e))}W.addCodeArg=Ri;function hE(t){let e=1;for(;e<t.length-1;){if(t[e]===Ti){let r=EE(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function EE(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Rt||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 Rt))return`"${t}${e.slice(1)}`}function yE(t,e){return e.emptyStr()?t:t.emptyStr()?e:Eu`${t}${e}`}W.strConcat=yE;function wE(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ss(Array.isArray(t)?t.join(","):t)}function CE(t){return new Pe(ss(t))}W.stringify=CE;function ss(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}W.safeStringify=ss;function IE(t){return typeof t=="string"&&W.IDENTIFIER.test(t)?new Pe(`.${t}`):hu`[${t}]`}W.getProperty=IE;function BE(t){if(typeof t=="string"&&W.IDENTIFIER.test(t))return new Pe(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}W.getEsmExportName=BE;function QE(t){return new Pe(t.toString())}W.regexpCode=QE});var Pi=Q(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.ValueScope=Me.ValueScopeName=Me.Scope=Me.varKinds=Me.UsedValueState=void 0;var ke=os(),Di=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},bo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(bo||(Me.UsedValueState=bo={}));Me.varKinds={const:new ke.Name("const"),let:new ke.Name("let"),var:new ke.Name("var")};var xo=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof ke.Name?e:this.name(e)}name(e){return new ke.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,s;if(!((s=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||s===void 0)&&s.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Me.Scope=xo;var To=class extends ke.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:s}){this.value=e,this.scopePath=(0,ke._)`.${new ke.Name(r)}[${s}]`}};Me.ValueScopeName=To;var _E=(0,ke._)`\n`,$i=class extends xo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?_E:ke.nil}}get(){return this._scope}name(e){return new To(e,this._newName(e))}value(e,r){var s;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:n}=o,i=(s=r.key)!==null&&s!==void 0?s:r.ref,a=this._values[n];if(a){let l=a.get(i);if(l)return l}else a=this._values[n]=new Map;a.set(i,o);let c=this._scope[n]||(this._scope[n]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:n,itemIndex:u}),o}getValue(e,r){let s=this._values[e];if(s)return s.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,s=>{if(s.scopePath===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return(0,ke._)`${e}${s.scopePath}`})}scopeCode(e=this._values,r,s){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,s)}_reduceValues(e,r,s={},o){let n=ke.nil;for(let i in e){let a=e[i];if(!a)continue;let c=s[i]=s[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,bo.Started);let l=r(u);if(l){let d=this.opts.es5?Me.varKinds.var:Me.varKinds.const;n=(0,ke._)`${n}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))n=(0,ke._)`${n}${l}${this.opts._n}`;else throw new Di(u);c.set(u,bo.Completed)})}return n}};Me.ValueScope=$i});var U=Q(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.or=F.and=F.not=F.CodeGen=F.operators=F.varKinds=F.ValueScopeName=F.ValueScope=F.Scope=F.Name=F.regexpCode=F.stringify=F.getProperty=F.nil=F.strConcat=F.str=F._=void 0;var G=os(),Fe=Pi(),yt=os();Object.defineProperty(F,"_",{enumerable:!0,get:function(){return yt._}});Object.defineProperty(F,"str",{enumerable:!0,get:function(){return yt.str}});Object.defineProperty(F,"strConcat",{enumerable:!0,get:function(){return yt.strConcat}});Object.defineProperty(F,"nil",{enumerable:!0,get:function(){return yt.nil}});Object.defineProperty(F,"getProperty",{enumerable:!0,get:function(){return yt.getProperty}});Object.defineProperty(F,"stringify",{enumerable:!0,get:function(){return yt.stringify}});Object.defineProperty(F,"regexpCode",{enumerable:!0,get:function(){return yt.regexpCode}});Object.defineProperty(F,"Name",{enumerable:!0,get:function(){return yt.Name}});var Po=Pi();Object.defineProperty(F,"Scope",{enumerable:!0,get:function(){return Po.Scope}});Object.defineProperty(F,"ValueScope",{enumerable:!0,get:function(){return Po.ValueScope}});Object.defineProperty(F,"ValueScopeName",{enumerable:!0,get:function(){return Po.ValueScopeName}});Object.defineProperty(F,"varKinds",{enumerable:!0,get:function(){return Po.varKinds}});F.operators={GT:new G._Code(">"),GTE:new G._Code(">="),LT:new G._Code("<"),LTE:new G._Code("<="),EQ:new G._Code("==="),NEQ:new G._Code("!=="),NOT:new G._Code("!"),OR:new G._Code("||"),AND:new G._Code("&&"),ADD:new G._Code("+")};var st=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ji=class extends st{constructor(e,r,s){super(),this.varKind=e,this.name=r,this.rhs=s}render({es5:e,_n:r}){let s=e?Fe.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${s} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=ar(this.rhs,e,r)),this}get names(){return this.rhs instanceof G._CodeOrName?this.rhs.names:{}}},Ro=class extends st{constructor(e,r,s){super(),this.lhs=e,this.rhs=r,this.sideEffects=s}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof G.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ar(this.rhs,e,r),this}get names(){let e=this.lhs instanceof G.Name?{}:{...this.lhs.names};return $o(e,this.rhs)}},Ni=class extends Ro{constructor(e,r,s,o){super(e,s,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},zi=class extends st{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ui=class extends st{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Fi=class extends st{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Oi=class extends st{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=ar(this.code,e,r),this}get names(){return this.code instanceof G._CodeOrName?this.code.names:{}}},ns=class extends st{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,s)=>r+s.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let s=e[r].optimizeNodes();Array.isArray(s)?e.splice(r,1,...s):s?e[r]=s:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:s}=this,o=s.length;for(;o--;){let n=s[o];n.optimizeNames(e,r)||(SE(e,n.names),s.splice(o,1))}return s.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Pt(e,r.names),{})}},ot=class extends ns{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Li=class extends ns{},ir=class extends ot{};ir.kind="else";var Dt=class t extends ot{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let s=r.optimizeNodes();r=this.else=Array.isArray(s)?new ir(s):s}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(yu(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var s;if(this.else=(s=this.else)===null||s===void 0?void 0:s.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=ar(this.condition,e,r),this}get names(){let e=super.names;return $o(e,this.condition),this.else&&Pt(e,this.else.names),e}};Dt.kind="if";var $t=class extends ot{};$t.kind="for";var qi=class extends $t{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=ar(this.iteration,e,r),this}get names(){return Pt(super.names,this.iteration.names)}},Gi=class extends $t{constructor(e,r,s,o){super(),this.varKind=e,this.name=r,this.from=s,this.to=o}render(e){let r=e.es5?Fe.varKinds.var:this.varKind,{name:s,from:o,to:n}=this;return`for(${r} ${s}=${o}; ${s}<${n}; ${s}++)`+super.render(e)}get names(){let e=$o(super.names,this.from);return $o(e,this.to)}},Do=class extends $t{constructor(e,r,s,o){super(),this.loop=e,this.varKind=r,this.name=s,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=ar(this.iterable,e,r),this}get names(){return Pt(super.names,this.iterable.names)}},is=class extends ot{constructor(e,r,s){super(),this.name=e,this.args=r,this.async=s}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};is.kind="func";var as=class extends ns{render(e){return"return "+super.render(e)}};as.kind="return";var Hi=class extends ot{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var s,o;return super.optimizeNames(e,r),(s=this.catch)===null||s===void 0||s.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Pt(e,this.catch.names),this.finally&&Pt(e,this.finally.names),e}},cs=class extends ot{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};cs.kind="catch";var ls=class extends ot{render(e){return"finally"+super.render(e)}};ls.kind="finally";var Yi=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
4
|
+
import{b as Gl,i as fo}from"./chunk-VC6OXOMP.js";import{a as er,b as mo}from"./chunk-MWZIARZE.js";import{a as Ue,b as xl,c as uo,d as Ao}from"./chunk-W37Y53LX.js";import{e as Hl,f as tr}from"./chunk-NR62AA5K.js";import{a as Ll}from"./chunk-QN27QEFS.js";import{a as We}from"./chunk-7MHXMDYC.js";import{A as zl,B as Ul,C as $,D as C,I as R,J as Fl,K as Ol,L as Gr,N as O,P as tt,Q as Hr,R as S,S as po,a as bl,d as Tl,e as Se,f as Rl,g as Dl,h as A,i as $l,j as J,k as K,l as Pl,m as jl,n as ne,o as _,p as k,q as le,r as re,s as ei,t as ti,u as X,v as Te,w as b,x as oe,y as Nl,z as ri}from"./chunk-SIWLMWHH.js";import{a as go,b as Yl,c as Jl,f as Wl}from"./chunk-A2VR3BC4.js";import{a as ql}from"./chunk-E55KH72M.js";import{a as ft,b as Q,d as lo}from"./chunk-X3UA5OZL.js";var os=Q(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.regexpCode=W.getEsmExportName=W.getProperty=W.safeStringify=W.stringify=W.strConcat=W.addCodeArg=W.str=W._=W.nil=W._Code=W.Name=W.IDENTIFIER=W._CodeOrName=void 0;var rs=class{};W._CodeOrName=rs;W.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Rt=class extends rs{constructor(e){if(super(),!W.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}}};W.Name=Rt;var Pe=class extends rs{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,s)=>`${r}${s}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,s)=>(s instanceof Rt&&(r[s.str]=(r[s.str]||0)+1),r),{})}};W._Code=Pe;W.nil=new Pe("");function hu(t,...e){let r=[t[0]],s=0;for(;s<e.length;)Ri(r,e[s]),r.push(t[++s]);return new Pe(r)}W._=hu;var Ti=new Pe("+");function Eu(t,...e){let r=[ss(t[0])],s=0;for(;s<e.length;)r.push(Ti),Ri(r,e[s]),r.push(Ti,ss(t[++s]));return hE(r),new Pe(r)}W.str=Eu;function Ri(t,e){e instanceof Pe?t.push(...e._items):e instanceof Rt?t.push(e):t.push(wE(e))}W.addCodeArg=Ri;function hE(t){let e=1;for(;e<t.length-1;){if(t[e]===Ti){let r=EE(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function EE(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Rt||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 Rt))return`"${t}${e.slice(1)}`}function yE(t,e){return e.emptyStr()?t:t.emptyStr()?e:Eu`${t}${e}`}W.strConcat=yE;function wE(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ss(Array.isArray(t)?t.join(","):t)}function CE(t){return new Pe(ss(t))}W.stringify=CE;function ss(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}W.safeStringify=ss;function IE(t){return typeof t=="string"&&W.IDENTIFIER.test(t)?new Pe(`.${t}`):hu`[${t}]`}W.getProperty=IE;function BE(t){if(typeof t=="string"&&W.IDENTIFIER.test(t))return new Pe(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}W.getEsmExportName=BE;function QE(t){return new Pe(t.toString())}W.regexpCode=QE});var Pi=Q(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.ValueScope=Me.ValueScopeName=Me.Scope=Me.varKinds=Me.UsedValueState=void 0;var ke=os(),Di=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},bo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(bo||(Me.UsedValueState=bo={}));Me.varKinds={const:new ke.Name("const"),let:new ke.Name("let"),var:new ke.Name("var")};var xo=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof ke.Name?e:this.name(e)}name(e){return new ke.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,s;if(!((s=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||s===void 0)&&s.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Me.Scope=xo;var To=class extends ke.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:s}){this.value=e,this.scopePath=(0,ke._)`.${new ke.Name(r)}[${s}]`}};Me.ValueScopeName=To;var _E=(0,ke._)`\n`,$i=class extends xo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?_E:ke.nil}}get(){return this._scope}name(e){return new To(e,this._newName(e))}value(e,r){var s;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:n}=o,i=(s=r.key)!==null&&s!==void 0?s:r.ref,a=this._values[n];if(a){let l=a.get(i);if(l)return l}else a=this._values[n]=new Map;a.set(i,o);let c=this._scope[n]||(this._scope[n]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:n,itemIndex:u}),o}getValue(e,r){let s=this._values[e];if(s)return s.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,s=>{if(s.scopePath===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return(0,ke._)`${e}${s.scopePath}`})}scopeCode(e=this._values,r,s){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,s)}_reduceValues(e,r,s={},o){let n=ke.nil;for(let i in e){let a=e[i];if(!a)continue;let c=s[i]=s[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,bo.Started);let l=r(u);if(l){let d=this.opts.es5?Me.varKinds.var:Me.varKinds.const;n=(0,ke._)`${n}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))n=(0,ke._)`${n}${l}${this.opts._n}`;else throw new Di(u);c.set(u,bo.Completed)})}return n}};Me.ValueScope=$i});var U=Q(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.or=F.and=F.not=F.CodeGen=F.operators=F.varKinds=F.ValueScopeName=F.ValueScope=F.Scope=F.Name=F.regexpCode=F.stringify=F.getProperty=F.nil=F.strConcat=F.str=F._=void 0;var G=os(),Fe=Pi(),yt=os();Object.defineProperty(F,"_",{enumerable:!0,get:function(){return yt._}});Object.defineProperty(F,"str",{enumerable:!0,get:function(){return yt.str}});Object.defineProperty(F,"strConcat",{enumerable:!0,get:function(){return yt.strConcat}});Object.defineProperty(F,"nil",{enumerable:!0,get:function(){return yt.nil}});Object.defineProperty(F,"getProperty",{enumerable:!0,get:function(){return yt.getProperty}});Object.defineProperty(F,"stringify",{enumerable:!0,get:function(){return yt.stringify}});Object.defineProperty(F,"regexpCode",{enumerable:!0,get:function(){return yt.regexpCode}});Object.defineProperty(F,"Name",{enumerable:!0,get:function(){return yt.Name}});var Po=Pi();Object.defineProperty(F,"Scope",{enumerable:!0,get:function(){return Po.Scope}});Object.defineProperty(F,"ValueScope",{enumerable:!0,get:function(){return Po.ValueScope}});Object.defineProperty(F,"ValueScopeName",{enumerable:!0,get:function(){return Po.ValueScopeName}});Object.defineProperty(F,"varKinds",{enumerable:!0,get:function(){return Po.varKinds}});F.operators={GT:new G._Code(">"),GTE:new G._Code(">="),LT:new G._Code("<"),LTE:new G._Code("<="),EQ:new G._Code("==="),NEQ:new G._Code("!=="),NOT:new G._Code("!"),OR:new G._Code("||"),AND:new G._Code("&&"),ADD:new G._Code("+")};var st=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ji=class extends st{constructor(e,r,s){super(),this.varKind=e,this.name=r,this.rhs=s}render({es5:e,_n:r}){let s=e?Fe.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${s} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=ar(this.rhs,e,r)),this}get names(){return this.rhs instanceof G._CodeOrName?this.rhs.names:{}}},Ro=class extends st{constructor(e,r,s){super(),this.lhs=e,this.rhs=r,this.sideEffects=s}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof G.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ar(this.rhs,e,r),this}get names(){let e=this.lhs instanceof G.Name?{}:{...this.lhs.names};return $o(e,this.rhs)}},Ni=class extends Ro{constructor(e,r,s,o){super(e,s,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},zi=class extends st{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ui=class extends st{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Fi=class extends st{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Oi=class extends st{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=ar(this.code,e,r),this}get names(){return this.code instanceof G._CodeOrName?this.code.names:{}}},ns=class extends st{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,s)=>r+s.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let s=e[r].optimizeNodes();Array.isArray(s)?e.splice(r,1,...s):s?e[r]=s:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:s}=this,o=s.length;for(;o--;){let n=s[o];n.optimizeNames(e,r)||(SE(e,n.names),s.splice(o,1))}return s.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Pt(e,r.names),{})}},ot=class extends ns{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Li=class extends ns{},ir=class extends ot{};ir.kind="else";var Dt=class t extends ot{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let s=r.optimizeNodes();r=this.else=Array.isArray(s)?new ir(s):s}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(yu(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var s;if(this.else=(s=this.else)===null||s===void 0?void 0:s.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=ar(this.condition,e,r),this}get names(){let e=super.names;return $o(e,this.condition),this.else&&Pt(e,this.else.names),e}};Dt.kind="if";var $t=class extends ot{};$t.kind="for";var qi=class extends $t{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=ar(this.iteration,e,r),this}get names(){return Pt(super.names,this.iteration.names)}},Gi=class extends $t{constructor(e,r,s,o){super(),this.varKind=e,this.name=r,this.from=s,this.to=o}render(e){let r=e.es5?Fe.varKinds.var:this.varKind,{name:s,from:o,to:n}=this;return`for(${r} ${s}=${o}; ${s}<${n}; ${s}++)`+super.render(e)}get names(){let e=$o(super.names,this.from);return $o(e,this.to)}},Do=class extends $t{constructor(e,r,s,o){super(),this.loop=e,this.varKind=r,this.name=s,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=ar(this.iterable,e,r),this}get names(){return Pt(super.names,this.iterable.names)}},is=class extends ot{constructor(e,r,s){super(),this.name=e,this.args=r,this.async=s}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};is.kind="func";var as=class extends ns{render(e){return"return "+super.render(e)}};as.kind="return";var Hi=class extends ot{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var s,o;return super.optimizeNames(e,r),(s=this.catch)===null||s===void 0||s.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Pt(e,this.catch.names),this.finally&&Pt(e,this.finally.names),e}},cs=class extends ot{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};cs.kind="catch";var ls=class extends ot{render(e){return"finally"+super.render(e)}};ls.kind="finally";var Yi=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
5
5
|
`:""},this._extScope=e,this._scope=new Fe.Scope({parent:e}),this._nodes=[new Li]}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 s=this._extScope.value(e,r);return(this._values[s.prefix]||(this._values[s.prefix]=new Set)).add(s),s}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,s,o){let n=this._scope.toName(r);return s!==void 0&&o&&(this._constants[n.str]=s),this._leafNode(new ji(e,n,s)),n}const(e,r,s){return this._def(Fe.varKinds.const,e,r,s)}let(e,r,s){return this._def(Fe.varKinds.let,e,r,s)}var(e,r,s){return this._def(Fe.varKinds.var,e,r,s)}assign(e,r,s){return this._leafNode(new Ro(e,r,s))}add(e,r){return this._leafNode(new Ni(e,F.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==G.nil&&this._leafNode(new Oi(e)),this}object(...e){let r=["{"];for(let[s,o]of e)r.length>1&&r.push(","),r.push(s),(s!==o||this.opts.es5)&&(r.push(":"),(0,G.addCodeArg)(r,o));return r.push("}"),new G._Code(r)}if(e,r,s){if(this._blockNode(new Dt(e)),r&&s)this.code(r).else().code(s).endIf();else if(r)this.code(r).endIf();else if(s)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Dt(e))}else(){return this._elseNode(new ir)}endIf(){return this._endBlockNode(Dt,ir)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new qi(e),r)}forRange(e,r,s,o,n=this.opts.es5?Fe.varKinds.var:Fe.varKinds.let){let i=this._scope.toName(e);return this._for(new Gi(n,i,r,s),()=>o(i))}forOf(e,r,s,o=Fe.varKinds.const){let n=this._scope.toName(e);if(this.opts.es5){let i=r instanceof G.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,G._)`${i}.length`,a=>{this.var(n,(0,G._)`${i}[${a}]`),s(n)})}return this._for(new Do("of",o,n,r),()=>s(n))}forIn(e,r,s,o=this.opts.es5?Fe.varKinds.var:Fe.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,G._)`Object.keys(${r})`,s);let n=this._scope.toName(e);return this._for(new Do("in",o,n,r),()=>s(n))}endFor(){return this._endBlockNode($t)}label(e){return this._leafNode(new zi(e))}break(e){return this._leafNode(new Ui(e))}return(e){let r=new as;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(as)}try(e,r,s){if(!r&&!s)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Hi;if(this._blockNode(o),this.code(e),r){let n=this.name("e");this._currNode=o.catch=new cs(n),r(n)}return s&&(this._currNode=o.finally=new ls,this.code(s)),this._endBlockNode(cs,ls)}throw(e){return this._leafNode(new Fi(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 s=this._nodes.length-r;if(s<0||e!==void 0&&s!==e)throw new Error(`CodeGen: wrong number of nodes: ${s} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=G.nil,s,o){return this._blockNode(new is(e,r,s)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(is)}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 s=this._currNode;if(s instanceof e||r&&s 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 Dt))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}};F.CodeGen=Yi;function Pt(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function $o(t,e){return e instanceof G._CodeOrName?Pt(t,e.names):t}function ar(t,e,r){if(t instanceof G.Name)return s(t);if(!o(t))return t;return new G._Code(t._items.reduce((n,i)=>(i instanceof G.Name&&(i=s(i)),i instanceof G._Code?n.push(...i._items):n.push(i),n),[]));function s(n){let i=r[n.str];return i===void 0||e[n.str]!==1?n:(delete e[n.str],i)}function o(n){return n instanceof G._Code&&n._items.some(i=>i instanceof G.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function SE(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function yu(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,G._)`!${Ji(t)}`}F.not=yu;var kE=wu(F.operators.AND);function ME(...t){return t.reduce(kE)}F.and=ME;var vE=wu(F.operators.OR);function bE(...t){return t.reduce(vE)}F.or=bE;function wu(t){return(e,r)=>e===G.nil?r:r===G.nil?e:(0,G._)`${Ji(e)} ${t} ${Ji(r)}`}function Ji(t){return t instanceof G.Name?t:(0,G._)`(${t})`}});var H=Q(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.checkStrictMode=L.getErrorPath=L.Type=L.useFunc=L.setEvaluated=L.evaluatedPropsToName=L.mergeEvaluated=L.eachItem=L.unescapeJsonPointer=L.escapeJsonPointer=L.escapeFragment=L.unescapeFragment=L.schemaRefOrVal=L.schemaHasRulesButRef=L.schemaHasRules=L.checkUnknownRules=L.alwaysValidSchema=L.toHash=void 0;var Z=U(),xE=os();function TE(t){let e={};for(let r of t)e[r]=!0;return e}L.toHash=TE;function RE(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Bu(t,e),!Qu(e,t.self.RULES.all))}L.alwaysValidSchema=RE;function Bu(t,e=t.schema){let{opts:r,self:s}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=s.RULES.keywords;for(let n in e)o[n]||ku(t,`unknown keyword: "${n}"`)}L.checkUnknownRules=Bu;function Qu(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}L.schemaHasRules=Qu;function DE(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}L.schemaHasRulesButRef=DE;function $E({topSchemaRef:t,schemaPath:e},r,s,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Z._)`${r}`}return(0,Z._)`${t}${e}${(0,Z.getProperty)(s)}`}L.schemaRefOrVal=$E;function PE(t){return _u(decodeURIComponent(t))}L.unescapeFragment=PE;function jE(t){return encodeURIComponent(Vi(t))}L.escapeFragment=jE;function Vi(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}L.escapeJsonPointer=Vi;function _u(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}L.unescapeJsonPointer=_u;function NE(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}L.eachItem=NE;function Cu({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:s}){return(o,n,i,a)=>{let c=i===void 0?n:i instanceof Z.Name?(n instanceof Z.Name?t(o,n,i):e(o,n,i),i):n instanceof Z.Name?(e(o,i,n),n):r(n,i);return a===Z.Name&&!(c instanceof Z.Name)?s(o,c):c}}L.mergeEvaluated={props:Cu({mergeNames:(t,e,r)=>t.if((0,Z._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Z._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Z._)`${r} || {}`).code((0,Z._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Z._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Z._)`${r} || {}`),Ki(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Su}),items:Cu({mergeNames:(t,e,r)=>t.if((0,Z._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Z._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Z._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Z._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Su(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Z._)`{}`);return e!==void 0&&Ki(t,r,e),r}L.evaluatedPropsToName=Su;function Ki(t,e,r){Object.keys(r).forEach(s=>t.assign((0,Z._)`${e}${(0,Z.getProperty)(s)}`,!0))}L.setEvaluated=Ki;var Iu={};function zE(t,e){return t.scopeValue("func",{ref:e,code:Iu[e.code]||(Iu[e.code]=new xE._Code(e.code))})}L.useFunc=zE;var Wi;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Wi||(L.Type=Wi={}));function UE(t,e,r){if(t instanceof Z.Name){let s=e===Wi.Num;return r?s?(0,Z._)`"[" + ${t} + "]"`:(0,Z._)`"['" + ${t} + "']"`:s?(0,Z._)`"/" + ${t}`:(0,Z._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Z.getProperty)(t).toString():"/"+Vi(t)}L.getErrorPath=UE;function ku(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}L.checkStrictMode=ku});var nt=Q(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});var ye=U(),FE={data:new ye.Name("data"),valCxt:new ye.Name("valCxt"),instancePath:new ye.Name("instancePath"),parentData:new ye.Name("parentData"),parentDataProperty:new ye.Name("parentDataProperty"),rootData:new ye.Name("rootData"),dynamicAnchors:new ye.Name("dynamicAnchors"),vErrors:new ye.Name("vErrors"),errors:new ye.Name("errors"),this:new ye.Name("this"),self:new ye.Name("self"),scope:new ye.Name("scope"),json:new ye.Name("json"),jsonPos:new ye.Name("jsonPos"),jsonLen:new ye.Name("jsonLen"),jsonPart:new ye.Name("jsonPart")};Zi.default=FE});var us=Q(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.extendErrors=we.resetErrorsCount=we.reportExtraError=we.reportError=we.keyword$DataError=we.keywordError=void 0;var Y=U(),jo=H(),Be=nt();we.keywordError={message:({keyword:t})=>(0,Y.str)`must pass "${t}" keyword validation`};we.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Y.str)`"${t}" keyword must be ${e} ($data)`:(0,Y.str)`"${t}" keyword is invalid ($data)`};function OE(t,e=we.keywordError,r,s){let{it:o}=t,{gen:n,compositeRule:i,allErrors:a}=o,c=bu(t,e,r);s??(i||a)?Mu(n,c):vu(o,(0,Y._)`[${c}]`)}we.reportError=OE;function LE(t,e=we.keywordError,r){let{it:s}=t,{gen:o,compositeRule:n,allErrors:i}=s,a=bu(t,e,r);Mu(o,a),n||i||vu(s,Be.default.vErrors)}we.reportExtraError=LE;function qE(t,e){t.assign(Be.default.errors,e),t.if((0,Y._)`${Be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Y._)`${Be.default.vErrors}.length`,e),()=>t.assign(Be.default.vErrors,null)))}we.resetErrorsCount=qE;function GE({gen:t,keyword:e,schemaValue:r,data:s,errsCount:o,it:n}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Be.default.errors,a=>{t.const(i,(0,Y._)`${Be.default.vErrors}[${a}]`),t.if((0,Y._)`${i}.instancePath === undefined`,()=>t.assign((0,Y._)`${i}.instancePath`,(0,Y.strConcat)(Be.default.instancePath,n.errorPath))),t.assign((0,Y._)`${i}.schemaPath`,(0,Y.str)`${n.errSchemaPath}/${e}`),n.opts.verbose&&(t.assign((0,Y._)`${i}.schema`,r),t.assign((0,Y._)`${i}.data`,s))})}we.extendErrors=GE;function Mu(t,e){let r=t.const("err",e);t.if((0,Y._)`${Be.default.vErrors} === null`,()=>t.assign(Be.default.vErrors,(0,Y._)`[${r}]`),(0,Y._)`${Be.default.vErrors}.push(${r})`),t.code((0,Y._)`${Be.default.errors}++`)}function vu(t,e){let{gen:r,validateName:s,schemaEnv:o}=t;o.$async?r.throw((0,Y._)`new ${t.ValidationError}(${e})`):(r.assign((0,Y._)`${s}.errors`,e),r.return(!1))}var jt={keyword:new Y.Name("keyword"),schemaPath:new Y.Name("schemaPath"),params:new Y.Name("params"),propertyName:new Y.Name("propertyName"),message:new Y.Name("message"),schema:new Y.Name("schema"),parentSchema:new Y.Name("parentSchema")};function bu(t,e,r){let{createErrors:s}=t.it;return s===!1?(0,Y._)`{}`:HE(t,e,r)}function HE(t,e,r={}){let{gen:s,it:o}=t,n=[YE(o,r),JE(t,r)];return WE(t,e,n),s.object(...n)}function YE({errorPath:t},{instancePath:e}){let r=e?(0,Y.str)`${t}${(0,jo.getErrorPath)(e,jo.Type.Str)}`:t;return[Be.default.instancePath,(0,Y.strConcat)(Be.default.instancePath,r)]}function JE({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:s}){let o=s?e:(0,Y.str)`${e}/${t}`;return r&&(o=(0,Y.str)`${o}${(0,jo.getErrorPath)(r,jo.Type.Str)}`),[jt.schemaPath,o]}function WE(t,{params:e,message:r},s){let{keyword:o,data:n,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;s.push([jt.keyword,o],[jt.params,typeof e=="function"?e(t):e||(0,Y._)`{}`]),c.messages&&s.push([jt.message,typeof r=="function"?r(t):r]),c.verbose&&s.push([jt.schema,i],[jt.parentSchema,(0,Y._)`${l}${d}`],[Be.default.data,n]),u&&s.push([jt.propertyName,u])}});var Tu=Q(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.boolOrEmptySchema=cr.topBoolOrEmptySchema=void 0;var VE=us(),KE=U(),ZE=nt(),XE={message:"boolean schema is false"};function ey(t){let{gen:e,schema:r,validateName:s}=t;r===!1?xu(t,!1):typeof r=="object"&&r.$async===!0?e.return(ZE.default.data):(e.assign((0,KE._)`${s}.errors`,null),e.return(!0))}cr.topBoolOrEmptySchema=ey;function ty(t,e){let{gen:r,schema:s}=t;s===!1?(r.var(e,!1),xu(t)):r.var(e,!0)}cr.boolOrEmptySchema=ty;function xu(t,e){let{gen:r,data:s}=t,o={gen:r,keyword:"false schema",data:s,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,VE.reportError)(o,XE,void 0,e)}});var Xi=Q(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.getRules=lr.isJSONType=void 0;var ry=["string","number","integer","boolean","null","object","array"],sy=new Set(ry);function oy(t){return typeof t=="string"&&sy.has(t)}lr.isJSONType=oy;function ny(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}lr.getRules=ny});var ea=Q(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.shouldUseRule=wt.shouldUseGroup=wt.schemaHasRulesForType=void 0;function iy({schema:t,self:e},r){let s=e.RULES.types[r];return s&&s!==!0&&Ru(t,s)}wt.schemaHasRulesForType=iy;function Ru(t,e){return e.rules.some(r=>Du(t,r))}wt.shouldUseGroup=Ru;function Du(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(s=>t[s]!==void 0))}wt.shouldUseRule=Du});var ds=Q(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.reportTypeError=Ce.checkDataTypes=Ce.checkDataType=Ce.coerceAndCheckDataType=Ce.getJSONTypes=Ce.getSchemaTypes=Ce.DataType=void 0;var ay=Xi(),cy=ea(),ly=us(),N=U(),$u=H(),ur;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(ur||(Ce.DataType=ur={}));function uy(t){let e=Pu(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Ce.getSchemaTypes=uy;function Pu(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(ay.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ce.getJSONTypes=Pu;function dy(t,e){let{gen:r,data:s,opts:o}=t,n=Ay(e,o.coerceTypes),i=e.length>0&&!(n.length===0&&e.length===1&&(0,cy.schemaHasRulesForType)(t,e[0]));if(i){let a=ra(e,s,o.strictNumbers,ur.Wrong);r.if(a,()=>{n.length?py(t,e,n):sa(t)})}return i}Ce.coerceAndCheckDataType=dy;var ju=new Set(["string","number","integer","boolean","null"]);function Ay(t,e){return e?t.filter(r=>ju.has(r)||e==="array"&&r==="array"):[]}function py(t,e,r){let{gen:s,data:o,opts:n}=t,i=s.let("dataType",(0,N._)`typeof ${o}`),a=s.let("coerced",(0,N._)`undefined`);n.coerceTypes==="array"&&s.if((0,N._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>s.assign(o,(0,N._)`${o}[0]`).assign(i,(0,N._)`typeof ${o}`).if(ra(e,o,n.strictNumbers),()=>s.assign(a,o))),s.if((0,N._)`${a} !== undefined`);for(let u of r)(ju.has(u)||u==="array"&&n.coerceTypes==="array")&&c(u);s.else(),sa(t),s.endIf(),s.if((0,N._)`${a} !== undefined`,()=>{s.assign(o,a),my(t,a)});function c(u){switch(u){case"string":s.elseIf((0,N._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,N._)`"" + ${o}`).elseIf((0,N._)`${o} === null`).assign(a,(0,N._)`""`);return;case"number":s.elseIf((0,N._)`${i} == "boolean" || ${o} === null
|
|
6
6
|
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,N._)`+${o}`);return;case"integer":s.elseIf((0,N._)`${i} === "boolean" || ${o} === null
|
|
7
7
|
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,N._)`+${o}`);return;case"boolean":s.elseIf((0,N._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,N._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":s.elseIf((0,N._)`${o} === "" || ${o} === 0 || ${o} === false`),s.assign(a,null);return;case"array":s.elseIf((0,N._)`${i} === "string" || ${i} === "number"
|
|
@@ -19,7 +19,7 @@ ${ce}`,d++}else pp(E,B,z)?p=E.slice(E.charCodeAt(B+6)===qt?B+7:B+6,M)||void 0:y(
|
|
|
19
19
|
${vl}`,d++;return}if(pp(E,B,z)){p=E.slice(E.charCodeAt(B+6)===qt?B+7:B+6,M)||void 0;return}if(z===105&&E.charCodeAt(B+1)===100&&E.charCodeAt(B+2)===58){let mt=E.slice(E.charCodeAt(B+3)===qt?B+4:B+3,M);u=mt.includes("\0")?void 0:mt;return}if(z===58){if(o){let mt=E.slice(B,M);o(mt.slice(E.charCodeAt(B+1)===qt?2:1))}return}let D=E.slice(B,M),ce=D.indexOf(":");if(ce===-1){w(D,"",D);return}let qr=D.slice(0,ce),ao=D.charCodeAt(ce+1)===qt?2:1,co=D.slice(ce+ao);w(qr,co,D)}function w(E,B,M){switch(E){case"event":p=B||void 0;break;case"data":l=d===0?B:`${l}
|
|
20
20
|
${B}`,d++;break;case"id":u=B.includes("\0")?void 0:B;break;case"retry":/^\d+$/.test(B)?s(parseInt(B,10)):r(new xs(`Invalid \`retry\` value: "${B}"`,{type:"invalid-retry",value:B,line:M}));break;default:r(new xs(`Unknown field "${E.length>20?`${E.slice(0,20)}\u2026`:E}"`,{type:"unknown-field",field:E,value:B,line:M}));break}}function I(){d>0&&e({id:u,event:p,data:l}),u=void 0,l="",d=0,p=void 0}function v(E={}){if(E.consume&&i.length>0){let B=i.join("");y(B,0,B.length)}c=!0,u=void 0,l="",d=0,p=void 0,i.length=0,a=0,m=!1}return{feed:g,reset:v}}function Ap(t,e,r){return r===100&&t.charCodeAt(e+1)===97&&t.charCodeAt(e+2)===116&&t.charCodeAt(e+3)===97&&t.charCodeAt(e+4)===58}function pp(t,e,r){return r===101&&t.charCodeAt(e+1)===118&&t.charCodeAt(e+2)===101&&t.charCodeAt(e+3)===110&&t.charCodeAt(e+4)===116&&t.charCodeAt(e+5)===58}var hn=class extends Event{constructor(e,r){var s,o;super(e),this.code=(s=r?.code)!=null?s:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,s){return s(mp(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(mp(this),r)}};function BQ(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Sc(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Sc).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Sc(t.cause)}`:t.message:`${t}`}function mp(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var gp=t=>{throw TypeError(t)},Dc=(t,e,r)=>e.has(t)||gp("Cannot "+r),q=(t,e,r)=>(Dc(t,e,"read from private field"),r?r.call(t):e.get(t)),de=(t,e,r)=>e.has(t)?gp("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),se=(t,e,r,s)=>(Dc(t,e,"write to private field"),e.set(t,r),r),at=(t,e,r)=>(Dc(t,e,"access private method"),r),xe,Gt,Qr,gn,En,Ds,kr,$s,kt,_r,Mr,Sr,Ts,He,kc,Mc,vc,fp,bc,xc,Rs,Tc,Rc,Ht=class extends EventTarget{constructor(e,r){var s,o;super(),de(this,He),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,de(this,xe),de(this,Gt),de(this,Qr),de(this,gn),de(this,En),de(this,Ds),de(this,kr),de(this,$s,null),de(this,kt),de(this,_r),de(this,Mr,null),de(this,Sr,null),de(this,Ts,null),de(this,Mc,async n=>{var i;q(this,_r).reset();let{body:a,redirected:c,status:u,headers:l}=n;if(u===204){at(this,He,Rs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?se(this,Qr,new URL(n.url)):se(this,Qr,void 0),u!==200){at(this,He,Rs).call(this,`Non-200 status code (${u})`,u);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){at(this,He,Rs).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(q(this,xe)===this.CLOSED)return;se(this,xe,this.OPEN);let d=new Event("open");if((i=q(this,Ts))==null||i.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){at(this,He,Rs).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,m=a.getReader(),g=!0;do{let{done:f,value:h}=await m.read();h&&q(this,_r).feed(p.decode(h,{stream:!f})),f&&(g=!1,q(this,_r).reset(),at(this,He,Tc).call(this))}while(g)}),de(this,vc,n=>{se(this,kt,void 0),!(n.name==="AbortError"||n.type==="aborted")&&at(this,He,Tc).call(this,Sc(n))}),de(this,bc,n=>{typeof n.id=="string"&&se(this,$s,n.id);let i=new MessageEvent(n.event||"message",{data:n.data,origin:q(this,Qr)?q(this,Qr).origin:q(this,Gt).origin,lastEventId:n.id||""});q(this,Sr)&&(!n.event||n.event==="message")&&q(this,Sr).call(this,i),this.dispatchEvent(i)}),de(this,xc,n=>{se(this,Ds,n)}),de(this,Rc,()=>{se(this,kr,void 0),q(this,xe)===this.CONNECTING&&at(this,He,kc).call(this)});try{if(e instanceof URL)se(this,Gt,e);else if(typeof e=="string")se(this,Gt,new URL(e,QQ()));else throw new Error("Invalid URL")}catch{throw BQ("An invalid or illegal string was specified")}se(this,_r,fn({onEvent:q(this,bc),onRetry:q(this,xc)})),se(this,xe,this.CONNECTING),se(this,Ds,3e3),se(this,En,(s=r?.fetch)!=null?s:globalThis.fetch),se(this,gn,(o=r?.withCredentials)!=null?o:!1),at(this,He,kc).call(this)}get readyState(){return q(this,xe)}get url(){return q(this,Gt).href}get withCredentials(){return q(this,gn)}get onerror(){return q(this,Mr)}set onerror(e){se(this,Mr,e)}get onmessage(){return q(this,Sr)}set onmessage(e){se(this,Sr,e)}get onopen(){return q(this,Ts)}set onopen(e){se(this,Ts,e)}addEventListener(e,r,s){let o=r;super.addEventListener(e,o,s)}removeEventListener(e,r,s){let o=r;super.removeEventListener(e,o,s)}close(){q(this,kr)&&clearTimeout(q(this,kr)),q(this,xe)!==this.CLOSED&&(q(this,kt)&&q(this,kt).abort(),se(this,xe,this.CLOSED),se(this,kt,void 0))}};xe=new WeakMap,Gt=new WeakMap,Qr=new WeakMap,gn=new WeakMap,En=new WeakMap,Ds=new WeakMap,kr=new WeakMap,$s=new WeakMap,kt=new WeakMap,_r=new WeakMap,Mr=new WeakMap,Sr=new WeakMap,Ts=new WeakMap,He=new WeakSet,kc=function(){se(this,xe,this.CONNECTING),se(this,kt,new AbortController),q(this,En)(q(this,Gt),at(this,He,fp).call(this)).then(q(this,Mc)).catch(q(this,vc))},Mc=new WeakMap,vc=new WeakMap,fp=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...q(this,$s)?{"Last-Event-ID":q(this,$s)}:void 0},cache:"no-store",signal:(t=q(this,kt))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},bc=new WeakMap,xc=new WeakMap,Rs=function(t,e){var r;q(this,xe)!==this.CLOSED&&se(this,xe,this.CLOSED);let s=new hn("error",{code:e,message:t});(r=q(this,Mr))==null||r.call(this,s),this.dispatchEvent(s)},Tc=function(t,e){var r;if(q(this,xe)===this.CLOSED)return;se(this,xe,this.CONNECTING);let s=new hn("error",{code:e,message:t});(r=q(this,Mr))==null||r.call(this,s),this.dispatchEvent(s),se(this,kr,setTimeout(q(this,Rc),q(this,Ds)))},Rc=new WeakMap,Ht.CONNECTING=0,Ht.OPEN=1,Ht.CLOSED=2;function QQ(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}function vr(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function yn(t=fetch,e){return e?async(r,s)=>{let o={...e,...s,headers:s?.headers?{...vr(e.headers),...vr(s.headers)}:e.headers};return t(r,o)}:t}var $c;$c=globalThis.crypto?.webcrypto??globalThis.crypto??import("crypto").then(t=>t.webcrypto);async function _Q(t){return(await $c).getRandomValues(new Uint8Array(t))}async function SQ(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,s="";for(;s.length<t;){let o=await _Q(t-s.length);for(let n of o)n<r&&(s+=e[n%e.length])}return s}async function kQ(t){return await SQ(t)}async function MQ(t){let e=await(await $c).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Pc(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await kQ(t),r=await MQ(e);return{code_verifier:e,code_challenge:r}}var Ee=$l().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:zl.custom,message:"URL must be parseable",fatal:!0}),bl}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Ep=le({resource:A().url(),authorization_servers:_(Ee).optional(),jwks_uri:A().url().optional(),scopes_supported:_(A()).optional(),bearer_methods_supported:_(A()).optional(),resource_signing_alg_values_supported:_(A()).optional(),resource_name:A().optional(),resource_documentation:A().optional(),resource_policy_uri:A().url().optional(),resource_tos_uri:A().url().optional(),tls_client_certificate_bound_access_tokens:K().optional(),authorization_details_types_supported:_(A()).optional(),dpop_signing_alg_values_supported:_(A()).optional(),dpop_bound_access_tokens_required:K().optional()}),jc=le({issuer:A(),authorization_endpoint:Ee,token_endpoint:Ee,registration_endpoint:Ee.optional(),scopes_supported:_(A()).optional(),response_types_supported:_(A()),response_modes_supported:_(A()).optional(),grant_types_supported:_(A()).optional(),token_endpoint_auth_methods_supported:_(A()).optional(),token_endpoint_auth_signing_alg_values_supported:_(A()).optional(),service_documentation:Ee.optional(),revocation_endpoint:Ee.optional(),revocation_endpoint_auth_methods_supported:_(A()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(A()).optional(),introspection_endpoint:A().optional(),introspection_endpoint_auth_methods_supported:_(A()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(A()).optional(),code_challenge_methods_supported:_(A()).optional(),client_id_metadata_document_supported:K().optional()}),vQ=le({issuer:A(),authorization_endpoint:Ee,token_endpoint:Ee,userinfo_endpoint:Ee.optional(),jwks_uri:Ee,registration_endpoint:Ee.optional(),scopes_supported:_(A()).optional(),response_types_supported:_(A()),response_modes_supported:_(A()).optional(),grant_types_supported:_(A()).optional(),acr_values_supported:_(A()).optional(),subject_types_supported:_(A()),id_token_signing_alg_values_supported:_(A()),id_token_encryption_alg_values_supported:_(A()).optional(),id_token_encryption_enc_values_supported:_(A()).optional(),userinfo_signing_alg_values_supported:_(A()).optional(),userinfo_encryption_alg_values_supported:_(A()).optional(),userinfo_encryption_enc_values_supported:_(A()).optional(),request_object_signing_alg_values_supported:_(A()).optional(),request_object_encryption_alg_values_supported:_(A()).optional(),request_object_encryption_enc_values_supported:_(A()).optional(),token_endpoint_auth_methods_supported:_(A()).optional(),token_endpoint_auth_signing_alg_values_supported:_(A()).optional(),display_values_supported:_(A()).optional(),claim_types_supported:_(A()).optional(),claims_supported:_(A()).optional(),service_documentation:A().optional(),claims_locales_supported:_(A()).optional(),ui_locales_supported:_(A()).optional(),claims_parameter_supported:K().optional(),request_parameter_supported:K().optional(),request_uri_parameter_supported:K().optional(),require_request_uri_registration:K().optional(),op_policy_uri:Ee.optional(),op_tos_uri:Ee.optional(),client_id_metadata_document_supported:K().optional()}),yp=k({...vQ.shape,...jc.pick({code_challenge_methods_supported:!0}).shape}),wp=k({access_token:A(),id_token:A().optional(),token_type:A(),expires_in:Ul.number().optional(),scope:A().optional(),refresh_token:A().optional()}).strip(),Cp=k({error:A(),error_description:A().optional(),error_uri:A().optional()}),hp=Ee.optional().or(b("").transform(()=>{})),bQ=k({redirect_uris:_(Ee),token_endpoint_auth_method:A().optional(),grant_types:_(A()).optional(),response_types:_(A()).optional(),client_name:A().optional(),client_uri:Ee.optional(),logo_uri:hp,scope:A().optional(),contacts:_(A()).optional(),tos_uri:hp,policy_uri:A().optional(),jwks_uri:Ee.optional(),jwks:jl().optional(),software_id:A().optional(),software_version:A().optional(),software_statement:A().optional()}).strip(),xQ=k({client_id:A(),client_secret:A().optional(),client_id_issued_at:J().optional(),client_secret_expires_at:J().optional()}).strip(),Ip=bQ.merge(xQ),NR=k({error:A(),error_description:A().optional()}).strip(),zR=k({token:A(),token_type_hint:A().optional()}).strip();function Bp(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function Qp({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),s=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==s.origin||r.pathname.length<s.pathname.length)return!1;let o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",n=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return o.startsWith(n)}var ae=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Ps=class extends ae{};Ps.errorCode="invalid_request";var Yt=class extends ae{};Yt.errorCode="invalid_client";var Jt=class extends ae{};Jt.errorCode="invalid_grant";var Wt=class extends ae{};Wt.errorCode="unauthorized_client";var js=class extends ae{};js.errorCode="unsupported_grant_type";var Ns=class extends ae{};Ns.errorCode="invalid_scope";var zs=class extends ae{};zs.errorCode="access_denied";var ct=class extends ae{};ct.errorCode="server_error";var Us=class extends ae{};Us.errorCode="temporarily_unavailable";var Fs=class extends ae{};Fs.errorCode="unsupported_response_type";var Os=class extends ae{};Os.errorCode="unsupported_token_type";var Ls=class extends ae{};Ls.errorCode="invalid_token";var qs=class extends ae{};qs.errorCode="method_not_allowed";var Gs=class extends ae{};Gs.errorCode="too_many_requests";var Vt=class extends ae{};Vt.errorCode="invalid_client_metadata";var Hs=class extends ae{};Hs.errorCode="insufficient_scope";var Ys=class extends ae{};Ys.errorCode="invalid_target";var _p={[Ps.errorCode]:Ps,[Yt.errorCode]:Yt,[Jt.errorCode]:Jt,[Wt.errorCode]:Wt,[js.errorCode]:js,[Ns.errorCode]:Ns,[zs.errorCode]:zs,[ct.errorCode]:ct,[Us.errorCode]:Us,[Fs.errorCode]:Fs,[Os.errorCode]:Os,[Ls.errorCode]:Ls,[qs.errorCode]:qs,[Gs.errorCode]:Gs,[Vt.errorCode]:Vt,[Hs.errorCode]:Hs,[Ys.errorCode]:Ys};var _e=class extends Error{constructor(e){super(e??"Unauthorized")}};function TQ(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Nc="code",zc="S256";function RQ(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&TQ(t.token_endpoint_auth_method)&&(e.length===0||e.includes(t.token_endpoint_auth_method))?t.token_endpoint_auth_method:e.length===0?r?"client_secret_basic":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function DQ(t,e,r,s){let{client_id:o,client_secret:n}=e;switch(t){case"client_secret_basic":$Q(o,n,r);return;case"client_secret_post":PQ(o,n,s);return;case"none":jQ(o,s);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function $Q(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let s=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${s}`)}function PQ(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function jQ(t,e){e.set("client_id",t)}async function kp(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let s=Cp.parse(JSON.parse(r)),{error:o,error_description:n,error_uri:i}=s,a=_p[o]||ct;return new a(n||"",i)}catch(s){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${s}. Raw body: ${r}`;return new ct(o)}}async function lt(t,e){try{return await Uc(t,e)}catch(r){if(r instanceof Yt||r instanceof Wt)return await t.invalidateCredentials?.("all"),await Uc(t,e);if(r instanceof Jt)return await t.invalidateCredentials?.("tokens"),await Uc(t,e);throw r}}async function Uc(t,{serverUrl:e,authorizationCode:r,scope:s,resourceMetadataUrl:o,fetchFn:n}){let i=await t.discoveryState?.(),a,c,u,l=o;if(!l&&i?.resourceMetadataUrl&&(l=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,u=i.authorizationServerMetadata??await vp(c,{fetchFn:n}),!a)try{a=await Mp(e,{resourceMetadataUrl:l},n)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let I=await qQ(e,{resourceMetadataUrl:l,fetchFn:n});c=I.authorizationServerUrl,u=I.authorizationServerMetadata,a=I.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let d=await zQ(e,t,a),p=s||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,m=await Promise.resolve(t.clientInformation());if(!m){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let I=u?.client_id_metadata_document_supported===!0,v=t.clientMetadataUrl;if(v&&!NQ(v))throw new Vt(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${v}`);if(I&&v)m={client_id:v},await t.saveClientInformation?.(m);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let B=await WQ(c,{metadata:u,clientMetadata:t.clientMetadata,scope:p,fetchFn:n});await t.saveClientInformation(B),m=B}}let g=!t.redirectUrl;if(r!==void 0||g){let I=await JQ(t,c,{metadata:u,resource:d,authorizationCode:r,fetchFn:n});return await t.saveTokens(I),"AUTHORIZED"}let f=await t.tokens();if(f?.refresh_token)try{let I=await YQ(c,{metadata:u,clientInformation:m,refreshToken:f.refresh_token,resource:d,addClientAuthentication:t.addClientAuthentication,fetchFn:n});return await t.saveTokens(I),"AUTHORIZED"}catch(I){if(!(!(I instanceof ae)||I instanceof ct))throw I}let h=t.state?await t.state():void 0,{authorizationUrl:y,codeVerifier:w}=await GQ(c,{metadata:u,clientInformation:m,state:h,redirectUrl:t.redirectUrl,scope:p,resource:d});return await t.saveCodeVerifier(w),await t.redirectToAuthorization(y),"REDIRECT"}function NQ(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function zQ(t,e,r){let s=Bp(t);if(e.validateResourceURL)return await e.validateResourceURL(s,r?.resource);if(r){if(!Qp({requestedResource:s,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${s} (or origin)`);return new URL(r.resource)}}function br(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,s]=e.split(" ");if(r.toLowerCase()!=="bearer"||!s)return{};let o=Fc(t,"resource_metadata")||void 0,n;if(o)try{n=new URL(o)}catch{}let i=Fc(t,"scope")||void 0,a=Fc(t,"error")||void 0;return{resourceMetadataUrl:n,scope:i,error:a}}function Fc(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let s=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(s);return o?o[1]||o[2]:null}async function Mp(t,e,r=fetch){let s=await OQ(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!s||s.status===404)throw await s?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!s.ok)throw await s.body?.cancel(),new Error(`HTTP ${s.status} trying to load well-known OAuth protected resource metadata.`);return Ep.parse(await s.json())}async function Oc(t,e,r=fetch){try{return await r(t,{headers:e})}catch(s){if(s instanceof TypeError)return e?Oc(t,void 0,r):void 0;throw s}}function UQ(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Sp(t,e,r=fetch){return await Oc(t,{"MCP-Protocol-Version":e},r)}function FQ(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function OQ(t,e,r,s){let o=new URL(t),n=s?.protocolVersion??sr,i;if(s?.metadataUrl)i=new URL(s.metadataUrl);else{let c=UQ(e,o.pathname);i=new URL(c,s?.metadataServerUrl??o),i.search=o.search}let a=await Sp(i,n,r);if(!s?.metadataUrl&&FQ(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await Sp(c,n,r)}return a}function LQ(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",s=[];if(!r)return s.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),s.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),s;let o=e.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),s.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,e.origin),type:"oauth"}),s.push({url:new URL(`/.well-known/openid-configuration${o}`,e.origin),type:"oidc"}),s.push({url:new URL(`${o}/.well-known/openid-configuration`,e.origin),type:"oidc"}),s}async function vp(t,{fetchFn:e=fetch,protocolVersion:r=sr}={}){let s={"MCP-Protocol-Version":r,Accept:"application/json"},o=LQ(t);for(let{url:n,type:i}of o){let a=await Oc(n,s,e);if(a){if(!a.ok){if(await a.body?.cancel(),a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${n}`)}return i==="oauth"?jc.parse(await a.json()):yp.parse(await a.json())}}}async function qQ(t,e){let r,s;try{r=await Mp(t,{resourceMetadataUrl:e?.resourceMetadataUrl},e?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(s=r.authorization_servers[0])}catch{}s||(s=String(new URL("/",t)));let o=await vp(s,{fetchFn:e?.fetchFn});return{authorizationServerUrl:s,authorizationServerMetadata:o,resourceMetadata:r}}async function GQ(t,{metadata:e,clientInformation:r,redirectUrl:s,scope:o,state:n,resource:i}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Nc))throw new Error(`Incompatible auth server: does not support response type ${Nc}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(zc))throw new Error(`Incompatible auth server: does not support code challenge method ${zc}`)}else a=new URL("/authorize",t);let c=await Pc(),u=c.code_verifier,l=c.code_challenge;return a.searchParams.set("response_type",Nc),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",l),a.searchParams.set("code_challenge_method",zc),a.searchParams.set("redirect_uri",String(s)),n&&a.searchParams.set("state",n),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:u}}function HQ(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function bp(t,{metadata:e,tokenRequestParams:r,clientInformation:s,addClientAuthentication:o,resource:n,fetchFn:i}){let a=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(n&&r.set("resource",n.href),o)await o(c,r,a,e);else if(s){let l=e?.token_endpoint_auth_methods_supported??[],d=RQ(s,l);DQ(d,s,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await kp(u);return wp.parse(await u.json())}async function YQ(t,{metadata:e,clientInformation:r,refreshToken:s,resource:o,addClientAuthentication:n,fetchFn:i}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:s}),c=await bp(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:n,resource:o,fetchFn:i});return{refresh_token:s,...c}}async function JQ(t,e,{metadata:r,resource:s,authorizationCode:o,fetchFn:n}={}){let i=t.clientMetadata.scope,a;if(t.prepareTokenRequest&&(a=await t.prepareTokenRequest(i)),!a){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let u=await t.codeVerifier();a=HQ(o,u,t.redirectUrl)}let c=await t.clientInformation();return bp(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:s,fetchFn:n})}async function WQ(t,{metadata:e,clientMetadata:r,scope:s,fetchFn:o}){let n;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(e.registration_endpoint)}else n=new URL("/register",t);let i=await(o??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...s!==void 0?{scope:s}:{}})});if(!i.ok)throw await kp(i);return Ip.parse(await i.json())}var Lc=class extends Error{constructor(e,r,s){super(`SSE error: ${r}`),this.code=e,this.event=s}},wn=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=yn(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new _e("No auth provider");let e;try{e=await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new _e;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let s=await this._authProvider.tokens();s&&(e.Authorization=`Bearer ${s.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=vr(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,s)=>{this._eventSource=new Ht(this._url.href,{...this._eventSourceInit,fetch:async(o,n)=>{let i=await this._commonHeaders();i.set("Accept","text/event-stream");let a=await e(o,{...n,headers:i});if(a.status===401&&a.headers.has("www-authenticate")){let{resourceMetadataUrl:c,scope:u}=br(a);this._resourceMetadataUrl=c,this._scope=u}return a}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,s);return}let n=new Lc(o.code,o.message,o);s(n),this.onerror?.(n)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{let n=o;try{if(this._endpoint=new URL(n.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){s(i),this.onerror?.(i),this.close();return}r()}),this._eventSource.onmessage=o=>{let n=o,i;try{i=ht.parse(JSON.parse(n.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(i)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new _e("No auth provider");if(await lt(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new _e("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let s={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,s);if(!o.ok){let n=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){let{resourceMetadataUrl:i,scope:a}=br(o);if(this._resourceMetadataUrl=i,this._scope=a,await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new _e;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${n}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};var wm=lo(Em(),1);import Xc from"process";import{PassThrough as Q_}from"stream";var I_=10*1024*1024,In=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??I_}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
21
21
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),B_(r)}clear(){this._buffer=void 0}};function B_(t){return ht.parse(JSON.parse(t))}function ym(t){return JSON.stringify(t)+`
|
|
22
|
-
`}var __=Xc.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function S_(){let t={};for(let e of __){let r=Xc.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Bn=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new In({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Q_)}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)=>{this._process=(0,wm.default)(this._serverParams.command,this._serverParams.args??[],{env:{...S_(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Xc.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",s=>{r(s),this.onerror?.(s)}),this._process.on("spawn",()=>{e()}),this._process.on("close",s=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",s=>{this.onerror?.(s)}),this._process.stdout?.on("data",s=>{try{this._readBuffer.append(s),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}}),this._process.stdout?.on("error",s=>{this.onerror?.(s)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(s=>{e.once("close",()=>{s()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(s=>setTimeout(s,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(s=>setTimeout(s,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let s=ym(e);this._process.stdin.write(s)?r():this._process.stdin.once("drain",r)})}};var _m=lo(Qm(),1);function Sm(t){if(t)try{return _m.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var Qn=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:s,maxBufferSize:o}={}){let n;super({start(i){n=fn({onEvent:a=>{i.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:s,maxBufferSize:o})},transform(i){n.feed(i)}})}};var $_={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Mt=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},_n=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=yn(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??$_}async _authThenStart(){if(!this._authProvider)throw new _e("No auth provider");let e;try{e=await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new _e;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let s=await this._authProvider.tokens();s&&(e.Authorization=`Bearer ${s.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=vr(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let s=await this._commonHeaders();s.set("Accept","text/event-stream"),r&&s.set("last-event-id",r);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:s,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Mt(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(s){throw this.onerror?.(s),s}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,s=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(s,e),o)}_scheduleReconnection(e,r=0){let s=this._reconnectionOptions.maxRetries;if(r>=s){this.onerror?.(new Error(`Maximum reconnection attempts (${s}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,s){if(!e)return;let{onresumptiontoken:o,replayMessageId:n}=r,i,a=!1,c=!1;(async()=>{try{let l=e.pipeThrough(new TextDecoderStream).pipeThrough(new Qn({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){let{value:m,done:g}=await l.read();if(g)break;if(m.id&&(i=m.id,a=!0,o?.(m.id)),!!m.data&&(!m.event||m.event==="message"))try{let f=ht.parse(JSON.parse(m.data));bt(f)&&(c=!0,n!==void 0&&(f.id=n)),this.onmessage?.(f)}catch(f){this.onerror?.(f)}}(s||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:n},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(s||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:n},0)}catch(m){this.onerror?.(new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}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 _e("No auth provider");if(await lt(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new _e("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:s,onresumptiontoken:o}=r||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:Jr(e)?e.id:void 0}).catch(m=>this.onerror?.(m));return}let n=await this._commonHeaders();n.set("content-type","application/json"),n.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:n,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let m=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Mt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:g,scope:f}=br(a);if(this._resourceMetadataUrl=g,this._scope=f,await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new _e;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:g,scope:f,error:h}=br(a);if(h==="insufficient_scope"){let y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Mt(403,"Server returned 403 after trying upscoping");if(f&&(this._scope=f),g&&(this._resourceMetadataUrl=g),this._lastUpscopingHeader=y??void 0,await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new _e;return this.send(e)}}throw new Mt(a.status,`Error POSTing to endpoint: ${m}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),iu(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>this.onerror?.(m));return}let l=(Array.isArray(e)?e:[e]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,d=a.headers.get("content-type"),p=Sm(d);if(l)if(p==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(p==="application/json"){let m=await a.json(),g=Array.isArray(m)?m.map(f=>ht.parse(f)):[ht.parse(m)];for(let f of g)this.onmessage?.(f)}else throw await a.body?.cancel(),new Mt(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(s){throw this.onerror?.(s),s}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},s=await(this._fetch??fetch)(this._url,r);if(await s.body?.cancel(),!s.ok&&s.status!==405)throw new Mt(s.status,`Failed to terminate session: ${s.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,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};import{readFileSync as P_,statSync as j_}from"fs";import{extname as N_}from"path";import tl from"sharp";var z_=R({module:"images"});function km(t){if(t==="image/png"||t==="image/jpeg"||t==="image/gif"||t==="image/webp")return t;throw new Error(`Unsupported image media type: "${t}"`)}var ol=5*1024*1024,rl=ol*3/4,vt=2e3,$D=10,Rr=class extends Error{constructor(e){super(e),this.name="ImageTooLargeError"}},U_={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function F_(t){return U_[N_(t).toLowerCase()]??null}function Mm(t){return F_(t)!==null}function O_(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=6&&t[0]===71&&t[1]===73&&t[2]===70?"image/gif":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}async function vm(t){if(!j_(t).isFile())throw new Error(`Not a file: ${t}`);let r=P_(t),s=O_(r);if(!s)throw new Error(`File ${t} has an image extension but its contents are not a supported image format (png/jpeg/gif/webp)`);let o=await nl(r,s);return{mediaType:o.mediaType,data:o.data,sourcePath:t,byteLength:o.byteLength}}function sl(t,e){return{data:t.toString("base64"),mediaType:e,byteLength:t.length}}function Js(t){return`${(t/(1024*1024)).toFixed(1)}MB`}async function nl(t,e){if(t.length===0)throw new Rr("Image file is empty (0 bytes)");if(t.length<=rl)return sl(t,e);try{return await L_(t,e)}catch(r){throw r instanceof Rr?r:(z_.warn({err:r},"sharp compression failed"),new Rr(`Image is ${Js(t.length)} raw (${Js(t.length*4/3)} base64-encoded, API limit ${Js(ol)}) and compression failed. Please provide a smaller image.`))}}async function L_(t,e){let r=await tl(t).metadata(),s=r.width??vt,o=r.height??vt;s>vt&&(o=Math.max(1,Math.round(o*vt/s)),s=vt),o>vt&&(s=Math.max(1,Math.round(s*vt/o)),o=vt);let n=e==="image/png"||e==="image/gif";for(let i=0;i<3;i++){if(n){let a=await tl(t).resize(s,o,{fit:"inside",withoutEnlargement:!0}).png({compressionLevel:8,palette:!0}).toBuffer();if(a.length<=rl)return sl(a,"image/png")}for(let a of[80,60,40,20]){let c=await tl(t).resize(s,o,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:a}).toBuffer();if(c.length<=rl)return sl(c,"image/jpeg")}s=Math.max(1,Math.round(s/2)),o=Math.max(1,Math.round(o/2))}throw new Rr(`Unable to compress image (${Js(t.length)} raw) under the ${Js(ol)} API limit. Please provide a smaller image.`)}import{readFileSync as q_}from"fs";import bm from"path";import{fileURLToPath as G_}from"url";var H_=$.object({version:$.string()});function Y_(){return"0.0.24"}var xm=Y_();var Rm=R({module:"mcp"});function Tm(t){return t.replace(/\$\{(\w+)\}|\$(\w+)/g,(e,r,s)=>process.env[r||s]??"")}function J_(t){let e={};for(let[r,s]of Object.entries(t))e[r]=s??"";return e}var W_=new Set(["image/png","image/jpeg","image/gif","image/webp"]);async function V_(t){let e=[],r=[],s=!1;for(let n of t){let i=Ol(n)?n:{};if(i.type==="image"&&typeof i.data=="string"&&typeof i.mimeType=="string"&&W_.has(i.mimeType))try{let u=await nl(Buffer.from(i.data,"base64"),km(i.mimeType));r.push({type:"image",source:{type:"base64",media_type:u.mediaType,data:u.data}}),e.push(`[Image: ${u.mediaType}]`),s=!0;continue}catch(u){Rm.warn({err:u},"mcp image dropped (too large to fit the API limit)");let l="[note: an image returned by the tool was too large and was dropped]";e.push(l),r.push({type:"text",text:l});continue}if(i.type==="image"){let l=`[Unsupported image: ${typeof i.mimeType=="string"?i.mimeType:"unknown"}]`;e.push(l),r.push({type:"text",text:l});continue}let a=JSON.stringify(n),c=i.type==="text"&&typeof i.text=="string"?i.text:typeof a=="string"?a:String(n);e.push(c),r.push({type:"text",text:c})}let o=e.join(`
|
|
22
|
+
`}var __=Xc.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function S_(){let t={};for(let e of __){let r=Xc.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Bn=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new In({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Q_)}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)=>{this._process=(0,wm.default)(this._serverParams.command,this._serverParams.args??[],{env:{...S_(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Xc.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",s=>{r(s),this.onerror?.(s)}),this._process.on("spawn",()=>{e()}),this._process.on("close",s=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",s=>{this.onerror?.(s)}),this._process.stdout?.on("data",s=>{try{this._readBuffer.append(s),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}}),this._process.stdout?.on("error",s=>{this.onerror?.(s)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(s=>{e.once("close",()=>{s()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(s=>setTimeout(s,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(s=>setTimeout(s,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let s=ym(e);this._process.stdin.write(s)?r():this._process.stdin.once("drain",r)})}};var _m=lo(Qm(),1);function Sm(t){if(t)try{return _m.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var Qn=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:s,maxBufferSize:o}={}){let n;super({start(i){n=fn({onEvent:a=>{i.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:s,maxBufferSize:o})},transform(i){n.feed(i)}})}};var $_={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Mt=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},_n=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=yn(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??$_}async _authThenStart(){if(!this._authProvider)throw new _e("No auth provider");let e;try{e=await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new _e;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let s=await this._authProvider.tokens();s&&(e.Authorization=`Bearer ${s.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=vr(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let s=await this._commonHeaders();s.set("Accept","text/event-stream"),r&&s.set("last-event-id",r);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:s,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Mt(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(s){throw this.onerror?.(s),s}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,s=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(s,e),o)}_scheduleReconnection(e,r=0){let s=this._reconnectionOptions.maxRetries;if(r>=s){this.onerror?.(new Error(`Maximum reconnection attempts (${s}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,s){if(!e)return;let{onresumptiontoken:o,replayMessageId:n}=r,i,a=!1,c=!1;(async()=>{try{let l=e.pipeThrough(new TextDecoderStream).pipeThrough(new Qn({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){let{value:m,done:g}=await l.read();if(g)break;if(m.id&&(i=m.id,a=!0,o?.(m.id)),!!m.data&&(!m.event||m.event==="message"))try{let f=ht.parse(JSON.parse(m.data));bt(f)&&(c=!0,n!==void 0&&(f.id=n)),this.onmessage?.(f)}catch(f){this.onerror?.(f)}}(s||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:n},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(s||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:n},0)}catch(m){this.onerror?.(new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}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 _e("No auth provider");if(await lt(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new _e("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:s,onresumptiontoken:o}=r||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:Jr(e)?e.id:void 0}).catch(m=>this.onerror?.(m));return}let n=await this._commonHeaders();n.set("content-type","application/json"),n.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:n,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let m=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Mt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:g,scope:f}=br(a);if(this._resourceMetadataUrl=g,this._scope=f,await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new _e;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:g,scope:f,error:h}=br(a);if(h==="insufficient_scope"){let y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Mt(403,"Server returned 403 after trying upscoping");if(f&&(this._scope=f),g&&(this._resourceMetadataUrl=g),this._lastUpscopingHeader=y??void 0,await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new _e;return this.send(e)}}throw new Mt(a.status,`Error POSTing to endpoint: ${m}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),iu(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>this.onerror?.(m));return}let l=(Array.isArray(e)?e:[e]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,d=a.headers.get("content-type"),p=Sm(d);if(l)if(p==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(p==="application/json"){let m=await a.json(),g=Array.isArray(m)?m.map(f=>ht.parse(f)):[ht.parse(m)];for(let f of g)this.onmessage?.(f)}else throw await a.body?.cancel(),new Mt(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(s){throw this.onerror?.(s),s}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},s=await(this._fetch??fetch)(this._url,r);if(await s.body?.cancel(),!s.ok&&s.status!==405)throw new Mt(s.status,`Failed to terminate session: ${s.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,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};import{readFileSync as P_,statSync as j_}from"fs";import{extname as N_}from"path";import tl from"sharp";var z_=R({module:"images"});function km(t){if(t==="image/png"||t==="image/jpeg"||t==="image/gif"||t==="image/webp")return t;throw new Error(`Unsupported image media type: "${t}"`)}var ol=5*1024*1024,rl=ol*3/4,vt=2e3,$D=10,Rr=class extends Error{constructor(e){super(e),this.name="ImageTooLargeError"}},U_={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function F_(t){return U_[N_(t).toLowerCase()]??null}function Mm(t){return F_(t)!==null}function O_(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=6&&t[0]===71&&t[1]===73&&t[2]===70?"image/gif":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}async function vm(t){if(!j_(t).isFile())throw new Error(`Not a file: ${t}`);let r=P_(t),s=O_(r);if(!s)throw new Error(`File ${t} has an image extension but its contents are not a supported image format (png/jpeg/gif/webp)`);let o=await nl(r,s);return{mediaType:o.mediaType,data:o.data,sourcePath:t,byteLength:o.byteLength}}function sl(t,e){return{data:t.toString("base64"),mediaType:e,byteLength:t.length}}function Js(t){return`${(t/(1024*1024)).toFixed(1)}MB`}async function nl(t,e){if(t.length===0)throw new Rr("Image file is empty (0 bytes)");if(t.length<=rl)return sl(t,e);try{return await L_(t,e)}catch(r){throw r instanceof Rr?r:(z_.warn({err:r},"sharp compression failed"),new Rr(`Image is ${Js(t.length)} raw (${Js(t.length*4/3)} base64-encoded, API limit ${Js(ol)}) and compression failed. Please provide a smaller image.`))}}async function L_(t,e){let r=await tl(t).metadata(),s=r.width??vt,o=r.height??vt;s>vt&&(o=Math.max(1,Math.round(o*vt/s)),s=vt),o>vt&&(s=Math.max(1,Math.round(s*vt/o)),o=vt);let n=e==="image/png"||e==="image/gif";for(let i=0;i<3;i++){if(n){let a=await tl(t).resize(s,o,{fit:"inside",withoutEnlargement:!0}).png({compressionLevel:8,palette:!0}).toBuffer();if(a.length<=rl)return sl(a,"image/png")}for(let a of[80,60,40,20]){let c=await tl(t).resize(s,o,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:a}).toBuffer();if(c.length<=rl)return sl(c,"image/jpeg")}s=Math.max(1,Math.round(s/2)),o=Math.max(1,Math.round(o/2))}throw new Rr(`Unable to compress image (${Js(t.length)} raw) under the ${Js(ol)} API limit. Please provide a smaller image.`)}import{readFileSync as q_}from"fs";import bm from"path";import{fileURLToPath as G_}from"url";var H_=$.object({version:$.string()});function Y_(){return"0.0.26"}var xm=Y_();var Rm=R({module:"mcp"});function Tm(t){return t.replace(/\$\{(\w+)\}|\$(\w+)/g,(e,r,s)=>process.env[r||s]??"")}function J_(t){let e={};for(let[r,s]of Object.entries(t))e[r]=s??"";return e}var W_=new Set(["image/png","image/jpeg","image/gif","image/webp"]);async function V_(t){let e=[],r=[],s=!1;for(let n of t){let i=Ol(n)?n:{};if(i.type==="image"&&typeof i.data=="string"&&typeof i.mimeType=="string"&&W_.has(i.mimeType))try{let u=await nl(Buffer.from(i.data,"base64"),km(i.mimeType));r.push({type:"image",source:{type:"base64",media_type:u.mediaType,data:u.data}}),e.push(`[Image: ${u.mediaType}]`),s=!0;continue}catch(u){Rm.warn({err:u},"mcp image dropped (too large to fit the API limit)");let l="[note: an image returned by the tool was too large and was dropped]";e.push(l),r.push({type:"text",text:l});continue}if(i.type==="image"){let l=`[Unsupported image: ${typeof i.mimeType=="string"?i.mimeType:"unknown"}]`;e.push(l),r.push({type:"text",text:l});continue}let a=JSON.stringify(n),c=i.type==="text"&&typeof i.text=="string"?i.text:typeof a=="string"?a:String(n);e.push(c),r.push({type:"text",text:c})}let o=e.join(`
|
|
23
23
|
`);return s?{output:o,contentBlocks:r}:{output:o}}var Sn=class{name;config;client=null;transport=null;constructor(e){this.name=e.name,this.config=e}async connect(){if(this.config.command){let e=process.env;if(this.config.env)for(let[r,s]of Object.entries(this.config.env))e[r]=Tm(s);this.transport=new Bn({command:this.config.command,args:this.config.args??[],env:J_(e),stderr:"ignore"})}else if(this.config.url){let e=new URL(this.config.url),r={};if(this.config.headers)for(let[o,n]of Object.entries(this.config.headers))r[o]=Tm(n);let s={requestInit:{headers:r}};this.transport=this.config.transport==="sse"?new wn(e,s):new _n(e,s)}else throw new Error(`MCP server '${this.name}': needs either 'command' (stdio) or 'url' (http/sse)`);this.client=new mn({name:"swifty",version:xm},{}),await this.client.connect(this.transport)}getInstructions(){return this.client?.getInstructions()??""}async listTools(){if(!this.client)throw new Error("Not connected");return(await this.client.listTools()).tools.map(({name:r,description:s,inputSchema:{properties:o,...n}})=>({name:r,description:s??"",inputSchema:{...n,properties:o??{}}}))}async callTool(e,r){if(!this.client)throw new Error("Not connected");let s=await this.client.callTool({name:e,arguments:r});return{...s.content&&Array.isArray(s.content)?await V_(s.content):{output:JSON.stringify(s)},isError:s.isError===!0}}async disconnect(){try{await this.client?.close()}catch(e){Rm.error({err:e},"mcp operation failed")}this.client=null,this.transport=null}};var K_=R({module:"mcp"}),Dm=class{clients=new Map;async connectAll(e){let r={tools:[],servers:[],errors:[],instructions:[]};for(let s of e){if(this.clients.has(s.name))continue;let o=new Sn(s);try{await o.connect();let n=await o.listTools();this.clients.set(s.name,o),r.servers.push(s.name);for(let a of n)r.tools.push({serverName:s.name,tool:a});let i=o.getInstructions();i&&r.instructions.push({serverName:s.name,text:i})}catch(n){K_.error({err:n},"mcp operation failed"),r.errors.push({serverName:s.name,error:O(n)}),await o.disconnect()}}return r}getClient(e){return this.clients.get(e)}connectedServers(){return[...this.clients.keys()]}missingServers(e){return e.filter(r=>!this.clients.has(r.name)).map(r=>r.name)}async disconnectAll(){for(let e of this.clients.values())await e.disconnect();this.clients.clear()}};import{execSync as Lm}from"child_process";import{platform as Z_,arch as X_}from"os";function $m(){return{name:"Identity",priority:0,content:`You are Swifty, an AI programming assistant running in a terminal.
|
|
24
24
|
You assist users with software engineering tasks, including writing code, debugging, refactoring, explaining code, and executing commands.
|
|
25
25
|
|
|
@@ -377,7 +377,7 @@ ${s.content.replace(/\n+$/,"")}`)}return r.join(`
|
|
|
377
377
|
`),isError:!1})}},Ng=class{name="TaskUpdate";description="Update a task's status, subject, or other fields.";category="read";list;constructor(e){this.list=e}schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{taskId:{type:"string",description:"Task ID"},status:{type:"string",description:"New status: pending, in_progress, completed, deleted"},subject:{type:"string",description:"New subject"},description:{type:"string",description:"New description"},owner:{type:"string",description:"New owner"},addBlocks:{type:"array",items:{type:"string"},description:"Tasks this one blocks"},addBlockedBy:{type:"array",items:{type:"string"},description:"Tasks blocking this one"}},required:["taskId"]}}}async execute(e,r){let s=await xl(hv,r);if(!s.success)return{output:O(s.error),isError:!0};let{taskId:o,status:n,subject:i,description:a,owner:c,addBlocks:u,addBlockedBy:l}=s.data;if(!o)return Promise.resolve({output:"Error: taskId is required",isError:!0});if(n==="deleted")return this.list.delete(o),Promise.resolve({output:`Task #${o} deleted`,isError:!1});let d={};return n&&(d.status=n),i&&(d.subject=i),a&&(d.description=a),c&&(d.owner=c),this.list.update(o,d)?(u&&this.list.addBlocks(o,u),l&&this.list.addBlockedBy(o,l),{output:`Updated task #${o} status`,isError:!1}):{output:"Task not found",isError:!0}}},hv=C.object({taskId:C.string(),subject:C.string().optional(),description:C.string().optional(),status:C.enum(["pending","in_progress","completed","deleted"]).optional(),owner:C.string().optional(),addBlocks:C.array(C.string()).optional(),addBlockedBy:C.array(C.string()).optional()});var zg=class{name="ExitPlanMode";description=`
|
|
378
378
|
Exit plan mode and present the plan for user approval.
|
|
379
379
|
Call this when your plan is complete and written to the plan file.
|
|
380
|
-
`;category="read";isPlanMode=null;planExists=null;schema(){let e={type:"object",properties:{}};return{name:this.name,description:this.description,input_schema:e}}execute(e,r){return this.isPlanMode&&!this.isPlanMode()?Promise.resolve({output:"You are not in plan mode. This tool is only for exiting plan mode after writing a plan.",isError:!0}):this.planExists&&!this.planExists()?Promise.resolve({output:"No plan file found. Please write your plan to the plan file before calling ExitPlanMode.",isError:!0}):Promise.resolve({output:"Plan mode will be exited after this turn. The user will be shown the plan approval dialog. Do not call any more tools \u2014 end your turn now.",isError:!1})}};export{si as a,ht as b,mn as c,Qm as d,$D as e,Mm as f,vm as g,xm as h,Dm as i,qm as j,Gm as k,Rn as l,Dn as m,$n as n,Pn as o,Zm as p,Xm as q,Tn as r,ef as s,tf as t,rf as u,mf as v,gf as w,Z$ as x,eP as y,tP as z,hf as A,gl as B,nP as C,Ks as D,EP as E,yP as F,Pf as G,Gf as H,zn as I,Vf as J,Zf as K,Un as L,eg as M,tg as N,Fn as O,On as P,Ln as Q,cg as R,CN as S,ug as T,dg as U,Ag as V,pg as W,mg as X,zN as Y,UN as Z,YN as _,xM as $,wg as aa,Cg as ba,oz as ca,Kn as da,kg as ea,$z as fa,Tg as ga,Rg as ha,Dg as ia,$g as ja,Pg as ka,jg as la,Ng as ma,zg as na};
|
|
380
|
+
`;category="read";isPlanMode=null;planExists=null;schema(){let e={type:"object",properties:{}};return{name:this.name,description:this.description,input_schema:e}}execute(e,r){return this.isPlanMode&&!this.isPlanMode()?this.planExists?.()?Promise.resolve({output:"You are not in plan mode. This tool is only for exiting plan mode after writing a plan. You can call AskUserQuestion tool to ask the user whether to execute the plan.",isError:!0}):Promise.resolve({output:"You are not in plan mode. This tool is only for exiting plan mode after writing a plan.",isError:!0}):this.planExists&&!this.planExists()?Promise.resolve({output:"No plan file found. Please write your plan to the plan file before calling ExitPlanMode.",isError:!0}):Promise.resolve({output:"Plan mode will be exited after this turn. The user will be shown the plan approval dialog. Do not call any more tools \u2014 end your turn now.",isError:!1})}};export{si as a,ht as b,mn as c,Qm as d,$D as e,Mm as f,vm as g,xm as h,Dm as i,qm as j,Gm as k,Rn as l,Dn as m,$n as n,Pn as o,Zm as p,Xm as q,Tn as r,ef as s,tf as t,rf as u,mf as v,gf as w,Z$ as x,eP as y,tP as z,hf as A,gl as B,nP as C,Ks as D,EP as E,yP as F,Pf as G,Gf as H,zn as I,Vf as J,Zf as K,Un as L,eg as M,tg as N,Fn as O,On as P,Ln as Q,cg as R,CN as S,ug as T,dg as U,Ag as V,pg as W,mg as X,zN as Y,UN as Z,YN as _,xM as $,wg as aa,Cg as ba,oz as ca,Kn as da,kg as ea,$z as fa,Tg as ga,Rg as ha,Dg as ia,$g as ja,Pg as ka,jg as la,Ng as ma,zg as na};
|
|
381
381
|
/*! Bundled license information:
|
|
382
382
|
|
|
383
383
|
content-type/index.js:
|
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
3
|
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{c as D,d as O,e as U,g as W,m as B,n as Y,o as j}from"./chunk-MWZIARZE.js";import{a as C,e as M,g as L}from"./chunk-FZPTNGTU.js";import{I as
|
|
5
|
-
\u2026 (content truncated)`;return t<=o.length?o.slice(0,t):n.slice(0,t-o.length)+o}var
|
|
4
|
+
import{c as D,d as O,e as U,g as W,m as B,n as Y,o as j}from"./chunk-MWZIARZE.js";import{a as C,e as M,g as L}from"./chunk-FZPTNGTU.js";import{I as y,L as A,N as F,O as N,R as T}from"./chunk-SIWLMWHH.js";function I(n){return n?Math.floor(n.length/3.5):0}function x(n,e){if(e<=0||!n||I(n)<=e)return n;let t=Math.floor(e*3.5);if(t<=0||t>=n.length)return n;let o=`
|
|
5
|
+
\u2026 (content truncated)`;return t<=o.length?o.slice(0,t):n.slice(0,t-o.length)+o}var S=class{files=new Map;skills=new Map;recordFileRead(e,t){for(this.files.delete(e),this.files.set(e,{path:e,content:x(t,5e3),timestamp:Date.now()});this.files.size>5;){let o=this.files.keys().next().value;if(typeof o!="string")break;this.files.delete(o)}}recordSkillInvocation(e,t){this.skills.set(e,{name:e,body:t,timestamp:Date.now()})}snapshotFiles(e=5){return[...this.files.values()].sort((o,r)=>r.timestamp-o.timestamp).slice(0,e)}snapshotSkills(){return[...this.skills.values()].sort((e,t)=>t.timestamp-e.timestamp)}buildRecoveryAttachment(e){let t=[],o=this.snapshotFiles();if(o.length>0){t.push(`## Recently read files
|
|
6
6
|
`),t.push(`These snapshots are what the file-reading tool last returned. Re-open with the tool if you need the current bytes.
|
|
7
|
-
`);for(let s of o){let i=
|
|
7
|
+
`);for(let s of o){let i=x(s.content,5e3),l=new Date(s.timestamp).toISOString().replace(/\.\d{3}Z$/,"Z");t.push(`### ${s.path} (read ${l})
|
|
8
8
|
|
|
9
9
|
\`\`\`
|
|
10
10
|
${i}${i.endsWith(`
|
|
11
11
|
`)?"":`
|
|
12
12
|
`}\`\`\``)}}let r=this.snapshotSkills();if(r.length>0){let s=0,i=[];i.push(`## Active skills
|
|
13
13
|
`),i.push(`These skills were invoked earlier in the session. Continue to follow each SOP when its triggering condition applies.
|
|
14
|
-
`);let l=!1;for(let d of r){let u=
|
|
14
|
+
`);let l=!1;for(let d of r){let u=x(d.body,5e3),g=I(u)+I(d.name)+8;if(s+g>25e3)break;s+=g,i.push(`### ${d.name}
|
|
15
15
|
|
|
16
16
|
${u}`),l=!0}l&&t.push(i.join(`
|
|
17
17
|
|
|
@@ -24,7 +24,7 @@ You still have access to the following tools \u2014 call them directly when the
|
|
|
24
24
|
|
|
25
25
|
Everything above the divider is reconstructed context. For exact code, error strings, or user-typed text, re-read the source rather than guess from the summary.`),t.join(`
|
|
26
26
|
|
|
27
|
-
`))}};import{readFileSync as de,writeFileSync as pe,mkdirSync as me,existsSync as
|
|
27
|
+
`))}};import{readFileSync as de,writeFileSync as pe,mkdirSync as me,existsSync as _}from"fs";import{join as $,resolve as H}from"path";var G=y({module:"plan-file"}),V=["brave","calm","dark","eager","fair","gentle","happy","kind","lively","mighty","noble","proud","quiet","swift","warm","wise"],q=["crystal","dragon","eagle","falcon","flame","forest","frost","mountain","ocean","phoenix","river","shadow","thunder","tiger"];function ge(){let n=V[Math.floor(Math.random()*V.length)],e=q[Math.floor(Math.random()*q.length)],t=Date.now().toString(36).slice(-4);return`${n}-${e}-${t}`}var m=null;function K(n,e){let t=H(e,".swifty","plans");return H(n).startsWith(t+"/")}function z(n){if(m&&_(m))if(!K(m,n))G.warn({planPath:m,workDir:n},"current plan path is not under work dir");else return m;let e=$(n,".swifty","plans");me(e,{recursive:!0});let t=ge();return m=$(e,`${t}.md`),pe(m,"","utf-8"),m}function Ne(){return!m||!_(m)?null:de(m,"utf-8")}function X(n){return!m||!_(m)?!1:K(m,n)?!0:(G.warn({planPath:m,workDir:n},"current plan path is not under work dir"),!1)}function Me(){m=null}var fe=`You are Swifty, an AI assistant that orchestrates software engineering tasks across multiple workers.
|
|
28
28
|
|
|
29
29
|
## 1. Your Role
|
|
30
30
|
|
|
@@ -224,15 +224,15 @@ At the very end of your turn, once you have asked the user questions and are hap
|
|
|
224
224
|
|
|
225
225
|
You have exited plan mode. You can now make edits, run tools, and take actions.%EXTRA%`,Re="You have re-entered plan mode. Your previous plan file is at %PLAN_PATH%. Review it and continue from where you left off. You can update, refine, or restart the plan as needed. Follow the same 5-phase workflow as before.";function Q(n,e,t){let o=`Plan file: ${n}`;return e?o+=`
|
|
226
226
|
A plan file already exists at ${n}. You can read it and make incremental edits using the EditFile tool.`:o+=`
|
|
227
|
-
No plan file exists yet. You should create your plan at ${n} using the WriteFile tool.`,(t-1)%5===0?ke.replace("%PLAN_FILE_INFO%",o):ve.replace("%PLAN_PATH%",n)}function Oe(n,e){let t="";return e&&(t=` The plan file is located at ${n} if you need to reference it.`),we.replace("%EXTRA%",t)}function Ue(n,e){return e?Re.replace("%PLAN_PATH%",n):""}import{writeFileSync as be,mkdirSync as Se}from"fs";import{join as te,resolve as Z}from"path";var Ee=
|
|
228
|
-
\u2026 ${String(n.length-
|
|
227
|
+
No plan file exists yet. You should create your plan at ${n} using the WriteFile tool.`,(t-1)%5===0?ke.replace("%PLAN_FILE_INFO%",o):ve.replace("%PLAN_PATH%",n)}function Oe(n,e){let t="";return e&&(t=` The plan file is located at ${n} if you need to reference it.`),we.replace("%EXTRA%",t)}function Ue(n,e){return e?Re.replace("%PLAN_PATH%",n):""}import{writeFileSync as be,mkdirSync as Se}from"fs";import{join as te,resolve as Z}from"path";var Ee=y({module:"tool-result"}),ee=2e5,k=2e3;function oe(n,e){return te(n,".swifty","sessions",e||"default","tool-results")}function ne(n,e,t,o){let r=oe(n,e);Se(r,{recursive:!0});let s=te(r,t+".txt");try{be(s,o,{encoding:"utf-8",flag:"wx"})}catch(i){if(Ee.error({err:i},"tool-result operation failed"),N(i)&&"code"in i&&i.code!=="EEXIST")throw i}return s}function He(n){return n.length<=k?n:n.slice(0,k)+`
|
|
228
|
+
\u2026 ${String(n.length-k)} chars omitted from transcript`}function P(n,e){n.content=e,n.contentBlocks?.length&&(n.contentBlocks=[{type:"text",text:e},...n.contentBlocks.filter(t=>t.type!=="text")])}function se(n,e){let t=Math.floor(n.length/1024),o=n.slice(0,k),r=n.length>k,s=`<persisted-output>
|
|
229
229
|
`;return s+=`Output too large (${String(t)}KB). Full content saved to:
|
|
230
230
|
${e}
|
|
231
231
|
|
|
232
232
|
`,s+=`Preview (first 2KB):
|
|
233
233
|
${o}`,r&&(s+=`
|
|
234
234
|
...`),s+=`
|
|
235
|
-
</persisted-output>`,s}function re(n,e,t,o){if(n!=="ReadFile"||!e)return!1;let r=e.file_path;return typeof r!="string"||!r?!1:Z(r).startsWith(Z(oe(t,o)))}function ie(n,e,t,o){let r=n.reduce((i,l)=>i+l.content.length,0);if(r<=ee)return;let s=n.toSorted((i,l)=>l.content.length-i.content.length);for(let i of s){if(r<=ee)break;if(o?.has(i.toolUseId))continue;let l=i.content;if(l.length<=
|
|
236
|
-
`+
|
|
237
|
-
`)),this.announcedDeferred=
|
|
238
|
-
`+c)}await this.fireLifecycle("turn_start"),await this.fireLifecycle("pre_send");let
|
|
235
|
+
</persisted-output>`,s}function re(n,e,t,o){if(n!=="ReadFile"||!e)return!1;let r=e.file_path;return typeof r!="string"||!r?!1:Z(r).startsWith(Z(oe(t,o)))}function ie(n,e,t,o){let r=n.reduce((i,l)=>i+l.content.length,0);if(r<=ee)return;let s=n.toSorted((i,l)=>l.content.length-i.content.length);for(let i of s){if(r<=ee)break;if(o?.has(i.toolUseId))continue;let l=i.content;if(l.length<=k)continue;let d;try{d=ne(e,t,i.toolUseId,l)}catch{continue}let u=se(l,d);r-=l.length-u.length,P(i,u)}}function ae(n,e,t,o){let r;try{r=ne(n,e,t,o)}catch{return o}return se(o,r)}var Te=y({module:"agent"}),E=class{pending=[];registry;ctx;constructor(e,t){this.registry=e,this.ctx=t}submit(e,t,o){this.pending.push({toolId:e,toolName:t,arguments:o})}async collectResults(){let e=[...this.pending];this.pending=[];let t=e.map(async o=>{let r=this.registry.get(o.toolName),s=Date.now();if(!r)return{toolId:o.toolId,toolName:o.toolName,result:{output:`Error: unknown tool '${o.toolName}'`,isError:!0},elapsed:0};try{let i=await r.execute(this.ctx,o.arguments);return{toolId:o.toolId,toolName:o.toolName,result:i,elapsed:(Date.now()-s)/1e3}}catch(i){return Te.error({err:i},"agent operation failed"),{toolId:o.toolId,toolName:o.toolName,result:{output:`Error executing ${o.toolName}: ${F(i)}`,isError:!0},elapsed:(Date.now()-s)/1e3}}});return Promise.all(t)}hasPending(){return this.pending.length>0}};var xe=64e3,le=3,Ie=5e4,ce="The following deferred tools are available via ToolSearch.",he=class{announcedDeferred=[];client;registry;checker;conversation;workDir;sessionId;sessionFilePath;hookEngine;fileHistory;fileStateCache;abortSignal;contextWindow;maxOutput;recoveryState;maxIterations;notificationFn;onLoopComplete;compactTracking=new B;onPermissionRequest;toolFilter;coordinatorActiveFn;activeSkills;instructions;memoryContent;skillSection;skillDeltaFn;memoryRecallPromise;memoryRecallConsumed=!1;memoryRecallSettled=!1;memoryRecallValue;onMemoriesSurfaced;constructor(e){this.client=e.client,this.registry=e.registry,this.checker=e.checker,this.conversation=e.conversation,this.workDir=e.workDir,this.sessionId=e.sessionId??"",this.sessionFilePath=e.sessionId?U(e.workDir,e.sessionId):"",this.hookEngine=e.hookEngine,this.fileHistory=e.fileHistory,this.fileStateCache=e.fileStateCache,this.abortSignal=e.abortSignal,this.contextWindow=e.contextWindow??2e5,this.maxOutput=e.maxOutput??8192,this.recoveryState=e.recoveryState??new S,this.maxIterations=e.maxIterations??0,this.notificationFn=e.notificationFn,this.onLoopComplete=e.onLoopComplete,this.onPermissionRequest=e.onPermissionRequest,this.activeSkills=e.activeSkills??new Map,this.toolFilter=e.toolFilter,this.coordinatorActiveFn=e.coordinatorActiveFn,this.instructions=e.instructions??"",this.memoryContent=e.memoryContent??"",this.skillSection=e.skillSection??"",this.skillDeltaFn=e.skillDeltaFn,this.memoryRecallPromise=e.memoryRecallPromise,this.onMemoriesSurfaced=e.onMemoriesSurfaced,this.memoryRecallPromise?.then(t=>{this.memoryRecallValue=t,this.memoryRecallSettled=!0},()=>{this.memoryRecallSettled=!0})}async*run(){let e=this.registry.getAllSchemas();this.toolFilter&&(e=e.filter(i=>this.toolFilter?.(i.name)));let t=this.registry.listTools().map(i=>i.name),o=!1,r=0,s=0;await this.fireLifecycle("session_start");try{let i=!0;for(;i;){if(s++,this.maxIterations>0&&s>this.maxIterations){yield{type:"error",error:new Error(`Agent reached maximum iterations (${String(this.maxIterations)})`)};return}let l="",d=[],u=[],g="end_turn",p=null;if(this.checker.mode==="plan"){let c=z(this.workDir);this.checker.planFilePath=c,this.conversation.addSystemReminder(Q(c,X(this.workDir),s))}this.coordinatorActiveFn?.()&&this.conversation.addSystemReminder(J(s));let v=this.registry.getDeferredToolNames();if(v.length>0&&(v.length!==this.announcedDeferred.length||v.some((a,w)=>a!==this.announcedDeferred[w])||!this.conversation.hasReminderContaining(ce))){let a=ce+' Their schemas are NOT loaded - use ToolSearch with query "select:<name>[,<name>...]" to load tool schemas';a+=this.registry.mcpLoadingMode==="dispatch"?", then invoke them with the mcp_call tool":" before calling them",this.conversation.addSystemReminder(a+`:
|
|
236
|
+
`+v.join(`
|
|
237
|
+
`)),this.announcedDeferred=v}if(this.hookEngine)for(let c of this.hookEngine.drainNotifications())this.conversation.addSystemReminder(c);if(this.notificationFn)for(let c of this.notificationFn())this.conversation.addSystemReminder(c);if(this.skillDeltaFn){let c=this.skillDeltaFn();c&&this.conversation.addSystemReminder(`The following skills became available:
|
|
238
|
+
`+c)}await this.fireLifecycle("turn_start"),await this.fireLifecycle("pre_send");let b=await Y(this.conversation,this.client,this.contextWindow,this.maxOutput,this.compactTracking,this.recoveryState,t,e,this.sessionFilePath);b.message&&(yield{type:"compact",message:b.message,boundary:b.boundary}),b.compacted&&this.conversation.injectLongTermMemory(this.instructions,this.memoryContent,this.skillSection);try{let c=this.client.stream(this.conversation,e,this.abortSignal);for await(let a of c){if(this.abortSignal?.aborted){i=!1;break}switch(a.type){case"text_delta":l+=a.text,yield{type:"stream_text",text:a.text};break;case"thinking_delta":yield{type:"thinking_text",text:a.text};break;case"thinking_complete":d.push({thinking:a.thinking,signature:a.signature}),yield{type:"thinking_complete",thinking:a.thinking,signature:a.signature};break;case"tool_call_start":break;case"tool_call_complete":u.push({toolUseId:a.toolId,toolName:a.toolName,arguments:a.arguments}),yield{type:"tool_use",toolName:a.toolName,toolId:a.toolId,args:a.arguments};break;case"stream_end":g=a.stopReason,p=a.usage,yield{type:"usage",usage:a.usage};break}}}catch(c){if(this.abortSignal?.aborted){yield{type:"loop_complete",stopReason:"interrupted"};return}if(c instanceof L)try{let a=await j(this.conversation,this.client,this.recoveryState,t,e,this.sessionFilePath);this.conversation.clearUsageAnchor(),this.conversation.injectLongTermMemory(this.instructions,this.memoryContent,this.skillSection),yield{type:"compact",message:"Auto-compacted due to context length: "+a.message,boundary:a.boundary};continue}catch{yield{type:"error",error:c};return}if(c instanceof M){let a=_e(T(A(c),"retryAfter"));if(yield{type:"retry",reason:"rate limited",delay:a},await this.interruptibleSleep(a)){yield{type:"loop_complete",stopReason:"interrupted"};return}continue}yield{type:"error",error:c instanceof Error?c:new Error(JSON.stringify(c))};return}if(this.abortSignal?.aborted){l&&(this.conversation.addAssistantFull(l,d,[]),this.persistLastMessage()),yield{type:"loop_complete",stopReason:"interrupted"};return}if(await this.fireLifecycle("post_receive",l),g==="max_tokens")if(o){if(r<le){r++,this.conversation.addAssistantFull(l,d,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Break remaining work into smaller pieces."),yield{type:"retry",reason:`max_tokens recovery ${String(r)}/${String(le)}`,delay:0};continue}}else{this.client.setMaxOutputTokens?.(xe),o=!0,l&&(this.conversation.addAssistantFull(l,d,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Do not apologize or repeat previous content. Pick up mid-thought if needed.")),yield{type:"retry",reason:"max_tokens escalation",delay:0};continue}else r=0;if(this.conversation.addAssistantFull(l,d,u),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),u.length>0){let c=await this.executeTools(u);for(let h of c)yield h;let a=new Set;for(let h of u)re(h.toolName,h.arguments,this.workDir,this.sessionId)&&a.add(h.toolUseId);let w=[];for(let h of c)if(h.type==="tool_result"){let f={toolUseId:h.toolId,content:h.output,...h.contentBlocks?.length?{contentBlocks:h.contentBlocks}:{},isError:h.isError};if(f.content.length>Ie&&!a.has(h.toolId)){let R=ae(this.workDir,this.sessionId,h.toolId,f.content);R!==f.content&&P(f,R),a.add(h.toolId)}w.push(f)}ie(w,this.workDir,this.sessionId,a);let ue=u.some(h=>{if(h.toolName!=="ExitPlanMode")return!1;let f=c.find(R=>R.type==="tool_result"&&R.toolId===h.toolUseId);return f?.type==="tool_result"&&!f.isError});if(this.conversation.addToolResultsMessage(w),this.persistLastMessage(),this.abortSignal?.aborted){yield{type:"turn_complete"},yield{type:"loop_complete",stopReason:"interrupted"};return}if(this.memoryRecallPromise&&!this.memoryRecallConsumed&&this.memoryRecallSettled){let h=this.memoryRecallValue;h?.reminder&&(this.conversation.addSystemReminder(h.reminder),this.onMemoriesSurfaced?.(h.paths)),this.memoryRecallConsumed=!0}if(ue){yield{type:"turn_complete"},yield{type:"loop_complete",stopReason:"end_turn"};return}yield{type:"turn_complete"},await this.fireLifecycle("turn_end")}else{if(i=!1,this.fileHistory){let c=l.length>60?l.slice(0,60)+"...":l;this.fileHistory.makeSnapshot(this.conversation.len(),c)}if(yield{type:"loop_complete",stopReason:g},this.onLoopComplete)try{this.onLoopComplete(this.conversation)}catch{}}}}finally{await this.fireLifecycle("session_end")}}async fireLifecycle(e,t){if(!this.hookEngine)return;let o=await this.hookEngine.fire(e,{event:e,message:t});for(let r of o)r.output&&this.hookEngine.recordNotification(r.output)}interruptibleSleep(e){return new Promise(t=>{if(this.abortSignal?.aborted){t(!0);return}let o=()=>{clearTimeout(r),t(!0)},r=setTimeout(()=>{this.abortSignal?.removeEventListener("abort",o),t(!1)},e);this.abortSignal?.addEventListener("abort",o,{once:!0})})}async executeTools(e){let t=[],o=this.partitionToolCalls(e);for(let r of o){let s=await this.executeBatch(r.blocks,r.concurrent&&r.blocks.length>1);t.push(...s)}return t}partitionToolCalls(e){let t=[];for(let o of e){let r=this.registry.get(o.toolName),s=r?r.isConcurrencySafe?.(o.arguments??{})??r.category==="read":!1;s&&t.length>0&&t[t.length-1].concurrent?t[t.length-1].blocks.push(o):t.push({concurrent:s,blocks:[o]})}return t}async executeBatch(e,t){let o=[],r=new E(this.registry,{workDir:this.workDir,abortSignal:this.abortSignal,fileHistory:this.fileHistory,fileStateCache:this.fileStateCache});for(let s of e){if(this.abortSignal?.aborted){o.push({type:"tool_result",toolName:s.toolName,toolId:s.toolUseId,output:"Error: command interrupted",isError:!0,elapsed:0});continue}if(this.hookEngine){let u=await this.hookEngine.firePreToolHooks(s.toolName,s.arguments);if(u.rejected){o.push({type:"tool_result",toolName:s.toolName,toolId:s.toolUseId,output:`Rejected by hook: ${u.reason}`,isError:!0,elapsed:0});continue}}let l=this.registry.get(s.toolName)?.category??"command",d=this.checker.check(s.toolName,l,s.arguments);if(d.effect==="deny"){o.push({type:"tool_result",toolName:s.toolName,toolId:s.toolUseId,output:`Permission denied: ${d.reason}. This operation has been blocked by the security policy. Inform the user that the command was denied; do not describe what the command would do.`,isError:!0,elapsed:0});continue}if(d.effect==="ask"&&this.onPermissionRequest){let u=await this.onPermissionRequest(s.toolName,s.arguments,d);if(u==="deny"){o.push({type:"tool_result",toolName:s.toolName,toolId:s.toolUseId,output:C,isError:!0,elapsed:0});continue}u==="allowAlways"&&this.checker.allowAlways(s.toolName,s.arguments)}if(r.submit(s.toolUseId,s.toolName,s.arguments),!t){let u=await r.collectResults();for(let g of u)await this.processToolResult(g,e,o)}}if(t){let s=await r.collectResults();for(let i of s)await this.processToolResult(i,e,o)}return o}async processToolResult(e,t,o){if(!e.result.isError&&e.toolName==="ReadFile"&&!e.result.contentBlocks?.length){let r=t.find(i=>i.toolUseId===e.toolId),s=T(r?.arguments??{},"file_path");s&&this.recoveryState.recordFileRead(s,e.result.output)}if(o.push({type:"tool_result",toolName:e.toolName,toolId:e.toolId,output:e.result.output,...e.result.contentBlocks?.length?{contentBlocks:e.result.contentBlocks}:{},isError:e.result.isError,elapsed:e.elapsed}),this.hookEngine){let r=await this.hookEngine.fire("post_tool_use",{event:"post_tool_use",toolName:e.toolName,message:e.result.output});for(let s of r)s.output&&this.hookEngine.recordNotification(s.output)}}persistLastMessage(){if(!this.workDir||!this.sessionId)return;let e=this.conversation.getMessages();if(e.length===0)return;let t=e[e.length-1];W(this.workDir,this.sessionId,{role:t.role,content:t.content,timestamp:Math.floor(Date.now()/1e3),...t.toolUses?.length?{tool_uses:D(t.toolUses)}:{},...t.toolResults?.length?{tool_results:O(t.toolResults)}:{}})}};function _e(n){if(!n)return 5e3;let e=parseInt(n,10);return Number.isNaN(e)?5e3:e*1e3}export{S as a,z as b,Ne as c,X as d,Me as e,Oe as f,Ue as g,He as h,he as i};
|
|
@@ -1002,7 +1002,15 @@ var Agent = class {
|
|
|
1002
1002
|
}
|
|
1003
1003
|
}
|
|
1004
1004
|
applyBudget(toolResults, this.workDir, this.sessionId, exemptIds);
|
|
1005
|
-
const
|
|
1005
|
+
const exitPlanSucceeded = toolUses.some((tu) => {
|
|
1006
|
+
if (tu.toolName !== "ExitPlanMode") {
|
|
1007
|
+
return false;
|
|
1008
|
+
}
|
|
1009
|
+
const result = results.find(
|
|
1010
|
+
(r) => r.type === "tool_result" && r.toolId === tu.toolUseId
|
|
1011
|
+
);
|
|
1012
|
+
return result?.type === "tool_result" && !result.isError;
|
|
1013
|
+
});
|
|
1006
1014
|
this.conversation.addToolResultsMessage(toolResults);
|
|
1007
1015
|
this.persistLastMessage();
|
|
1008
1016
|
if (this.abortSignal?.aborted) {
|
|
@@ -1018,7 +1026,7 @@ var Agent = class {
|
|
|
1018
1026
|
}
|
|
1019
1027
|
this.memoryRecallConsumed = true;
|
|
1020
1028
|
}
|
|
1021
|
-
if (
|
|
1029
|
+
if (exitPlanSucceeded) {
|
|
1022
1030
|
yield { type: "turn_complete" };
|
|
1023
1031
|
yield { type: "loop_complete", stopReason: "end_turn" };
|
|
1024
1032
|
return;
|
package/dist/lib/index.js
CHANGED
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
resetPlanPath,
|
|
19
19
|
savePlan,
|
|
20
20
|
toDisplayPreview
|
|
21
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-RKJYTYQM.js";
|
|
22
22
|
import {
|
|
23
23
|
AnthropicClient,
|
|
24
24
|
CHARS_PER_TOKEN,
|
|
@@ -2609,7 +2609,7 @@ var PackageJsonSchema = z5.object({
|
|
|
2609
2609
|
});
|
|
2610
2610
|
function resolveVersion() {
|
|
2611
2611
|
if (true) {
|
|
2612
|
-
return "0.0.
|
|
2612
|
+
return "0.0.26";
|
|
2613
2613
|
}
|
|
2614
2614
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
2615
2615
|
for (const levels of ["..", "../.."]) {
|
|
@@ -9806,6 +9806,12 @@ var ExitPlanModeTool = class {
|
|
|
9806
9806
|
}
|
|
9807
9807
|
execute(_ctx, _args) {
|
|
9808
9808
|
if (this.isPlanMode && !this.isPlanMode()) {
|
|
9809
|
+
if (this.planExists?.()) {
|
|
9810
|
+
return Promise.resolve({
|
|
9811
|
+
output: "You are not in plan mode. This tool is only for exiting plan mode after writing a plan. You can call AskUserQuestion tool to ask the user whether to execute the plan.",
|
|
9812
|
+
isError: true
|
|
9813
|
+
});
|
|
9814
|
+
}
|
|
9809
9815
|
return Promise.resolve({
|
|
9810
9816
|
output: "You are not in plan mode. This tool is only for exiting plan mode after writing a plan.",
|
|
9811
9817
|
isError: true
|
|
@@ -10100,7 +10106,7 @@ async function createRemoteAgent(opts) {
|
|
|
10100
10106
|
throw new Error("no llm client (provider not initialized)");
|
|
10101
10107
|
}
|
|
10102
10108
|
const { PermissionChecker: PC } = await import("./checker-6BW4222R.js");
|
|
10103
|
-
const { Agent: AgentClass } = await import("./agent-
|
|
10109
|
+
const { Agent: AgentClass } = await import("./agent-U7MIUCKT.js");
|
|
10104
10110
|
const subConv = new ConversationManager();
|
|
10105
10111
|
subConv.addUserMessage(prompt);
|
|
10106
10112
|
const subAgent = new AgentClass({
|