@linzumi/cli 1.0.197 → 1.0.199

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.
@@ -1,13 +1,14 @@
1
1
  import { createRequire as __linzumiBundleCreateRequire } from 'node:module';
2
2
  const require = __linzumiBundleCreateRequire(import.meta.url);
3
- var Zx=Object.create;var Tl=Object.defineProperty;var qx=Object.getOwnPropertyDescriptor;var Lx=Object.getOwnPropertyNames;var Vx=Object.getPrototypeOf,Ux=Object.prototype.hasOwnProperty;var E=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),zl=(e,t)=>{for(var r in t)Tl(e,r,{get:t[r],enumerable:!0})},Fx=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Lx(t))!Ux.call(e,i)&&i!==r&&Tl(e,i,{get:()=>t[i],enumerable:!(n=qx(t,i))||n.enumerable});return e};var vh=(e,t,r)=>(r=e!=null?Zx(Vx(e)):{},Fx(t||!e||!e.__esModule?Tl(r,"default",{value:e,enumerable:!0}):r,e));var Os=E(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.regexpCode=se.getEsmExportName=se.getProperty=se.safeStringify=se.stringify=se.strConcat=se.addCodeArg=se.str=se._=se.nil=se._Code=se.Name=se.IDENTIFIER=se._CodeOrName=void 0;var Es=class{};se._CodeOrName=Es;se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var vi=class extends Es{constructor(t){if(super(),!se.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};se.Name=vi;var sr=class extends Es{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof vi&&(r[n.str]=(r[n.str]||0)+1),r),{})}};se._Code=sr;se.nil=new sr("");function jb(e,...t){let r=[e[0]],n=0;for(;n<t.length;)wm(r,t[n]),r.push(e[++n]);return new sr(r)}se._=jb;var bm=new sr("+");function Nb(e,...t){let r=[As(e[0])],n=0;for(;n<t.length;)r.push(bm),wm(r,t[n]),r.push(bm,As(e[++n]));return CO(r),new sr(r)}se.str=Nb;function wm(e,t){t instanceof sr?e.push(...t._items):t instanceof vi?e.push(t):e.push(jO(t))}se.addCodeArg=wm;function CO(e){let t=1;for(;t<e.length-1;){if(e[t]===bm){let r=RO(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function RO(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof vi||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof vi))return`"${e}${t.slice(1)}`}function IO(e,t){return t.emptyStr()?e:e.emptyStr()?t:Nb`${e}${t}`}se.strConcat=IO;function jO(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:As(Array.isArray(e)?e.join(","):e)}function NO(e){return new sr(As(e))}se.stringify=NO;function As(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}se.safeStringify=As;function MO(e){return typeof e=="string"&&se.IDENTIFIER.test(e)?new sr(`.${e}`):jb`[${e}]`}se.getProperty=MO;function DO(e){if(typeof e=="string"&&se.IDENTIFIER.test(e))return new sr(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}se.getEsmExportName=DO;function ZO(e){return new sr(e.toString())}se.regexpCode=ZO});var Sm=E(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.ValueScope=Dt.ValueScopeName=Dt.Scope=Dt.varKinds=Dt.UsedValueState=void 0;var Mt=Os(),xm=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Nc;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Nc||(Dt.UsedValueState=Nc={}));Dt.varKinds={const:new Mt.Name("const"),let:new Mt.Name("let"),var:new Mt.Name("var")};var Mc=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Mt.Name?t:this.name(t)}name(t){return new Mt.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Dt.Scope=Mc;var Dc=class extends Mt.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Mt._)`.${new Mt.Name(r)}[${n}]`}};Dt.ValueScopeName=Dc;var qO=(0,Mt._)`\n`,km=class extends Mc{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?qO:Mt.nil}}get(){return this._scope}name(t){return new Dc(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(t),{prefix:o}=i,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let u=a.get(s);if(u)return u}else a=this._values[o]=new Map;a.set(s,i);let l=this._scope[o]||(this._scope[o]=[]),c=l.length;return l[c]=r.ref,i.setValue(r,{property:o,itemIndex:c}),i}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Mt._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(t,r,n={},i){let o=Mt.nil;for(let s in t){let a=t[s];if(!a)continue;let l=n[s]=n[s]||new Map;a.forEach(c=>{if(l.has(c))return;l.set(c,Nc.Started);let u=r(c);if(u){let d=this.opts.es5?Dt.varKinds.var:Dt.varKinds.const;o=(0,Mt._)`${o}${d} ${c} = ${u};${this.opts._n}`}else if(u=i?.(c))o=(0,Mt._)`${o}${u}${this.opts._n}`;else throw new xm(c);l.set(c,Nc.Completed)})}return o}};Dt.ValueScope=km});var H=E(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.or=K.and=K.not=K.CodeGen=K.operators=K.varKinds=K.ValueScopeName=K.ValueScope=K.Scope=K.Name=K.regexpCode=K.stringify=K.getProperty=K.nil=K.strConcat=K.str=K._=void 0;var ie=Os(),yr=Sm(),On=Os();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return On._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return On.str}});Object.defineProperty(K,"strConcat",{enumerable:!0,get:function(){return On.strConcat}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return On.nil}});Object.defineProperty(K,"getProperty",{enumerable:!0,get:function(){return On.getProperty}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return On.stringify}});Object.defineProperty(K,"regexpCode",{enumerable:!0,get:function(){return On.regexpCode}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return On.Name}});var Vc=Sm();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return Vc.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return Vc.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return Vc.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return Vc.varKinds}});K.operators={GT:new ie._Code(">"),GTE:new ie._Code(">="),LT:new ie._Code("<"),LTE:new ie._Code("<="),EQ:new ie._Code("==="),NEQ:new ie._Code("!=="),NOT:new ie._Code("!"),OR:new ie._Code("||"),AND:new ie._Code("&&"),ADD:new ie._Code("+")};var on=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},$m=class extends on{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?yr.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=fo(this.rhs,t,r)),this}get names(){return this.rhs instanceof ie._CodeOrName?this.rhs.names:{}}},Zc=class extends on{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof ie.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=fo(this.rhs,t,r),this}get names(){let t=this.lhs instanceof ie.Name?{}:{...this.lhs.names};return Lc(t,this.rhs)}},Tm=class extends Zc{constructor(t,r,n,i){super(t,n,i),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},zm=class extends on{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Em=class extends on{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Am=class extends on{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Om=class extends on{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=fo(this.code,t,r),this}get names(){return this.code instanceof ie._CodeOrName?this.code.names:{}}},Ps=class extends on{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(t,r)||(LO(t,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>xi(t,r.names),{})}},sn=class extends Ps{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Pm=class extends Ps{},uo=class extends sn{};uo.kind="else";var bi=class e extends sn{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new uo(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Mb(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=fo(this.condition,t,r),this}get names(){let t=super.names;return Lc(t,this.condition),this.else&&xi(t,this.else.names),t}};bi.kind="if";var wi=class extends sn{};wi.kind="for";var Cm=class extends wi{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=fo(this.iteration,t,r),this}get names(){return xi(super.names,this.iteration.names)}},Rm=class extends wi{constructor(t,r,n,i){super(),this.varKind=t,this.name=r,this.from=n,this.to=i}render(t){let r=t.es5?yr.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(t)}get names(){let t=Lc(super.names,this.from);return Lc(t,this.to)}},qc=class extends wi{constructor(t,r,n,i){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=i}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=fo(this.iterable,t,r),this}get names(){return xi(super.names,this.iterable.names)}},Cs=class extends sn{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};Cs.kind="func";var Rs=class extends Ps{render(t){return"return "+super.render(t)}};Rs.kind="return";var Im=class extends sn{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,i;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(i=this.finally)===null||i===void 0||i.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&xi(t,this.catch.names),this.finally&&xi(t,this.finally.names),t}},Is=class extends sn{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Is.kind="catch";var js=class extends sn{render(t){return"finally"+super.render(t)}};js.kind="finally";var jm=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
- `:""},this._extScope=t,this._scope=new yr.Scope({parent:t}),this._nodes=[new Pm]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new $m(t,o,n)),o}const(t,r,n){return this._def(yr.varKinds.const,t,r,n)}let(t,r,n){return this._def(yr.varKinds.let,t,r,n)}var(t,r,n){return this._def(yr.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Zc(t,r,n))}add(t,r){return this._leafNode(new Tm(t,K.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==ie.nil&&this._leafNode(new Om(t)),this}object(...t){let r=["{"];for(let[n,i]of t)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,ie.addCodeArg)(r,i));return r.push("}"),new ie._Code(r)}if(t,r,n){if(this._blockNode(new bi(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new bi(t))}else(){return this._elseNode(new uo)}endIf(){return this._endBlockNode(bi,uo)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Cm(t),r)}forRange(t,r,n,i,o=this.opts.es5?yr.varKinds.var:yr.varKinds.let){let s=this._scope.toName(t);return this._for(new Rm(o,s,r,n),()=>i(s))}forOf(t,r,n,i=yr.varKinds.const){let o=this._scope.toName(t);if(this.opts.es5){let s=r instanceof ie.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ie._)`${s}.length`,a=>{this.var(o,(0,ie._)`${s}[${a}]`),n(o)})}return this._for(new qc("of",i,o,r),()=>n(o))}forIn(t,r,n,i=this.opts.es5?yr.varKinds.var:yr.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,ie._)`Object.keys(${r})`,n);let o=this._scope.toName(t);return this._for(new qc("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(wi)}label(t){return this._leafNode(new zm(t))}break(t){return this._leafNode(new Em(t))}return(t){let r=new Rs;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Rs)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Im;if(this._blockNode(i),this.code(t),r){let o=this.name("e");this._currNode=i.catch=new Is(o),r(o)}return n&&(this._currNode=i.finally=new js,this.code(n)),this._endBlockNode(Is,js)}throw(t){return this._leafNode(new Am(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=ie.nil,n,i){return this._blockNode(new Cs(t,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Cs)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof bi))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};K.CodeGen=jm;function xi(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Lc(e,t){return t instanceof ie._CodeOrName?xi(e,t.names):e}function fo(e,t,r){if(e instanceof ie.Name)return n(e);if(!i(e))return e;return new ie._Code(e._items.reduce((o,s)=>(s instanceof ie.Name&&(s=n(s)),s instanceof ie._Code?o.push(...s._items):o.push(s),o),[]));function n(o){let s=r[o.str];return s===void 0||t[o.str]!==1?o:(delete t[o.str],s)}function i(o){return o instanceof ie._Code&&o._items.some(s=>s instanceof ie.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function LO(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Mb(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,ie._)`!${Nm(e)}`}K.not=Mb;var VO=Db(K.operators.AND);function UO(...e){return e.reduce(VO)}K.and=UO;var FO=Db(K.operators.OR);function GO(...e){return e.reduce(FO)}K.or=GO;function Db(e){return(t,r)=>t===ie.nil?r:r===ie.nil?t:(0,ie._)`${Nm(t)} ${e} ${Nm(r)}`}function Nm(e){return e instanceof ie.Name?e:(0,ie._)`(${e})`}});var ae=E(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.checkStrictMode=X.getErrorPath=X.Type=X.useFunc=X.setEvaluated=X.evaluatedPropsToName=X.mergeEvaluated=X.eachItem=X.unescapeJsonPointer=X.escapeJsonPointer=X.escapeFragment=X.unescapeFragment=X.schemaRefOrVal=X.schemaHasRulesButRef=X.schemaHasRules=X.checkUnknownRules=X.alwaysValidSchema=X.toHash=void 0;var ye=H(),BO=Os();function JO(e){let t={};for(let r of e)t[r]=!0;return t}X.toHash=JO;function WO(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Lb(e,t),!Vb(t,e.self.RULES.all))}X.alwaysValidSchema=WO;function Lb(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let i=n.RULES.keywords;for(let o in t)i[o]||Gb(e,`unknown keyword: "${o}"`)}X.checkUnknownRules=Lb;function Vb(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}X.schemaHasRules=Vb;function HO(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}X.schemaHasRulesButRef=HO;function KO({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ye._)`${r}`}return(0,ye._)`${e}${t}${(0,ye.getProperty)(n)}`}X.schemaRefOrVal=KO;function QO(e){return Ub(decodeURIComponent(e))}X.unescapeFragment=QO;function XO(e){return encodeURIComponent(Dm(e))}X.escapeFragment=XO;function Dm(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=Dm;function Ub(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=Ub;function YO(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}X.eachItem=YO;function Zb({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,o,s,a)=>{let l=s===void 0?o:s instanceof ye.Name?(o instanceof ye.Name?e(i,o,s):t(i,o,s),s):o instanceof ye.Name?(t(i,s,o),o):r(o,s);return a===ye.Name&&!(l instanceof ye.Name)?n(i,l):l}}X.mergeEvaluated={props:Zb({mergeNames:(e,t,r)=>e.if((0,ye._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,ye._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,ye._)`${r} || {}`).code((0,ye._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,ye._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,ye._)`${r} || {}`),Zm(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Fb}),items:Zb({mergeNames:(e,t,r)=>e.if((0,ye._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,ye._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,ye._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,ye._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Fb(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,ye._)`{}`);return t!==void 0&&Zm(e,r,t),r}X.evaluatedPropsToName=Fb;function Zm(e,t,r){Object.keys(r).forEach(n=>e.assign((0,ye._)`${t}${(0,ye.getProperty)(n)}`,!0))}X.setEvaluated=Zm;var qb={};function eP(e,t){return e.scopeValue("func",{ref:t,code:qb[t.code]||(qb[t.code]=new BO._Code(t.code))})}X.useFunc=eP;var Mm;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Mm||(X.Type=Mm={}));function tP(e,t,r){if(e instanceof ye.Name){let n=t===Mm.Num;return r?n?(0,ye._)`"[" + ${e} + "]"`:(0,ye._)`"['" + ${e} + "']"`:n?(0,ye._)`"/" + ${e}`:(0,ye._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ye.getProperty)(e).toString():"/"+Dm(e)}X.getErrorPath=tP;function Gb(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}X.checkStrictMode=Gb});var an=E(qm=>{"use strict";Object.defineProperty(qm,"__esModule",{value:!0});var _t=H(),rP={data:new _t.Name("data"),valCxt:new _t.Name("valCxt"),instancePath:new _t.Name("instancePath"),parentData:new _t.Name("parentData"),parentDataProperty:new _t.Name("parentDataProperty"),rootData:new _t.Name("rootData"),dynamicAnchors:new _t.Name("dynamicAnchors"),vErrors:new _t.Name("vErrors"),errors:new _t.Name("errors"),this:new _t.Name("this"),self:new _t.Name("self"),scope:new _t.Name("scope"),json:new _t.Name("json"),jsonPos:new _t.Name("jsonPos"),jsonLen:new _t.Name("jsonLen"),jsonPart:new _t.Name("jsonPart")};qm.default=rP});var Ns=E(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.extendErrors=yt.resetErrorsCount=yt.reportExtraError=yt.reportError=yt.keyword$DataError=yt.keywordError=void 0;var oe=H(),Uc=ae(),Et=an();yt.keywordError={message:({keyword:e})=>(0,oe.str)`must pass "${e}" keyword validation`};yt.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,oe.str)`"${e}" keyword must be ${t} ($data)`:(0,oe.str)`"${e}" keyword is invalid ($data)`};function nP(e,t=yt.keywordError,r,n){let{it:i}=e,{gen:o,compositeRule:s,allErrors:a}=i,l=Wb(e,t,r);n??(s||a)?Bb(o,l):Jb(i,(0,oe._)`[${l}]`)}yt.reportError=nP;function iP(e,t=yt.keywordError,r){let{it:n}=e,{gen:i,compositeRule:o,allErrors:s}=n,a=Wb(e,t,r);Bb(i,a),o||s||Jb(n,Et.default.vErrors)}yt.reportExtraError=iP;function oP(e,t){e.assign(Et.default.errors,t),e.if((0,oe._)`${Et.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,oe._)`${Et.default.vErrors}.length`,t),()=>e.assign(Et.default.vErrors,null)))}yt.resetErrorsCount=oP;function sP({gen:e,keyword:t,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",i,Et.default.errors,a=>{e.const(s,(0,oe._)`${Et.default.vErrors}[${a}]`),e.if((0,oe._)`${s}.instancePath === undefined`,()=>e.assign((0,oe._)`${s}.instancePath`,(0,oe.strConcat)(Et.default.instancePath,o.errorPath))),e.assign((0,oe._)`${s}.schemaPath`,(0,oe.str)`${o.errSchemaPath}/${t}`),o.opts.verbose&&(e.assign((0,oe._)`${s}.schema`,r),e.assign((0,oe._)`${s}.data`,n))})}yt.extendErrors=sP;function Bb(e,t){let r=e.const("err",t);e.if((0,oe._)`${Et.default.vErrors} === null`,()=>e.assign(Et.default.vErrors,(0,oe._)`[${r}]`),(0,oe._)`${Et.default.vErrors}.push(${r})`),e.code((0,oe._)`${Et.default.errors}++`)}function Jb(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw((0,oe._)`new ${e.ValidationError}(${t})`):(r.assign((0,oe._)`${n}.errors`,t),r.return(!1))}var ki={keyword:new oe.Name("keyword"),schemaPath:new oe.Name("schemaPath"),params:new oe.Name("params"),propertyName:new oe.Name("propertyName"),message:new oe.Name("message"),schema:new oe.Name("schema"),parentSchema:new oe.Name("parentSchema")};function Wb(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,oe._)`{}`:aP(e,t,r)}function aP(e,t,r={}){let{gen:n,it:i}=e,o=[cP(i,r),lP(e,r)];return uP(e,t,o),n.object(...o)}function cP({errorPath:e},{instancePath:t}){let r=t?(0,oe.str)`${e}${(0,Uc.getErrorPath)(t,Uc.Type.Str)}`:e;return[Et.default.instancePath,(0,oe.strConcat)(Et.default.instancePath,r)]}function lP({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:(0,oe.str)`${t}/${e}`;return r&&(i=(0,oe.str)`${i}${(0,Uc.getErrorPath)(r,Uc.Type.Str)}`),[ki.schemaPath,i]}function uP(e,{params:t,message:r},n){let{keyword:i,data:o,schemaValue:s,it:a}=e,{opts:l,propertyName:c,topSchemaRef:u,schemaPath:d}=a;n.push([ki.keyword,i],[ki.params,typeof t=="function"?t(e):t||(0,oe._)`{}`]),l.messages&&n.push([ki.message,typeof r=="function"?r(e):r]),l.verbose&&n.push([ki.schema,s],[ki.parentSchema,(0,oe._)`${u}${d}`],[Et.default.data,o]),c&&n.push([ki.propertyName,c])}});var Kb=E(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.boolOrEmptySchema=mo.topBoolOrEmptySchema=void 0;var dP=Ns(),fP=H(),mP=an(),pP={message:"boolean schema is false"};function hP(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Hb(e,!1):typeof r=="object"&&r.$async===!0?t.return(mP.default.data):(t.assign((0,fP._)`${n}.errors`,null),t.return(!0))}mo.topBoolOrEmptySchema=hP;function gP(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Hb(e)):r.var(t,!0)}mo.boolOrEmptySchema=gP;function Hb(e,t){let{gen:r,data:n}=e,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,dP.reportError)(i,pP,void 0,t)}});var Lm=E(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.getRules=po.isJSONType=void 0;var _P=["string","number","integer","boolean","null","object","array"],yP=new Set(_P);function vP(e){return typeof e=="string"&&yP.has(e)}po.isJSONType=vP;function bP(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}po.getRules=bP});var Vm=E(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.shouldUseRule=Pn.shouldUseGroup=Pn.schemaHasRulesForType=void 0;function wP({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Qb(e,n)}Pn.schemaHasRulesForType=wP;function Qb(e,t){return t.rules.some(r=>Xb(e,r))}Pn.shouldUseGroup=Qb;function Xb(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}Pn.shouldUseRule=Xb});var Ms=E(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.reportTypeError=vt.checkDataTypes=vt.checkDataType=vt.coerceAndCheckDataType=vt.getJSONTypes=vt.getSchemaTypes=vt.DataType=void 0;var xP=Lm(),kP=Vm(),SP=Ns(),J=H(),Yb=ae(),ho;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(ho||(vt.DataType=ho={}));function $P(e){let t=ew(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}vt.getSchemaTypes=$P;function ew(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(xP.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}vt.getJSONTypes=ew;function TP(e,t){let{gen:r,data:n,opts:i}=e,o=zP(t,i.coerceTypes),s=t.length>0&&!(o.length===0&&t.length===1&&(0,kP.schemaHasRulesForType)(e,t[0]));if(s){let a=Fm(t,n,i.strictNumbers,ho.Wrong);r.if(a,()=>{o.length?EP(e,t,o):Gm(e)})}return s}vt.coerceAndCheckDataType=TP;var tw=new Set(["string","number","integer","boolean","null"]);function zP(e,t){return t?e.filter(r=>tw.has(r)||t==="array"&&r==="array"):[]}function EP(e,t,r){let{gen:n,data:i,opts:o}=e,s=n.let("dataType",(0,J._)`typeof ${i}`),a=n.let("coerced",(0,J._)`undefined`);o.coerceTypes==="array"&&n.if((0,J._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,J._)`${i}[0]`).assign(s,(0,J._)`typeof ${i}`).if(Fm(t,i,o.strictNumbers),()=>n.assign(a,i))),n.if((0,J._)`${a} !== undefined`);for(let c of r)(tw.has(c)||c==="array"&&o.coerceTypes==="array")&&l(c);n.else(),Gm(e),n.endIf(),n.if((0,J._)`${a} !== undefined`,()=>{n.assign(i,a),AP(e,a)});function l(c){switch(c){case"string":n.elseIf((0,J._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,J._)`"" + ${i}`).elseIf((0,J._)`${i} === null`).assign(a,(0,J._)`""`);return;case"number":n.elseIf((0,J._)`${s} == "boolean" || ${i} === null
5
- || (${s} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,J._)`+${i}`);return;case"integer":n.elseIf((0,J._)`${s} === "boolean" || ${i} === null
6
- || (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,J._)`+${i}`);return;case"boolean":n.elseIf((0,J._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,J._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,J._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,J._)`${s} === "string" || ${s} === "number"
7
- || ${s} === "boolean" || ${i} === null`).assign(a,(0,J._)`[${i}]`)}}}function AP({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,J._)`${t} !== undefined`,()=>e.assign((0,J._)`${t}[${r}]`,n))}function Um(e,t,r,n=ho.Correct){let i=n===ho.Correct?J.operators.EQ:J.operators.NEQ,o;switch(e){case"null":return(0,J._)`${t} ${i} null`;case"array":o=(0,J._)`Array.isArray(${t})`;break;case"object":o=(0,J._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=s((0,J._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=s();break;default:return(0,J._)`typeof ${t} ${i} ${e}`}return n===ho.Correct?o:(0,J.not)(o);function s(a=J.nil){return(0,J.and)((0,J._)`typeof ${t} == "number"`,a,r?(0,J._)`isFinite(${t})`:J.nil)}}vt.checkDataType=Um;function Fm(e,t,r,n){if(e.length===1)return Um(e[0],t,r,n);let i,o=(0,Yb.toHash)(e);if(o.array&&o.object){let s=(0,J._)`typeof ${t} != "object"`;i=o.null?s:(0,J._)`!${t} || ${s}`,delete o.null,delete o.array,delete o.object}else i=J.nil;o.number&&delete o.integer;for(let s in o)i=(0,J.and)(i,Um(s,t,r,n));return i}vt.checkDataTypes=Fm;var OP={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,J._)`{type: ${e}}`:(0,J._)`{type: ${t}}`};function Gm(e){let t=PP(e);(0,SP.reportError)(t,OP)}vt.reportTypeError=Gm;function PP(e){let{gen:t,data:r,schema:n}=e,i=(0,Yb.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var nw=E(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.assignDefaults=void 0;var go=H(),CP=ae();function RP(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)rw(e,i,r[i].default);else t==="array"&&Array.isArray(n)&&n.forEach((i,o)=>rw(e,o,i.default))}Fc.assignDefaults=RP;function rw(e,t,r){let{gen:n,compositeRule:i,data:o,opts:s}=e;if(r===void 0)return;let a=(0,go._)`${o}${(0,go.getProperty)(t)}`;if(i){(0,CP.checkStrictMode)(e,`default is ignored for: ${a}`);return}let l=(0,go._)`${a} === undefined`;s.useDefaults==="empty"&&(l=(0,go._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,go._)`${a} = ${(0,go.stringify)(r)}`)}});var ar=E(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.validateUnion=me.validateArray=me.usePattern=me.callValidateCode=me.schemaProperties=me.allSchemaProperties=me.noPropertyInData=me.propertyInData=me.isOwnProperty=me.hasPropFunc=me.reportMissingProp=me.checkMissingProp=me.checkReportMissingProp=void 0;var Te=H(),Bm=ae(),Cn=an(),IP=ae();function jP(e,t){let{gen:r,data:n,it:i}=e;r.if(Wm(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,Te._)`${t}`},!0),e.error()})}me.checkReportMissingProp=jP;function NP({gen:e,data:t,it:{opts:r}},n,i){return(0,Te.or)(...n.map(o=>(0,Te.and)(Wm(e,t,o,r.ownProperties),(0,Te._)`${i} = ${o}`)))}me.checkMissingProp=NP;function MP(e,t){e.setParams({missingProperty:t},!0),e.error()}me.reportMissingProp=MP;function iw(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Te._)`Object.prototype.hasOwnProperty`})}me.hasPropFunc=iw;function Jm(e,t,r){return(0,Te._)`${iw(e)}.call(${t}, ${r})`}me.isOwnProperty=Jm;function DP(e,t,r,n){let i=(0,Te._)`${t}${(0,Te.getProperty)(r)} !== undefined`;return n?(0,Te._)`${i} && ${Jm(e,t,r)}`:i}me.propertyInData=DP;function Wm(e,t,r,n){let i=(0,Te._)`${t}${(0,Te.getProperty)(r)} === undefined`;return n?(0,Te.or)(i,(0,Te.not)(Jm(e,t,r))):i}me.noPropertyInData=Wm;function ow(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}me.allSchemaProperties=ow;function ZP(e,t){return ow(t).filter(r=>!(0,Bm.alwaysValidSchema)(e,t[r]))}me.schemaProperties=ZP;function qP({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:o},it:s},a,l,c){let u=c?(0,Te._)`${e}, ${t}, ${n}${i}`:t,d=[[Cn.default.instancePath,(0,Te.strConcat)(Cn.default.instancePath,o)],[Cn.default.parentData,s.parentData],[Cn.default.parentDataProperty,s.parentDataProperty],[Cn.default.rootData,Cn.default.rootData]];s.opts.dynamicRef&&d.push([Cn.default.dynamicAnchors,Cn.default.dynamicAnchors]);let h=(0,Te._)`${u}, ${r.object(...d)}`;return l!==Te.nil?(0,Te._)`${a}.call(${l}, ${h})`:(0,Te._)`${a}(${h})`}me.callValidateCode=qP;var LP=(0,Te._)`new RegExp`;function VP({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,o=i(r,n);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,Te._)`${i.code==="new RegExp"?LP:(0,IP.useFunc)(e,i)}(${r}, ${n})`})}me.usePattern=VP;function UP(e){let{gen:t,data:r,keyword:n,it:i}=e,o=t.name("valid");if(i.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(o,!0),s(()=>t.break()),o;function s(a){let l=t.const("len",(0,Te._)`${r}.length`);t.forRange("i",0,l,c=>{e.subschema({keyword:n,dataProp:c,dataPropType:Bm.Type.Num},o),t.if((0,Te.not)(o),a)})}}me.validateArray=UP;function FP(e){let{gen:t,schema:r,keyword:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,Bm.alwaysValidSchema)(i,l))&&!i.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((l,c)=>{let u=e.subschema({keyword:n,schemaProp:c,compositeRule:!0},a);t.assign(s,(0,Te._)`${s} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,Te.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}me.validateUnion=FP});var cw=E(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.validateKeywordUsage=Zr.validSchemaType=Zr.funcKeywordCode=Zr.macroKeywordCode=void 0;var At=H(),Si=an(),GP=ar(),BP=Ns();function JP(e,t){let{gen:r,keyword:n,schema:i,parentSchema:o,it:s}=e,a=t.macro.call(s.self,i,o,s),l=aw(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let c=r.name("valid");e.subschema({schema:a,schemaPath:At.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},c),e.pass(c,()=>e.error(!0))}Zr.macroKeywordCode=JP;function WP(e,t){var r;let{gen:n,keyword:i,schema:o,parentSchema:s,$data:a,it:l}=e;KP(l,t);let c=!a&&t.compile?t.compile.call(l.self,o,s,l):t.validate,u=aw(n,i,c),d=n.let("valid");e.block$data(d,h),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function h(){if(t.errors===!1)f(),t.modifying&&sw(e),g(()=>e.error());else{let y=t.async?p():m();t.modifying&&sw(e),g(()=>HP(e,y))}}function p(){let y=n.let("ruleErrs",null);return n.try(()=>f((0,At._)`await `),v=>n.assign(d,!1).if((0,At._)`${v} instanceof ${l.ValidationError}`,()=>n.assign(y,(0,At._)`${v}.errors`),()=>n.throw(v))),y}function m(){let y=(0,At._)`${u}.errors`;return n.assign(y,null),f(At.nil),y}function f(y=t.async?(0,At._)`await `:At.nil){let v=l.opts.passContext?Si.default.this:Si.default.self,b=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,At._)`${y}${(0,GP.callValidateCode)(e,u,v,b)}`,t.modifying)}function g(y){var v;n.if((0,At.not)((v=t.valid)!==null&&v!==void 0?v:d),y)}}Zr.funcKeywordCode=WP;function sw(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,At._)`${n.parentData}[${n.parentDataProperty}]`))}function HP(e,t){let{gen:r}=e;r.if((0,At._)`Array.isArray(${t})`,()=>{r.assign(Si.default.vErrors,(0,At._)`${Si.default.vErrors} === null ? ${t} : ${Si.default.vErrors}.concat(${t})`).assign(Si.default.errors,(0,At._)`${Si.default.vErrors}.length`),(0,BP.extendErrors)(e)},()=>e.error())}function KP({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function aw(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,At.stringify)(r)})}function QP(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}Zr.validSchemaType=QP;function XP({schema:e,opts:t,self:r,errSchemaPath:n},i,o){if(Array.isArray(i.keyword)?!i.keyword.includes(o):i.keyword!==o)throw new Error("ajv implementation error");let s=i.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${o}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(e[o])){let l=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Zr.validateKeywordUsage=XP});var uw=E(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.extendSubschemaMode=Rn.extendSubschemaData=Rn.getSubschema=void 0;var qr=H(),lw=ae();function YP(e,{keyword:t,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:o,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,qr._)`${e.schemaPath}${(0,qr.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,qr._)`${e.schemaPath}${(0,qr.getProperty)(t)}${(0,qr.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,lw.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||o===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:s,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Rn.getSubschema=YP;function eC(e,t,{dataProp:r,dataPropType:n,data:i,dataTypes:o,propertyName:s}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:c,dataPathArr:u,opts:d}=t,h=a.let("data",(0,qr._)`${t.data}${(0,qr.getProperty)(r)}`,!0);l(h),e.errorPath=(0,qr.str)`${c}${(0,lw.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,qr._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(i!==void 0){let c=i instanceof qr.Name?i:a.let("data",i,!0);l(c),s!==void 0&&(e.propertyName=s)}o&&(e.dataTypes=o);function l(c){e.data=c,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,c]}}Rn.extendSubschemaData=eC;function tC(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:o}){n!==void 0&&(e.compositeRule=n),i!==void 0&&(e.createErrors=i),o!==void 0&&(e.allErrors=o),e.jtdDiscriminator=t,e.jtdMetadata=r}Rn.extendSubschemaMode=tC});var Hm=E((U2,dw)=>{"use strict";dw.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(o=Object.keys(t),n=o.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;i--!==0;){var s=o[i];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}});var mw=E((F2,fw)=>{"use strict";var In=fw.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};Gc(t,n,i,e,"",e)};In.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};In.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};In.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};In.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Gc(e,t,r,n,i,o,s,a,l,c){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,i,o,s,a,l,c);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in In.arrayKeywords)for(var h=0;h<d.length;h++)Gc(e,t,r,d[h],i+"/"+u+"/"+h,o,i,u,n,h)}else if(u in In.propsKeywords){if(d&&typeof d=="object")for(var p in d)Gc(e,t,r,d[p],i+"/"+u+"/"+rC(p),o,i,u,n,p)}else(u in In.keywords||e.allKeys&&!(u in In.skipKeywords))&&Gc(e,t,r,d,i+"/"+u,o,i,u,n)}r(n,i,o,s,a,l,c)}}function rC(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ds=E(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.getSchemaRefs=Zt.resolveUrl=Zt.normalizeId=Zt._getFullPath=Zt.getFullPath=Zt.inlineRef=void 0;var nC=ae(),iC=Hm(),oC=mw(),sC=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function aC(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Km(e):t?pw(e)<=t:!1}Zt.inlineRef=aC;var cC=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Km(e){for(let t in e){if(cC.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Km)||typeof r=="object"&&Km(r))return!0}return!1}function pw(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!sC.has(r)&&(typeof e[r]=="object"&&(0,nC.eachItem)(e[r],n=>t+=pw(n)),t===1/0))return 1/0}return t}function hw(e,t="",r){r!==!1&&(t=_o(t));let n=e.parse(t);return gw(e,n)}Zt.getFullPath=hw;function gw(e,t){return e.serialize(t).split("#")[0]+"#"}Zt._getFullPath=gw;var lC=/#\/?$/;function _o(e){return e?e.replace(lC,""):""}Zt.normalizeId=_o;function uC(e,t,r){return r=_o(r),e.resolve(t,r)}Zt.resolveUrl=uC;var dC=/^[a-z_][-a-z0-9._]*$/i;function fC(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=_o(e[r]||t),o={"":i},s=hw(n,i,!1),a={},l=new Set;return oC(e,{allKeys:!0},(d,h,p,m)=>{if(m===void 0)return;let f=s+h,g=o[m];typeof d[r]=="string"&&(g=y.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),o[h]=g;function y(b){let w=this.opts.uriResolver.resolve;if(b=_o(g?w(g,b):b),l.has(b))throw u(b);l.add(b);let S=this.refs[b];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?c(d,S.schema,b):b!==_o(f)&&(b[0]==="#"?(c(d,a[b],b),a[b]=d):this.refs[b]=f),b}function v(b){if(typeof b=="string"){if(!dC.test(b))throw new Error(`invalid anchor "${b}"`);y.call(this,`#${b}`)}}}),a;function c(d,h,p){if(h!==void 0&&!iC(d,h))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Zt.getSchemaRefs=fC});var Ls=E(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.getData=jn.KeywordCxt=jn.validateFunctionCode=void 0;var ww=Kb(),_w=Ms(),Xm=Vm(),Bc=Ms(),mC=nw(),qs=cw(),Qm=uw(),j=H(),U=an(),pC=Ds(),cn=ae(),Zs=Ns();function hC(e){if(Sw(e)&&($w(e),kw(e))){yC(e);return}xw(e,()=>(0,ww.topBoolOrEmptySchema)(e))}jn.validateFunctionCode=hC;function xw({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},o){i.code.es5?e.func(t,(0,j._)`${U.default.data}, ${U.default.valCxt}`,n.$async,()=>{e.code((0,j._)`"use strict"; ${yw(r,i)}`),_C(e,i),e.code(o)}):e.func(t,(0,j._)`${U.default.data}, ${gC(i)}`,n.$async,()=>e.code(yw(r,i)).code(o))}function gC(e){return(0,j._)`{${U.default.instancePath}="", ${U.default.parentData}, ${U.default.parentDataProperty}, ${U.default.rootData}=${U.default.data}${e.dynamicRef?(0,j._)`, ${U.default.dynamicAnchors}={}`:j.nil}}={}`}function _C(e,t){e.if(U.default.valCxt,()=>{e.var(U.default.instancePath,(0,j._)`${U.default.valCxt}.${U.default.instancePath}`),e.var(U.default.parentData,(0,j._)`${U.default.valCxt}.${U.default.parentData}`),e.var(U.default.parentDataProperty,(0,j._)`${U.default.valCxt}.${U.default.parentDataProperty}`),e.var(U.default.rootData,(0,j._)`${U.default.valCxt}.${U.default.rootData}`),t.dynamicRef&&e.var(U.default.dynamicAnchors,(0,j._)`${U.default.valCxt}.${U.default.dynamicAnchors}`)},()=>{e.var(U.default.instancePath,(0,j._)`""`),e.var(U.default.parentData,(0,j._)`undefined`),e.var(U.default.parentDataProperty,(0,j._)`undefined`),e.var(U.default.rootData,U.default.data),t.dynamicRef&&e.var(U.default.dynamicAnchors,(0,j._)`{}`)})}function yC(e){let{schema:t,opts:r,gen:n}=e;xw(e,()=>{r.$comment&&t.$comment&&zw(e),kC(e),n.let(U.default.vErrors,null),n.let(U.default.errors,0),r.unevaluated&&vC(e),Tw(e),TC(e)})}function vC(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,j._)`${r}.evaluated`),t.if((0,j._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,j._)`${e.evaluated}.props`,(0,j._)`undefined`)),t.if((0,j._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,j._)`${e.evaluated}.items`,(0,j._)`undefined`))}function yw(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,j._)`/*# sourceURL=${r} */`:j.nil}function bC(e,t){if(Sw(e)&&($w(e),kw(e))){wC(e,t);return}(0,ww.boolOrEmptySchema)(e,t)}function kw({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function Sw(e){return typeof e.schema!="boolean"}function wC(e,t){let{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&zw(e),SC(e),$C(e);let o=n.const("_errs",U.default.errors);Tw(e,o),n.var(t,(0,j._)`${o} === ${U.default.errors}`)}function $w(e){(0,cn.checkUnknownRules)(e),xC(e)}function Tw(e,t){if(e.opts.jtd)return vw(e,[],!1,t);let r=(0,_w.getSchemaTypes)(e.schema),n=(0,_w.coerceAndCheckDataType)(e,r);vw(e,r,!n,t)}function xC(e){let{schema:t,errSchemaPath:r,opts:n,self:i}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,cn.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function kC(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,cn.checkStrictMode)(e,"default is ignored in the schema root")}function SC(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,pC.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function $C(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function zw({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){let o=r.$comment;if(i.$comment===!0)e.code((0,j._)`${U.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let s=(0,j.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,j._)`${U.default.self}.opts.$comment(${o}, ${s}, ${a}.schema)`)}}function TC(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=e;r.$async?t.if((0,j._)`${U.default.errors} === 0`,()=>t.return(U.default.data),()=>t.throw((0,j._)`new ${i}(${U.default.vErrors})`)):(t.assign((0,j._)`${n}.errors`,U.default.vErrors),o.unevaluated&&zC(e),t.return((0,j._)`${U.default.errors} === 0`))}function zC({gen:e,evaluated:t,props:r,items:n}){r instanceof j.Name&&e.assign((0,j._)`${t}.props`,r),n instanceof j.Name&&e.assign((0,j._)`${t}.items`,n)}function vw(e,t,r,n){let{gen:i,schema:o,data:s,allErrors:a,opts:l,self:c}=e,{RULES:u}=c;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,cn.schemaHasRulesButRef)(o,u))){i.block(()=>Aw(e,"$ref",u.all.$ref.definition));return}l.jtd||EC(e,t),i.block(()=>{for(let h of u.rules)d(h);d(u.post)});function d(h){(0,Xm.shouldUseGroup)(o,h)&&(h.type?(i.if((0,Bc.checkDataType)(h.type,s,l.strictNumbers)),bw(e,h),t.length===1&&t[0]===h.type&&r&&(i.else(),(0,Bc.reportTypeError)(e)),i.endIf()):bw(e,h),a||i.if((0,j._)`${U.default.errors} === ${n||0}`))}}function bw(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,mC.assignDefaults)(e,t.type),r.block(()=>{for(let o of t.rules)(0,Xm.shouldUseRule)(n,o)&&Aw(e,o.keyword,o.definition,t.type)})}function EC(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(AC(e,t),e.opts.allowUnionTypes||OC(e,t),PC(e,e.dataTypes))}function AC(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Ew(e.dataTypes,r)||Ym(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),RC(e,t)}}function OC(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Ym(e,"use allowUnionTypes to allow union type keyword")}function PC(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,Xm.shouldUseRule)(e.schema,i)){let{type:o}=i.definition;o.length&&!o.some(s=>CC(t,s))&&Ym(e,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function CC(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Ew(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function RC(e,t){let r=[];for(let n of e.dataTypes)Ew(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Ym(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,cn.checkStrictMode)(e,t,e.opts.strictTypes)}var Jc=class{constructor(t,r,n){if((0,qs.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,cn.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",Ow(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,qs.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",U.default.errors))}result(t,r,n){this.failResult((0,j.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,j.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,j._)`${r} !== undefined && (${(0,j.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?Zs.reportExtraError:Zs.reportError)(this,this.def.error,r)}$dataError(){(0,Zs.reportError)(this,this.def.$dataError||Zs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Zs.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=j.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=j.nil,r=j.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:s}=this;n.if((0,j.or)((0,j._)`${i} === undefined`,r)),t!==j.nil&&n.assign(t,!0),(o.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==j.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:i,it:o}=this;return(0,j.or)(s(),a());function s(){if(n.length){if(!(r instanceof j.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,j._)`${(0,Bc.checkDataTypes)(l,r,o.opts.strictNumbers,Bc.DataType.Wrong)}`}return j.nil}function a(){if(i.validateSchema){let l=t.scopeValue("validate$data",{ref:i.validateSchema});return(0,j._)`!${l}(${r})`}return j.nil}}subschema(t,r){let n=(0,Qm.getSubschema)(this.it,t);(0,Qm.extendSubschemaData)(n,this.it,t),(0,Qm.extendSubschemaMode)(n,t);let i={...this.it,...n,items:void 0,props:void 0};return bC(i,r),i}mergeEvaluated(t,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=cn.mergeEvaluated.props(i,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=cn.mergeEvaluated.items(i,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(t,j.Name)),!0}};jn.KeywordCxt=Jc;function Aw(e,t,r,n){let i=new Jc(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,qs.funcKeywordCode)(i,r):"macro"in r?(0,qs.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,qs.funcKeywordCode)(i,r)}var IC=/^\/(?:[^~]|~0|~1)*$/,jC=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ow(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,o;if(e==="")return U.default.rootData;if(e[0]==="/"){if(!IC.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,o=U.default.rootData}else{let c=jC.exec(e);if(!c)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+c[1];if(i=c[2],i==="#"){if(u>=t)throw new Error(l("property/index",u));return n[t-u]}if(u>t)throw new Error(l("data",u));if(o=r[t-u],!i)return o}let s=o,a=i.split("/");for(let c of a)c&&(o=(0,j._)`${o}${(0,j.getProperty)((0,cn.unescapeJsonPointer)(c))}`,s=(0,j._)`${s} && ${o}`);return s;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${t}`}}jn.getData=Ow});var Wc=E(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var ep=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};tp.default=ep});var Vs=E(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});var rp=Ds(),np=class extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,rp.resolveUrl)(t,r,n),this.missingSchema=(0,rp.normalizeId)((0,rp.getFullPath)(t,this.missingRef))}};ip.default=np});var Kc=E(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.resolveSchema=cr.getCompilingSchema=cr.resolveRef=cr.compileSchema=cr.SchemaEnv=void 0;var vr=H(),NC=Wc(),$i=an(),br=Ds(),Pw=ae(),MC=Ls(),yo=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,br.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};cr.SchemaEnv=yo;function sp(e){let t=Cw.call(this,e);if(t)return t;let r=(0,br.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,s=new vr.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),a;e.$async&&(a=s.scopeValue("Error",{ref:NC.default,code:(0,vr._)`require("ajv/dist/runtime/validation_error").default`}));let l=s.scopeName("validate");e.validateName=l;let c={gen:s,allErrors:this.opts.allErrors,data:$i.default.data,parentData:$i.default.parentData,parentDataProperty:$i.default.parentDataProperty,dataNames:[$i.default.data],dataPathArr:[vr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,vr.stringify)(e.schema)}:{ref:e.schema}),validateName:l,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:vr.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,vr._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,MC.validateFunctionCode)(c),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs($i.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let p=new Function(`${$i.default.self}`,`${$i.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:l,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:f}=c;p.evaluated={props:m instanceof vr.Name?void 0:m,items:f instanceof vr.Name?void 0:f,dynamicProps:m instanceof vr.Name,dynamicItems:f instanceof vr.Name},p.source&&(p.source.evaluated=(0,vr.stringify)(p.evaluated))}return e.validate=p,e}catch(d){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(e)}}cr.compileSchema=sp;function DC(e,t,r){var n;r=(0,br.resolveUrl)(this.opts.uriResolver,t,r);let i=e.refs[r];if(i)return i;let o=LC.call(this,e,r);if(o===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(o=new yo({schema:s,schemaId:a,root:e,baseId:t}))}if(o!==void 0)return e.refs[r]=ZC.call(this,o)}cr.resolveRef=DC;function ZC(e){return(0,br.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:sp.call(this,e)}function Cw(e){for(let t of this._compilations)if(qC(t,e))return t}cr.getCompilingSchema=Cw;function qC(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function LC(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Hc.call(this,e,t)}function Hc(e,t){let r=this.opts.uriResolver.parse(t),n=(0,br._getFullPath)(this.opts.uriResolver,r),i=(0,br.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return op.call(this,r,e);let o=(0,br.normalizeId)(n),s=this.refs[o]||this.schemas[o];if(typeof s=="string"){let a=Hc.call(this,e,s);return typeof a?.schema!="object"?void 0:op.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||sp.call(this,s),o===(0,br.normalizeId)(t)){let{schema:a}=s,{schemaId:l}=this.opts,c=a[l];return c&&(i=(0,br.resolveUrl)(this.opts.uriResolver,i,c)),new yo({schema:a,schemaId:l,root:e,baseId:i})}return op.call(this,r,s)}}cr.resolveSchema=Hc;var VC=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function op(e,{baseId:t,schema:r,root:n}){var i;if(((i=e.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,Pw.unescapeFragment)(a)];if(l===void 0)return;r=l;let c=typeof r=="object"&&r[this.opts.schemaId];!VC.has(a)&&c&&(t=(0,br.resolveUrl)(this.opts.uriResolver,t,c))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,Pw.schemaHasRulesButRef)(r,this.RULES)){let a=(0,br.resolveUrl)(this.opts.uriResolver,t,r.$ref);o=Hc.call(this,n,a)}let{schemaId:s}=this.opts;if(o=o||new yo({schema:r,schemaId:s,root:n,baseId:t}),o.schema!==o.root.schema)return o}});var Rw=E((K2,UC)=>{UC.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var cp=E((Q2,Mw)=>{"use strict";var FC=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),jw=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function ap(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var GC=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Iw(e){return e.length=0,!0}function BC(e,t,r){if(e.length){let n=ap(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function JC(e){let t=0,r={error:!1,address:"",zone:""},n=[],i=[],o=!1,s=!1,a=BC;for(let l=0;l<e.length;l++){let c=e[l];if(!(c==="["||c==="]"))if(c===":"){if(o===!0&&(s=!0),!a(i,n,r))break;if(++t>7){r.error=!0;break}l>0&&e[l-1]===":"&&(o=!0),n.push(":");continue}else if(c==="%"){if(!a(i,n,r))break;a=Iw}else{i.push(c);continue}}return i.length&&(a===Iw?r.zone=i.join(""):s?n.push(i.join("")):n.push(ap(i))),r.address=n.join(""),r}function Nw(e){if(WC(e,":")<2)return{host:e,isIPV6:!1};let t=JC(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}function WC(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function HC(e){let t=e,r=[],n=-1,i=0;for(;i=t.length;){if(i===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(i===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(i===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}function KC(e,t){let r=t!==!0?escape:unescape;return e.scheme!==void 0&&(e.scheme=r(e.scheme)),e.userinfo!==void 0&&(e.userinfo=r(e.userinfo)),e.host!==void 0&&(e.host=r(e.host)),e.path!==void 0&&(e.path=r(e.path)),e.query!==void 0&&(e.query=r(e.query)),e.fragment!==void 0&&(e.fragment=r(e.fragment)),e}function QC(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!jw(r)){let n=Nw(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=e.host}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}Mw.exports={nonSimpleDomain:GC,recomposeAuthority:QC,normalizeComponentEncoding:KC,removeDotSegments:HC,isIPv4:jw,isUUID:FC,normalizeIPv6:Nw,stringArrayToHexStripped:ap}});var Vw=E((X2,Lw)=>{"use strict";var{isUUID:XC}=cp(),YC=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,e1=["http","https","ws","wss","urn","urn:uuid"];function t1(e){return e1.indexOf(e)!==-1}function lp(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function Dw(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Zw(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function r1(e){return e.secure=lp(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function n1(e){if((e.port===(lp(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function i1(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(YC);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let i=`${n}:${t.nid||e.nid}`,o=up(i);e.path=void 0,o&&(e=o.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function o1(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),i=`${r}:${t.nid||n}`,o=up(i);o&&(e=o.serialize(e,t));let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}function s1(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!XC(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function a1(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var qw={scheme:"http",domainHost:!0,parse:Dw,serialize:Zw},c1={scheme:"https",domainHost:qw.domainHost,parse:Dw,serialize:Zw},Qc={scheme:"ws",domainHost:!0,parse:r1,serialize:n1},l1={scheme:"wss",domainHost:Qc.domainHost,parse:Qc.parse,serialize:Qc.serialize},u1={scheme:"urn",parse:i1,serialize:o1,skipNormalize:!0},d1={scheme:"urn:uuid",parse:s1,serialize:a1,skipNormalize:!0},Xc={http:qw,https:c1,ws:Qc,wss:l1,urn:u1,"urn:uuid":d1};Object.setPrototypeOf(Xc,null);function up(e){return e&&(Xc[e]||Xc[e.toLowerCase()])||void 0}Lw.exports={wsIsSecure:lp,SCHEMES:Xc,isValidSchemeName:t1,getSchemeHandler:up}});var Gw=E((Y2,el)=>{"use strict";var{normalizeIPv6:f1,removeDotSegments:Us,recomposeAuthority:m1,normalizeComponentEncoding:Yc,isIPv4:p1,nonSimpleDomain:h1}=cp(),{SCHEMES:g1,getSchemeHandler:Uw}=Vw();function _1(e,t){return typeof e=="string"?e=Lr(ln(e,t),t):typeof e=="object"&&(e=ln(Lr(e,t),t)),e}function y1(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},i=Fw(ln(e,n),ln(t,n),n,!0);return n.skipEscape=!0,Lr(i,n)}function Fw(e,t,r,n){let i={};return n||(e=ln(Lr(e,r),r),t=ln(Lr(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(i.scheme=t.scheme,i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=Us(t.path||""),i.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=Us(t.path||""),i.query=t.query):(t.path?(t.path[0]==="/"?i.path=Us(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?i.path="/"+t.path:e.path?i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:i.path=t.path,i.path=Us(i.path)),i.query=t.query):(i.path=e.path,t.query!==void 0?i.query=t.query:i.query=e.query),i.userinfo=e.userinfo,i.host=e.host,i.port=e.port),i.scheme=e.scheme),i.fragment=t.fragment,i}function v1(e,t,r){return typeof e=="string"?(e=unescape(e),e=Lr(Yc(ln(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Lr(Yc(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=Lr(Yc(ln(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Lr(Yc(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function Lr(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),i=[],o=Uw(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&i.push(r.scheme,":");let s=m1(r);if(s!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(s),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=Us(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return r.query!==void 0&&i.push("?",r.query),r.fragment!==void 0&&i.push("#",r.fragment),i.join("")}var b1=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ln(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let o=e.match(b1);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(p1(n.host)===!1){let l=f1(n.host);n.host=l.host.toLowerCase(),i=l.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let s=Uw(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&i===!1&&h1(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!s||s&&!s.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s&&s.parse&&s.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var dp={SCHEMES:g1,normalize:_1,resolve:y1,resolveComponent:Fw,equal:v1,serialize:Lr,parse:ln};el.exports=dp;el.exports.default=dp;el.exports.fastUri=dp});var Jw=E(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});var Bw=Gw();Bw.code='require("ajv/dist/runtime/uri").default';fp.default=Bw});var t0=E(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.CodeGen=ct.Name=ct.nil=ct.stringify=ct.str=ct._=ct.KeywordCxt=void 0;var w1=Ls();Object.defineProperty(ct,"KeywordCxt",{enumerable:!0,get:function(){return w1.KeywordCxt}});var vo=H();Object.defineProperty(ct,"_",{enumerable:!0,get:function(){return vo._}});Object.defineProperty(ct,"str",{enumerable:!0,get:function(){return vo.str}});Object.defineProperty(ct,"stringify",{enumerable:!0,get:function(){return vo.stringify}});Object.defineProperty(ct,"nil",{enumerable:!0,get:function(){return vo.nil}});Object.defineProperty(ct,"Name",{enumerable:!0,get:function(){return vo.Name}});Object.defineProperty(ct,"CodeGen",{enumerable:!0,get:function(){return vo.CodeGen}});var x1=Wc(),Xw=Vs(),k1=Lm(),Fs=Kc(),S1=H(),Gs=Ds(),tl=Ms(),pp=ae(),Ww=Rw(),$1=Jw(),Yw=(e,t)=>new RegExp(e,t);Yw.code="new RegExp";var T1=["removeAdditional","useDefaults","coerceTypes"],z1=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),E1={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},A1={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Hw=200;function O1(e){var t,r,n,i,o,s,a,l,c,u,d,h,p,m,f,g,y,v,b,w,S,Z,F,ce,Je;let Ee=e.strict,bt=(t=e.code)===null||t===void 0?void 0:t.optimize,ut=bt===!0||bt===void 0?1:bt||0,Ye=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Yw,R=(i=e.uriResolver)!==null&&i!==void 0?i:$1.default;return{strictSchema:(s=(o=e.strictSchema)!==null&&o!==void 0?o:Ee)!==null&&s!==void 0?s:!0,strictNumbers:(l=(a=e.strictNumbers)!==null&&a!==void 0?a:Ee)!==null&&l!==void 0?l:!0,strictTypes:(u=(c=e.strictTypes)!==null&&c!==void 0?c:Ee)!==null&&u!==void 0?u:"log",strictTuples:(h=(d=e.strictTuples)!==null&&d!==void 0?d:Ee)!==null&&h!==void 0?h:"log",strictRequired:(m=(p=e.strictRequired)!==null&&p!==void 0?p:Ee)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:ut,regExp:Ye}:{optimize:ut,regExp:Ye},loopRequired:(f=e.loopRequired)!==null&&f!==void 0?f:Hw,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:Hw,meta:(y=e.meta)!==null&&y!==void 0?y:!0,messages:(v=e.messages)!==null&&v!==void 0?v:!0,inlineRefs:(b=e.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(w=e.schemaId)!==null&&w!==void 0?w:"$id",addUsedSchema:(S=e.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(Z=e.validateSchema)!==null&&Z!==void 0?Z:!0,validateFormats:(F=e.validateFormats)!==null&&F!==void 0?F:!0,unicodeRegExp:(ce=e.unicodeRegExp)!==null&&ce!==void 0?ce:!0,int32range:(Je=e.int32range)!==null&&Je!==void 0?Je:!0,uriResolver:R}}var Bs=class{constructor(t={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...O1(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new S1.ValueScope({scope:{},prefixes:z1,es5:r,lines:n}),this.logger=N1(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,k1.getRules)(),Kw.call(this,E1,t,"NOT SUPPORTED"),Kw.call(this,A1,t,"DEPRECATED","warn"),this._metaOpts=I1.call(this),t.formats&&C1.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&R1.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),P1.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,i=Ww;n==="id"&&(i={...Ww},i.id=i.$id,delete i.$id),r&&t&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,t,r);async function i(u,d){await o.call(this,u.$schema);let h=this._addSchema(u,d);return h.validate||s.call(this,h)}async function o(u){u&&!this.getSchema(u)&&await i.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Xw.default))throw d;return a.call(this,d),await l.call(this,d.missingSchema),s.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function l(u){let d=await c.call(this,u);this.refs[u]||await o.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function c(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(t,r,n,i=this.opts.validateSchema){if(Array.isArray(t)){for(let s of t)this.addSchema(s,void 0,n,i);return this}let o;if(typeof t=="object"){let{schemaId:s}=this.opts;if(o=t[s],o!==void 0&&typeof o!="string")throw new Error(`schema ${s} must be string`)}return r=(0,Gs.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,i,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,t);if(!i&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return i}getSchema(t){let r;for(;typeof(r=Qw.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,i=new Fs.SchemaEnv({schema:{},schemaId:n});if(r=Fs.resolveSchema.call(this,i,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Qw.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,Gs.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(D1.call(this,n,r),!r)return(0,pp.eachItem)(n,o=>mp.call(this,o)),this;q1.call(this,r);let i={...r,type:(0,tl.getJSONTypes)(r.type),schemaType:(0,tl.getJSONTypes)(r.schemaType)};return(0,pp.eachItem)(n,i.type.length===0?o=>mp.call(this,o,i):o=>i.type.forEach(s=>mp.call(this,o,i,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let i=n.rules.findIndex(o=>o.keyword===t);i>=0&&n.rules.splice(i,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,o)=>i+r+o)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let i of r){let o=i.split("/").slice(1),s=t;for(let a of o)s=s[a];for(let a in n){let l=n[a];if(typeof l!="object")continue;let{$data:c}=l.definition,u=s[a];c&&u&&(s[a]=e0(u))}}return t}_removeAllSchemas(t,r){for(let n in t){let i=t[n];(!r||r.test(n))&&(typeof i=="string"?delete t[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete t[n]))}}_addSchema(t,r,n,i=this.opts.validateSchema,o=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof t=="object")s=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(t);if(l!==void 0)return l;n=(0,Gs.normalizeId)(s||n);let c=Gs.getSchemaRefs.call(this,t,n);return l=new Fs.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:c}),this._cache.set(l.schema,l),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),i&&this.validateSchema(t,!0),l}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):Fs.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{Fs.compileSchema.call(this,t)}finally{this.opts=r}}};Bs.ValidationError=x1.default;Bs.MissingRefError=Xw.default;ct.default=Bs;function Kw(e,t,r,n="error"){for(let i in e){let o=i;o in t&&this.logger[n](`${r}: option ${i}. ${e[o]}`)}}function Qw(e){return e=(0,Gs.normalizeId)(e),this.schemas[e]||this.refs[e]}function P1(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function C1(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function R1(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function I1(){let e={...this.opts};for(let t of T1)delete e[t];return e}var j1={log(){},warn(){},error(){}};function N1(e){if(e===!1)return j1;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var M1=/^[a-z_$][a-z0-9_$:-]*$/i;function D1(e,t){let{RULES:r}=this;if((0,pp.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!M1.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function mp(e,t,r){var n;let i=t?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,s=i?o.post:o.rules.find(({type:l})=>l===r);if(s||(s={type:r,rules:[]},o.rules.push(s)),o.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,tl.getJSONTypes)(t.type),schemaType:(0,tl.getJSONTypes)(t.schemaType)}};t.before?Z1.call(this,s,a,t.before):s.rules.push(a),o.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function Z1(e,t,r){let n=e.rules.findIndex(i=>i.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function q1(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=e0(t)),e.validateSchema=this.compile(t,!0))}var L1={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function e0(e){return{anyOf:[e,L1]}}});var r0=E(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var V1={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};hp.default=V1});var s0=E(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.callRef=Ti.getValidate=void 0;var U1=Vs(),n0=ar(),qt=H(),bo=an(),i0=Kc(),rl=ae(),F1={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:i,schemaEnv:o,validateName:s,opts:a,self:l}=n,{root:c}=o;if((r==="#"||r==="#/")&&i===c.baseId)return d();let u=i0.resolveRef.call(l,c,i,r);if(u===void 0)throw new U1.default(n.opts.uriResolver,i,r);if(u instanceof i0.SchemaEnv)return h(u);return p(u);function d(){if(o===c)return nl(e,s,o,o.$async);let m=t.scopeValue("root",{ref:c});return nl(e,(0,qt._)`${m}.validate`,c,c.$async)}function h(m){let f=o0(e,m);nl(e,f,m,m.$async)}function p(m){let f=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,qt.stringify)(m)}:{ref:m}),g=t.name("valid"),y=e.subschema({schema:m,dataTypes:[],schemaPath:qt.nil,topSchemaRef:f,errSchemaPath:r},g);e.mergeEvaluated(y),e.ok(g)}}};function o0(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,qt._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Ti.getValidate=o0;function nl(e,t,r,n){let{gen:i,it:o}=e,{allErrors:s,schemaEnv:a,opts:l}=o,c=l.passContext?bo.default.this:qt.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,qt._)`await ${(0,n0.callValidateCode)(e,t,c)}`),p(t),s||i.assign(m,!0)},f=>{i.if((0,qt._)`!(${f} instanceof ${o.ValidationError})`,()=>i.throw(f)),h(f),s||i.assign(m,!1)}),e.ok(m)}function d(){e.result((0,n0.callValidateCode)(e,t,c),()=>p(t),()=>h(t))}function h(m){let f=(0,qt._)`${m}.errors`;i.assign(bo.default.vErrors,(0,qt._)`${bo.default.vErrors} === null ? ${f} : ${bo.default.vErrors}.concat(${f})`),i.assign(bo.default.errors,(0,qt._)`${bo.default.vErrors}.length`)}function p(m){var f;if(!o.opts.unevaluated)return;let g=(f=r?.validate)===null||f===void 0?void 0:f.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=rl.mergeEvaluated.props(i,g.props,o.props));else{let y=i.var("props",(0,qt._)`${m}.evaluated.props`);o.props=rl.mergeEvaluated.props(i,y,o.props,qt.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=rl.mergeEvaluated.items(i,g.items,o.items));else{let y=i.var("items",(0,qt._)`${m}.evaluated.items`);o.items=rl.mergeEvaluated.items(i,y,o.items,qt.Name)}}}Ti.callRef=nl;Ti.default=F1});var a0=E(gp=>{"use strict";Object.defineProperty(gp,"__esModule",{value:!0});var G1=r0(),B1=s0(),J1=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",G1.default,B1.default];gp.default=J1});var c0=E(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});var il=H(),Nn=il.operators,ol={maximum:{okStr:"<=",ok:Nn.LTE,fail:Nn.GT},minimum:{okStr:">=",ok:Nn.GTE,fail:Nn.LT},exclusiveMaximum:{okStr:"<",ok:Nn.LT,fail:Nn.GTE},exclusiveMinimum:{okStr:">",ok:Nn.GT,fail:Nn.LTE}},W1={message:({keyword:e,schemaCode:t})=>(0,il.str)`must be ${ol[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,il._)`{comparison: ${ol[e].okStr}, limit: ${t}}`},H1={keyword:Object.keys(ol),type:"number",schemaType:"number",$data:!0,error:W1,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,il._)`${r} ${ol[t].fail} ${n} || isNaN(${r})`)}};_p.default=H1});var l0=E(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});var Js=H(),K1={message:({schemaCode:e})=>(0,Js.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Js._)`{multipleOf: ${e}}`},Q1={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:K1,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,o=i.opts.multipleOfPrecision,s=t.let("res"),a=o?(0,Js._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,Js._)`${s} !== parseInt(${s})`;e.fail$data((0,Js._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};yp.default=Q1});var d0=E(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});function u0(e){let t=e.length,r=0,n=0,i;for(;n<t;)r++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<t&&(i=e.charCodeAt(n),(i&64512)===56320&&n++);return r}vp.default=u0;u0.code='require("ajv/dist/runtime/ucs2length").default'});var f0=E(bp=>{"use strict";Object.defineProperty(bp,"__esModule",{value:!0});var zi=H(),X1=ae(),Y1=d0(),eR={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,zi.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,zi._)`{limit: ${e}}`},tR={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:eR,code(e){let{keyword:t,data:r,schemaCode:n,it:i}=e,o=t==="maxLength"?zi.operators.GT:zi.operators.LT,s=i.opts.unicode===!1?(0,zi._)`${r}.length`:(0,zi._)`${(0,X1.useFunc)(e.gen,Y1.default)}(${r})`;e.fail$data((0,zi._)`${s} ${o} ${n}`)}};bp.default=tR});var m0=E(wp=>{"use strict";Object.defineProperty(wp,"__esModule",{value:!0});var rR=ar(),sl=H(),nR={message:({schemaCode:e})=>(0,sl.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,sl._)`{pattern: ${e}}`},iR={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:nR,code(e){let{data:t,$data:r,schema:n,schemaCode:i,it:o}=e,s=o.opts.unicodeRegExp?"u":"",a=r?(0,sl._)`(new RegExp(${i}, ${s}))`:(0,rR.usePattern)(e,n);e.fail$data((0,sl._)`!${a}.test(${t})`)}};wp.default=iR});var p0=E(xp=>{"use strict";Object.defineProperty(xp,"__esModule",{value:!0});var Ws=H(),oR={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,Ws.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,Ws._)`{limit: ${e}}`},sR={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:oR,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?Ws.operators.GT:Ws.operators.LT;e.fail$data((0,Ws._)`Object.keys(${r}).length ${i} ${n}`)}};xp.default=sR});var h0=E(kp=>{"use strict";Object.defineProperty(kp,"__esModule",{value:!0});var Hs=ar(),Ks=H(),aR=ae(),cR={message:({params:{missingProperty:e}})=>(0,Ks.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Ks._)`{missingProperty: ${e}}`},lR={keyword:"required",type:"object",schemaType:"array",$data:!0,error:cR,code(e){let{gen:t,schema:r,schemaCode:n,data:i,$data:o,it:s}=e,{opts:a}=s;if(!o&&r.length===0)return;let l=r.length>=a.loopRequired;if(s.allErrors?c():u(),a.strictRequired){let p=e.parentSchema.properties,{definedProperties:m}=e.it;for(let f of r)if(p?.[f]===void 0&&!m.has(f)){let g=s.schemaEnv.baseId+s.errSchemaPath,y=`required property "${f}" is not defined at "${g}" (strictRequired)`;(0,aR.checkStrictMode)(s,y,s.opts.strictRequired)}}function c(){if(l||o)e.block$data(Ks.nil,d);else for(let p of r)(0,Hs.checkReportMissingProp)(e,p)}function u(){let p=t.let("missing");if(l||o){let m=t.let("valid",!0);e.block$data(m,()=>h(p,m)),e.ok(m)}else t.if((0,Hs.checkMissingProp)(e,r,p)),(0,Hs.reportMissingProp)(e,p),t.else()}function d(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,Hs.noPropertyInData)(t,i,p,a.ownProperties),()=>e.error())})}function h(p,m){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(m,(0,Hs.propertyInData)(t,i,p,a.ownProperties)),t.if((0,Ks.not)(m),()=>{e.error(),t.break()})},Ks.nil)}}};kp.default=lR});var g0=E(Sp=>{"use strict";Object.defineProperty(Sp,"__esModule",{value:!0});var Qs=H(),uR={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Qs.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Qs._)`{limit: ${e}}`},dR={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:uR,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?Qs.operators.GT:Qs.operators.LT;e.fail$data((0,Qs._)`${r}.length ${i} ${n}`)}};Sp.default=dR});var al=E($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});var _0=Hm();_0.code='require("ajv/dist/runtime/equal").default';$p.default=_0});var y0=E(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});var Tp=Ms(),lt=H(),fR=ae(),mR=al(),pR={message:({params:{i:e,j:t}})=>(0,lt.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,lt._)`{i: ${e}, j: ${t}}`},hR={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:pR,code(e){let{gen:t,data:r,$data:n,schema:i,parentSchema:o,schemaCode:s,it:a}=e;if(!n&&!i)return;let l=t.let("valid"),c=o.items?(0,Tp.getSchemaTypes)(o.items):[];e.block$data(l,u,(0,lt._)`${s} === false`),e.ok(l);function u(){let m=t.let("i",(0,lt._)`${r}.length`),f=t.let("j");e.setParams({i:m,j:f}),t.assign(l,!0),t.if((0,lt._)`${m} > 1`,()=>(d()?h:p)(m,f))}function d(){return c.length>0&&!c.some(m=>m==="object"||m==="array")}function h(m,f){let g=t.name("item"),y=(0,Tp.checkDataTypes)(c,g,a.opts.strictNumbers,Tp.DataType.Wrong),v=t.const("indices",(0,lt._)`{}`);t.for((0,lt._)`;${m}--;`,()=>{t.let(g,(0,lt._)`${r}[${m}]`),t.if(y,(0,lt._)`continue`),c.length>1&&t.if((0,lt._)`typeof ${g} == "string"`,(0,lt._)`${g} += "_"`),t.if((0,lt._)`typeof ${v}[${g}] == "number"`,()=>{t.assign(f,(0,lt._)`${v}[${g}]`),e.error(),t.assign(l,!1).break()}).code((0,lt._)`${v}[${g}] = ${m}`)})}function p(m,f){let g=(0,fR.useFunc)(t,mR.default),y=t.name("outer");t.label(y).for((0,lt._)`;${m}--;`,()=>t.for((0,lt._)`${f} = ${m}; ${f}--;`,()=>t.if((0,lt._)`${g}(${r}[${m}], ${r}[${f}])`,()=>{e.error(),t.assign(l,!1).break(y)})))}}};zp.default=hR});var v0=E(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});var Ep=H(),gR=ae(),_R=al(),yR={message:"must be equal to constant",params:({schemaCode:e})=>(0,Ep._)`{allowedValue: ${e}}`},vR={keyword:"const",$data:!0,error:yR,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:o}=e;n||o&&typeof o=="object"?e.fail$data((0,Ep._)`!${(0,gR.useFunc)(t,_R.default)}(${r}, ${i})`):e.fail((0,Ep._)`${o} !== ${r}`)}};Ap.default=vR});var b0=E(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});var Xs=H(),bR=ae(),wR=al(),xR={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Xs._)`{allowedValues: ${e}}`},kR={keyword:"enum",schemaType:"array",$data:!0,error:xR,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:o,it:s}=e;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=s.opts.loopEnum,l,c=()=>l??(l=(0,bR.useFunc)(t,wR.default)),u;if(a||n)u=t.let("valid"),e.block$data(u,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=t.const("vSchema",o);u=(0,Xs.or)(...i.map((m,f)=>h(p,f)))}e.pass(u);function d(){t.assign(u,!1),t.forOf("v",o,p=>t.if((0,Xs._)`${c()}(${r}, ${p})`,()=>t.assign(u,!0).break()))}function h(p,m){let f=i[m];return typeof f=="object"&&f!==null?(0,Xs._)`${c()}(${r}, ${p}[${m}])`:(0,Xs._)`${r} === ${f}`}}};Op.default=kR});var w0=E(Pp=>{"use strict";Object.defineProperty(Pp,"__esModule",{value:!0});var SR=c0(),$R=l0(),TR=f0(),zR=m0(),ER=p0(),AR=h0(),OR=g0(),PR=y0(),CR=v0(),RR=b0(),IR=[SR.default,$R.default,TR.default,zR.default,ER.default,AR.default,OR.default,PR.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},CR.default,RR.default];Pp.default=IR});var Rp=E(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.validateAdditionalItems=void 0;var Ei=H(),Cp=ae(),jR={message:({params:{len:e}})=>(0,Ei.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Ei._)`{limit: ${e}}`},NR={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:jR,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Cp.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}x0(e,n)}};function x0(e,t){let{gen:r,schema:n,data:i,keyword:o,it:s}=e;s.items=!0;let a=r.const("len",(0,Ei._)`${i}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Ei._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Cp.alwaysValidSchema)(s,n)){let c=r.var("valid",(0,Ei._)`${a} <= ${t.length}`);r.if((0,Ei.not)(c),()=>l(c)),e.ok(c)}function l(c){r.forRange("i",t.length,a,u=>{e.subschema({keyword:o,dataProp:u,dataPropType:Cp.Type.Num},c),s.allErrors||r.if((0,Ei.not)(c),()=>r.break())})}}Ys.validateAdditionalItems=x0;Ys.default=NR});var Ip=E(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.validateTuple=void 0;var k0=H(),cl=ae(),MR=ar(),DR={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return S0(e,"additionalItems",t);r.items=!0,!(0,cl.alwaysValidSchema)(r,t)&&e.ok((0,MR.validateArray)(e))}};function S0(e,t,r=e.schema){let{gen:n,parentSchema:i,data:o,keyword:s,it:a}=e;u(i),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=cl.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),c=n.const("len",(0,k0._)`${o}.length`);r.forEach((d,h)=>{(0,cl.alwaysValidSchema)(a,d)||(n.if((0,k0._)`${c} > ${h}`,()=>e.subschema({keyword:s,schemaProp:h,dataProp:h},l)),e.ok(l))});function u(d){let{opts:h,errSchemaPath:p}=a,m=r.length,f=m===d.minItems&&(m===d.maxItems||d[t]===!1);if(h.strictTuples&&!f){let g=`"${s}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${p}"`;(0,cl.checkStrictMode)(a,g,h.strictTuples)}}}ea.validateTuple=S0;ea.default=DR});var $0=E(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});var ZR=Ip(),qR={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,ZR.validateTuple)(e,"items")};jp.default=qR});var z0=E(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});var T0=H(),LR=ae(),VR=ar(),UR=Rp(),FR={message:({params:{len:e}})=>(0,T0.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,T0._)`{limit: ${e}}`},GR={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:FR,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;n.items=!0,!(0,LR.alwaysValidSchema)(n,t)&&(i?(0,UR.validateAdditionalItems)(e,i):e.ok((0,VR.validateArray)(e)))}};Np.default=GR});var E0=E(Mp=>{"use strict";Object.defineProperty(Mp,"__esModule",{value:!0});var lr=H(),ll=ae(),BR={message:({params:{min:e,max:t}})=>t===void 0?(0,lr.str)`must contain at least ${e} valid item(s)`:(0,lr.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,lr._)`{minContains: ${e}}`:(0,lr._)`{minContains: ${e}, maxContains: ${t}}`},JR={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:BR,code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:o}=e,s,a,{minContains:l,maxContains:c}=n;o.opts.next?(s=l===void 0?1:l,a=c):s=1;let u=t.const("len",(0,lr._)`${i}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,ll.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,ll.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,ll.alwaysValidSchema)(o,r)){let f=(0,lr._)`${u} >= ${s}`;a!==void 0&&(f=(0,lr._)`${f} && ${u} <= ${a}`),e.pass(f);return}o.items=!0;let d=t.name("valid");a===void 0&&s===1?p(d,()=>t.if(d,()=>t.break())):s===0?(t.let(d,!0),a!==void 0&&t.if((0,lr._)`${i}.length > 0`,h)):(t.let(d,!1),h()),e.result(d,()=>e.reset());function h(){let f=t.name("_valid"),g=t.let("count",0);p(f,()=>t.if(f,()=>m(g)))}function p(f,g){t.forRange("i",0,u,y=>{e.subschema({keyword:"contains",dataProp:y,dataPropType:ll.Type.Num,compositeRule:!0},f),g()})}function m(f){t.code((0,lr._)`${f}++`),a===void 0?t.if((0,lr._)`${f} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,lr._)`${f} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,lr._)`${f} >= ${s}`,()=>t.assign(d,!0)))}}};Mp.default=JR});var P0=E(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.validateSchemaDeps=Vr.validatePropertyDeps=Vr.error=void 0;var Dp=H(),WR=ae(),ta=ar();Vr.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Dp.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Dp._)`{property: ${e},
3
+ var oS=Object.create;var su=Object.defineProperty;var sS=Object.getOwnPropertyDescriptor;var aS=Object.getOwnPropertyNames;var cS=Object.getPrototypeOf,lS=Object.prototype.hasOwnProperty;var bn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var z=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),au=(e,t)=>{for(var r in t)su(e,r,{get:t[r],enumerable:!0})},uS=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of aS(t))!lS.call(e,i)&&i!==r&&su(e,i,{get:()=>t[i],enumerable:!(n=sS(t,i))||n.enumerable});return e};var cu=(e,t,r)=>(r=e!=null?oS(cS(e)):{},uS(t||!e||!e.__esModule?su(r,"default",{value:e,enumerable:!0}):r,e));var gy=z((VZ,hy)=>{var Rn=bn("constants"),zE=process.cwd,dc=null,OE=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return dc||(dc=zE.call(process)),dc};try{process.cwd()}catch{}typeof process.chdir=="function"&&(id=process.chdir,process.chdir=function(e){dc=null,id.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,id));var id;hy.exports=AE;function AE(e){Rn.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||r(e),e.chown=o(e.chown),e.fchown=o(e.fchown),e.lchown=o(e.lchown),e.chmod=n(e.chmod),e.fchmod=n(e.fchmod),e.lchmod=n(e.lchmod),e.chownSync=s(e.chownSync),e.fchownSync=s(e.fchownSync),e.lchownSync=s(e.lchownSync),e.chmodSync=i(e.chmodSync),e.fchmodSync=i(e.fchmodSync),e.lchmodSync=i(e.lchmodSync),e.stat=a(e.stat),e.fstat=a(e.fstat),e.lstat=a(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(l,d,h){h&&process.nextTick(h)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(l,d,h,m){m&&process.nextTick(m)},e.lchownSync=function(){}),OE==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:(function(l){function d(h,m,p){var f=Date.now(),g=0;l(h,m,function y(v){if(v&&(v.code==="EACCES"||v.code==="EPERM"||v.code==="EBUSY")&&Date.now()-f<6e4){setTimeout(function(){e.stat(m,function(b,w){b&&b.code==="ENOENT"?l(h,m,y):p(v)})},g),g<100&&(g+=10);return}p&&p(v)})}return Object.setPrototypeOf&&Object.setPrototypeOf(d,l),d})(e.rename)),e.read=typeof e.read!="function"?e.read:(function(l){function d(h,m,p,f,g,y){var v;if(y&&typeof y=="function"){var b=0;v=function(w,S,q){if(w&&w.code==="EAGAIN"&&b<10)return b++,l.call(e,h,m,p,f,g,v);y.apply(this,arguments)}}return l.call(e,h,m,p,f,g,v)}return Object.setPrototypeOf&&Object.setPrototypeOf(d,l),d})(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:(function(l){return function(d,h,m,p,f){for(var g=0;;)try{return l.call(e,d,h,m,p,f)}catch(y){if(y.code==="EAGAIN"&&g<10){g++;continue}throw y}}})(e.readSync);function t(l){l.lchmod=function(d,h,m){l.open(d,Rn.O_WRONLY|Rn.O_SYMLINK,h,function(p,f){if(p){m&&m(p);return}l.fchmod(f,h,function(g){l.close(f,function(y){m&&m(g||y)})})})},l.lchmodSync=function(d,h){var m=l.openSync(d,Rn.O_WRONLY|Rn.O_SYMLINK,h),p=!0,f;try{f=l.fchmodSync(m,h),p=!1}finally{if(p)try{l.closeSync(m)}catch{}else l.closeSync(m)}return f}}function r(l){Rn.hasOwnProperty("O_SYMLINK")&&l.futimes?(l.lutimes=function(d,h,m,p){l.open(d,Rn.O_SYMLINK,function(f,g){if(f){p&&p(f);return}l.futimes(g,h,m,function(y){l.close(g,function(v){p&&p(y||v)})})})},l.lutimesSync=function(d,h,m){var p=l.openSync(d,Rn.O_SYMLINK),f,g=!0;try{f=l.futimesSync(p,h,m),g=!1}finally{if(g)try{l.closeSync(p)}catch{}else l.closeSync(p)}return f}):l.futimes&&(l.lutimes=function(d,h,m,p){p&&process.nextTick(p)},l.lutimesSync=function(){})}function n(l){return l&&function(d,h,m){return l.call(e,d,h,function(p){c(p)&&(p=null),m&&m.apply(this,arguments)})}}function i(l){return l&&function(d,h){try{return l.call(e,d,h)}catch(m){if(!c(m))throw m}}}function o(l){return l&&function(d,h,m,p){return l.call(e,d,h,m,function(f){c(f)&&(f=null),p&&p.apply(this,arguments)})}}function s(l){return l&&function(d,h,m){try{return l.call(e,d,h,m)}catch(p){if(!c(p))throw p}}}function a(l){return l&&function(d,h,m){typeof h=="function"&&(m=h,h=null);function p(f,g){g&&(g.uid<0&&(g.uid+=4294967296),g.gid<0&&(g.gid+=4294967296)),m&&m.apply(this,arguments)}return h?l.call(e,d,h,p):l.call(e,d,p)}}function u(l){return l&&function(d,h){var m=h?l.call(e,d,h):l.call(e,d);return m&&(m.uid<0&&(m.uid+=4294967296),m.gid<0&&(m.gid+=4294967296)),m}}function c(l){if(!l||l.code==="ENOSYS")return!0;var d=!process.getuid||process.getuid()!==0;return!!(d&&(l.code==="EINVAL"||l.code==="EPERM"))}}});var vy=z((BZ,yy)=>{var _y=bn("stream").Stream;yy.exports=PE;function PE(e){return{ReadStream:t,WriteStream:r};function t(n,i){if(!(this instanceof t))return new t(n,i);_y.call(this);var o=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,i=i||{};for(var s=Object.keys(i),a=0,u=s.length;a<u;a++){var c=s[a];this[c]=i[c]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){o._read()});return}e.open(this.path,this.flags,this.mode,function(l,d){if(l){o.emit("error",l),o.readable=!1;return}o.fd=d,o.emit("open",d),o._read()})}function r(n,i){if(!(this instanceof r))return new r(n,i);_y.call(this),this.path=n,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,i=i||{};for(var o=Object.keys(i),s=0,a=o.length;s<a;s++){var u=o[s];this[u]=i[u]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var wy=z((JZ,by)=>{"use strict";by.exports=RE;var CE=Object.getPrototypeOf||function(e){return e.__proto__};function RE(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:CE(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(e,r))}),t}});var cd=z((WZ,ad)=>{var Be=bn("fs"),IE=gy(),jE=vy(),NE=wy(),fc=bn("util"),mt,pc;typeof Symbol=="function"&&typeof Symbol.for=="function"?(mt=Symbol.for("graceful-fs.queue"),pc=Symbol.for("graceful-fs.previous")):(mt="___graceful-fs.queue",pc="___graceful-fs.previous");function ME(){}function Sy(e,t){Object.defineProperty(e,mt,{get:function(){return t}})}var ki=ME;fc.debuglog?ki=fc.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(ki=function(){var e=fc.format.apply(fc,arguments);e="GFS4: "+e.split(/\n/).join(`
4
+ GFS4: `),console.error(e)});Be[mt]||(xy=global[mt]||[],Sy(Be,xy),Be.close=(function(e){function t(r,n){return e.call(Be,r,function(i){i||ky(),typeof n=="function"&&n.apply(this,arguments)})}return Object.defineProperty(t,pc,{value:e}),t})(Be.close),Be.closeSync=(function(e){function t(r){e.apply(Be,arguments),ky()}return Object.defineProperty(t,pc,{value:e}),t})(Be.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){ki(Be[mt]),bn("assert").equal(Be[mt].length,0)}));var xy;global[mt]||Sy(global,Be[mt]);ad.exports=od(NE(Be));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!Be.__patched&&(ad.exports=od(Be),Be.__patched=!0);function od(e){IE(e),e.gracefulify=od,e.createReadStream=S,e.createWriteStream=q;var t=e.readFile;e.readFile=r;function r(C,G,H){return typeof G=="function"&&(H=G,G=null),fe(C,G,H);function fe(ge,j,$,R){return t(ge,j,function(N){N&&(N.code==="EMFILE"||N.code==="ENFILE")?go([fe,[ge,j,$],N,R||Date.now(),Date.now()]):typeof $=="function"&&$.apply(this,arguments)})}}var n=e.writeFile;e.writeFile=i;function i(C,G,H,fe){return typeof H=="function"&&(fe=H,H=null),ge(C,G,H,fe);function ge(j,$,R,N,I){return n(j,$,R,function(V){V&&(V.code==="EMFILE"||V.code==="ENFILE")?go([ge,[j,$,R,N],V,I||Date.now(),Date.now()]):typeof N=="function"&&N.apply(this,arguments)})}}var o=e.appendFile;o&&(e.appendFile=s);function s(C,G,H,fe){return typeof H=="function"&&(fe=H,H=null),ge(C,G,H,fe);function ge(j,$,R,N,I){return o(j,$,R,function(V){V&&(V.code==="EMFILE"||V.code==="ENFILE")?go([ge,[j,$,R,N],V,I||Date.now(),Date.now()]):typeof N=="function"&&N.apply(this,arguments)})}}var a=e.copyFile;a&&(e.copyFile=u);function u(C,G,H,fe){return typeof H=="function"&&(fe=H,H=0),ge(C,G,H,fe);function ge(j,$,R,N,I){return a(j,$,R,function(V){V&&(V.code==="EMFILE"||V.code==="ENFILE")?go([ge,[j,$,R,N],V,I||Date.now(),Date.now()]):typeof N=="function"&&N.apply(this,arguments)})}}var c=e.readdir;e.readdir=d;var l=/^v[0-5]\./;function d(C,G,H){typeof G=="function"&&(H=G,G=null);var fe=l.test(process.version)?function($,R,N,I){return c($,ge($,R,N,I))}:function($,R,N,I){return c($,R,ge($,R,N,I))};return fe(C,G,H);function ge(j,$,R,N){return function(I,V){I&&(I.code==="EMFILE"||I.code==="ENFILE")?go([fe,[j,$,R],I,N||Date.now(),Date.now()]):(V&&V.sort&&V.sort(),typeof R=="function"&&R.call(this,I,V))}}}if(process.version.substr(0,4)==="v0.8"){var h=jE(e);y=h.ReadStream,b=h.WriteStream}var m=e.ReadStream;m&&(y.prototype=Object.create(m.prototype),y.prototype.open=v);var p=e.WriteStream;p&&(b.prototype=Object.create(p.prototype),b.prototype.open=w),Object.defineProperty(e,"ReadStream",{get:function(){return y},set:function(C){y=C},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return b},set:function(C){b=C},enumerable:!0,configurable:!0});var f=y;Object.defineProperty(e,"FileReadStream",{get:function(){return f},set:function(C){f=C},enumerable:!0,configurable:!0});var g=b;Object.defineProperty(e,"FileWriteStream",{get:function(){return g},set:function(C){g=C},enumerable:!0,configurable:!0});function y(C,G){return this instanceof y?(m.apply(this,arguments),this):y.apply(Object.create(y.prototype),arguments)}function v(){var C=this;ce(C.path,C.flags,C.mode,function(G,H){G?(C.autoClose&&C.destroy(),C.emit("error",G)):(C.fd=H,C.emit("open",H),C.read())})}function b(C,G){return this instanceof b?(p.apply(this,arguments),this):b.apply(Object.create(b.prototype),arguments)}function w(){var C=this;ce(C.path,C.flags,C.mode,function(G,H){G?(C.destroy(),C.emit("error",G)):(C.fd=H,C.emit("open",H))})}function S(C,G){return new e.ReadStream(C,G)}function q(C,G){return new e.WriteStream(C,G)}var K=e.open;e.open=ce;function ce(C,G,H,fe){return typeof H=="function"&&(fe=H,H=null),ge(C,G,H,fe);function ge(j,$,R,N,I){return K(j,$,R,function(V,ye){V&&(V.code==="EMFILE"||V.code==="ENFILE")?go([ge,[j,$,R,N],V,I||Date.now(),Date.now()]):typeof N=="function"&&N.apply(this,arguments)})}}return e}function go(e){ki("ENQUEUE",e[0].name,e[1]),Be[mt].push(e),sd()}var mc;function ky(){for(var e=Date.now(),t=0;t<Be[mt].length;++t)Be[mt][t].length>2&&(Be[mt][t][3]=e,Be[mt][t][4]=e);sd()}function sd(){if(clearTimeout(mc),mc=void 0,Be[mt].length!==0){var e=Be[mt].shift(),t=e[0],r=e[1],n=e[2],i=e[3],o=e[4];if(i===void 0)ki("RETRY",t.name,r),t.apply(null,r);else if(Date.now()-i>=6e4){ki("TIMEOUT",t.name,r);var s=r.pop();typeof s=="function"&&s.call(null,n)}else{var a=Date.now()-o,u=Math.max(o-i,1),c=Math.min(u*1.2,100);a>=c?(ki("RETRY",t.name,r),t.apply(null,r.concat([i]))):Be[mt].push(e)}mc===void 0&&(mc=setTimeout(sd,0))}}});var $y=z((HZ,Ty)=>{function ar(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Ty.exports=ar;ar.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};ar.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null};ar.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),r=this._timeouts.shift();else return!1;var n=this,i=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r);return this._options.unref&&i.unref(),!0};ar.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};ar.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)};ar.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)};ar.prototype.start=ar.prototype.try;ar.prototype.errors=function(){return this._errors};ar.prototype.attempts=function(){return this._attempts};ar.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var i=this._errors[n],o=i.message,s=(e[o]||0)+1;e[o]=s,s>=r&&(t=i,r=s)}return t}});var Ey=z(Si=>{var DE=$y();Si.operation=function(e){var t=Si.timeouts(e);return new DE(t,{forever:e&&e.forever,unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})};Si.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i<t.retries;i++)n.push(this.createTimeout(i,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(i,t)),n.sort(function(o,s){return o-s}),n};Si.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,n=Math.round(r*t.minTimeout*Math.pow(t.factor,e));return n=Math.min(n,t.maxTimeout),n};Si.wrap=function(e,t,r){if(t instanceof Array&&(r=t,t=null),!r){r=[];for(var n in e)typeof e[n]=="function"&&r.push(n)}for(var i=0;i<r.length;i++){var o=r[i],s=e[o];e[o]=function(u){var c=Si.operation(t),l=Array.prototype.slice.call(arguments,1),d=l.pop();l.push(function(h){c.retry(h)||(h&&(arguments[0]=c.mainError()),d.apply(this,arguments))}),c.attempt(function(){u.apply(e,l)})}.bind(e,s),e[o].options=t}}});var Oy=z((QZ,zy)=>{zy.exports=Ey()});var Ay=z((XZ,hc)=>{hc.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&hc.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&hc.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var jy=z((YZ,vo)=>{var Ne=global.process,Ti=function(e){return e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function"};Ti(Ne)?(Py=bn("assert"),_o=Ay(),Cy=/^win/i.test(Ne.platform),xs=bn("events"),typeof xs!="function"&&(xs=xs.EventEmitter),Ne.__signal_exit_emitter__?at=Ne.__signal_exit_emitter__:(at=Ne.__signal_exit_emitter__=new xs,at.count=0,at.emitted={}),at.infinite||(at.setMaxListeners(1/0),at.infinite=!0),vo.exports=function(e,t){if(!Ti(global.process))return function(){};Py.equal(typeof e,"function","a callback must be provided for exit handler"),yo===!1&&ld();var r="exit";t&&t.alwaysLast&&(r="afterexit");var n=function(){at.removeListener(r,e),at.listeners("exit").length===0&&at.listeners("afterexit").length===0&&gc()};return at.on(r,e),n},gc=function(){!yo||!Ti(global.process)||(yo=!1,_o.forEach(function(t){try{Ne.removeListener(t,_c[t])}catch{}}),Ne.emit=yc,Ne.reallyExit=ud,at.count-=1)},vo.exports.unload=gc,$i=function(t,r,n){at.emitted[t]||(at.emitted[t]=!0,at.emit(t,r,n))},_c={},_o.forEach(function(e){_c[e]=function(){if(Ti(global.process)){var r=Ne.listeners(e);r.length===at.count&&(gc(),$i("exit",null,e),$i("afterexit",null,e),Cy&&e==="SIGHUP"&&(e="SIGINT"),Ne.kill(Ne.pid,e))}}}),vo.exports.signals=function(){return _o},yo=!1,ld=function(){yo||!Ti(global.process)||(yo=!0,at.count+=1,_o=_o.filter(function(t){try{return Ne.on(t,_c[t]),!0}catch{return!1}}),Ne.emit=Iy,Ne.reallyExit=Ry)},vo.exports.load=ld,ud=Ne.reallyExit,Ry=function(t){Ti(global.process)&&(Ne.exitCode=t||0,$i("exit",Ne.exitCode,null),$i("afterexit",Ne.exitCode,null),ud.call(Ne,Ne.exitCode))},yc=Ne.emit,Iy=function(t,r){if(t==="exit"&&Ti(global.process)){r!==void 0&&(Ne.exitCode=r);var n=yc.apply(this,arguments);return $i("exit",Ne.exitCode,null),$i("afterexit",Ne.exitCode,null),n}else return yc.apply(this,arguments)}):vo.exports=function(){return function(){}};var Py,_o,Cy,xs,at,gc,$i,_c,yo,ld,ud,Ry,yc,Iy});var Ly=z((eL,ks)=>{"use strict";var ZE=bn("path"),md=cd(),LE=Oy(),qE=jy(),ln={};function bo(e,t){return t.lockfilePath||`${e}.lock`}function pd(e,t,r){if(!t.realpath)return r(null,ZE.resolve(e));t.fs.realpath(e,r)}function dd(e,t,r){t.fs.mkdir(bo(e,t),n=>{if(!n)return r();if(n.code!=="EEXIST")return r(n);if(t.stale<=0)return r(Object.assign(new Error("Lock file is already being hold"),{code:"ELOCKED",file:e}));t.fs.stat(bo(e,t),(i,o)=>{if(i)return i.code==="ENOENT"?dd(e,{...t,stale:0},r):r(i);if(!My(o,t))return r(Object.assign(new Error("Lock file is already being hold"),{code:"ELOCKED",file:e}));Dy(e,t,s=>{if(s)return r(s);dd(e,{...t,stale:0},r)})})})}function My(e,t){return e.mtime.getTime()<Date.now()-t.stale}function Dy(e,t,r){t.fs.rmdir(bo(e,t),n=>{if(n&&n.code!=="ENOENT")return r(n);r()})}function fd(e,t){let r=ln[e];r.updateTimeout||(r.updateDelay=r.updateDelay||t.update,r.updateTimeout=setTimeout(()=>{let n=Date.now()/1e3;r.updateTimeout=null,t.fs.utimes(bo(e,t),n,n,i=>{if(!r.released){if(r.lastUpdate<=Date.now()-t.stale&&r.lastUpdate>Date.now()-t.stale*2){let o=Object.assign(new Error(r.updateError||"Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"});return Ny(e,r,o)}if(i)return i.code==="ENOENT"?Ny(e,r,Object.assign(i,{code:"ECOMPROMISED"})):(r.updateError=i,r.updateDelay=1e3,fd(e,t));r.lastUpdate=Date.now(),r.updateError=null,r.updateDelay=null,fd(e,t)}})},r.updateDelay),r.updateTimeout.unref&&r.updateTimeout.unref())}function Ny(e,t,r){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),ln[e]===t&&delete ln[e],t.options.onCompromised(r)}function FE(e,t,r){t={stale:1e4,update:null,realpath:!0,retries:0,fs:md,onCompromised:n=>{throw n},...t},t.retries=t.retries||0,t.retries=typeof t.retries=="number"?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),pd(e,t,(n,i)=>{if(n)return r(n);let o=LE.operation(t.retries);o.attempt(()=>{dd(i,t,s=>{if(o.retry(s))return;if(s)return r(o.mainError());let a=ln[i]={options:t,lastUpdate:Date.now()};fd(i,t),r(null,u=>{if(a.released)return u&&u(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));Zy(i,{...t,realpath:!1},u)})})})})}function Zy(e,t,r){t={fs:md,realpath:!0,...t},pd(e,t,(n,i)=>{if(n)return r(n);let o=ln[i];if(!o)return r(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));o.updateTimeout&&clearTimeout(o.updateTimeout),o.released=!0,delete ln[i],Dy(i,t,r)})}function UE(e,t,r){t={stale:1e4,realpath:!0,fs:md,...t},t.stale=Math.max(t.stale||0,2e3),pd(e,t,(n,i)=>{if(n)return r(n);t.fs.stat(bo(i,t),(o,s)=>o?o.code==="ENOENT"?r(null,!1):r(o):r(null,!My(s,t)))})}function GE(){return ln}qE(()=>{for(let e in ln){let t=ln[e].options;try{t.fs.rmdirSync(bo(e,t))}catch{}}});ks.exports.lock=FE;ks.exports.unlock=Zy;ks.exports.check=UE;ks.exports.getLocks=GE});var Fy=z((tL,qy)=>{"use strict";var VE=cd();function BE(e){let t=["mkdir","realpath","stat","rmdir","utimes"],r={...e};return t.forEach(n=>{r[n]=(...i)=>{let o=i.pop(),s;try{s=e[`${n}Sync`](...i)}catch(a){return o(a)}o(null,s)}}),r}function JE(e){return(...t)=>new Promise((r,n)=>{t.push((i,o)=>{i?n(i):r(o)}),e(...t)})}function WE(e){return(...t)=>{let r,n;if(t.push((i,o)=>{r=i,n=o}),e(...t),r)throw r;return n}}function HE(e){if(e={...e},e.fs=BE(e.fs||VE),typeof e.retries=="number"&&e.retries>0||e.retries&&typeof e.retries.retries=="number"&&e.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return e}qy.exports={toPromise:JE,toSync:WE,toSyncOptions:HE}});var Gy=z((rL,In)=>{"use strict";var wo=Ly(),{toPromise:vc,toSync:bc,toSyncOptions:hd}=Fy();async function Uy(e,t){let r=await vc(wo.lock)(e,t);return vc(r)}function KE(e,t){let r=bc(wo.lock)(e,hd(t));return bc(r)}function QE(e,t){return vc(wo.unlock)(e,t)}function XE(e,t){return bc(wo.unlock)(e,hd(t))}function YE(e,t){return vc(wo.check)(e,t)}function ez(e,t){return bc(wo.check)(e,hd(t))}In.exports=Uy;In.exports.lock=Uy;In.exports.unlock=QE;In.exports.lockSync=KE;In.exports.unlockSync=XE;In.exports.check=YE;In.exports.checkSync=ez});var Ys=z(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.regexpCode=pe.getEsmExportName=pe.getProperty=pe.safeStringify=pe.stringify=pe.strConcat=pe.addCodeArg=pe.str=pe._=pe.nil=pe._Code=pe.Name=pe.IDENTIFIER=pe._CodeOrName=void 0;var Qs=class{};pe._CodeOrName=Qs;pe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ni=class extends Qs{constructor(t){if(super(),!pe.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};pe.Name=Ni;var dr=class extends Qs{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Ni&&(r[n.str]=(r[n.str]||0)+1),r),{})}};pe._Code=dr;pe.nil=new dr("");function t0(e,...t){let r=[e[0]],n=0;for(;n<t.length;)mp(r,t[n]),r.push(e[++n]);return new dr(r)}pe._=t0;var fp=new dr("+");function r0(e,...t){let r=[Xs(e[0])],n=0;for(;n<t.length;)r.push(fp),mp(r,t[n]),r.push(fp,Xs(e[++n]));return $C(r),new dr(r)}pe.str=r0;function mp(e,t){t instanceof dr?e.push(...t._items):t instanceof Ni?e.push(t):e.push(OC(t))}pe.addCodeArg=mp;function $C(e){let t=1;for(;t<e.length-1;){if(e[t]===fp){let r=EC(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function EC(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Ni||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Ni))return`"${e}${t.slice(1)}`}function zC(e,t){return t.emptyStr()?e:e.emptyStr()?t:r0`${e}${t}`}pe.strConcat=zC;function OC(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Xs(Array.isArray(e)?e.join(","):e)}function AC(e){return new dr(Xs(e))}pe.stringify=AC;function Xs(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}pe.safeStringify=Xs;function PC(e){return typeof e=="string"&&pe.IDENTIFIER.test(e)?new dr(`.${e}`):t0`[${e}]`}pe.getProperty=PC;function CC(e){if(typeof e=="string"&&pe.IDENTIFIER.test(e))return new dr(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}pe.getEsmExportName=CC;function RC(e){return new dr(e.toString())}pe.regexpCode=RC});var gp=z(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.ValueScope=Gt.ValueScopeName=Gt.Scope=Gt.varKinds=Gt.UsedValueState=void 0;var Ut=Ys(),pp=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},gl;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(gl||(Gt.UsedValueState=gl={}));Gt.varKinds={const:new Ut.Name("const"),let:new Ut.Name("let"),var:new Ut.Name("var")};var _l=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ut.Name?t:this.name(t)}name(t){return new Ut.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Gt.Scope=_l;var yl=class extends Ut.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ut._)`.${new Ut.Name(r)}[${n}]`}};Gt.ValueScopeName=yl;var IC=(0,Ut._)`\n`,hp=class extends _l{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?IC:Ut.nil}}get(){return this._scope}name(t){return new yl(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(t),{prefix:o}=i,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let l=a.get(s);if(l)return l}else a=this._values[o]=new Map;a.set(s,i);let u=this._scope[o]||(this._scope[o]=[]),c=u.length;return u[c]=r.ref,i.setValue(r,{property:o,itemIndex:c}),i}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ut._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(t,r,n={},i){let o=Ut.nil;for(let s in t){let a=t[s];if(!a)continue;let u=n[s]=n[s]||new Map;a.forEach(c=>{if(u.has(c))return;u.set(c,gl.Started);let l=r(c);if(l){let d=this.opts.es5?Gt.varKinds.var:Gt.varKinds.const;o=(0,Ut._)`${o}${d} ${c} = ${l};${this.opts._n}`}else if(l=i?.(c))o=(0,Ut._)`${o}${l}${this.opts._n}`;else throw new pp(c);u.set(c,gl.Completed)})}return o}};Gt.ValueScope=hp});var ne=z(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.or=ie.and=ie.not=ie.CodeGen=ie.operators=ie.varKinds=ie.ValueScopeName=ie.ValueScope=ie.Scope=ie.Name=ie.regexpCode=ie.stringify=ie.getProperty=ie.nil=ie.strConcat=ie.str=ie._=void 0;var de=Ys(),Tr=gp(),qn=Ys();Object.defineProperty(ie,"_",{enumerable:!0,get:function(){return qn._}});Object.defineProperty(ie,"str",{enumerable:!0,get:function(){return qn.str}});Object.defineProperty(ie,"strConcat",{enumerable:!0,get:function(){return qn.strConcat}});Object.defineProperty(ie,"nil",{enumerable:!0,get:function(){return qn.nil}});Object.defineProperty(ie,"getProperty",{enumerable:!0,get:function(){return qn.getProperty}});Object.defineProperty(ie,"stringify",{enumerable:!0,get:function(){return qn.stringify}});Object.defineProperty(ie,"regexpCode",{enumerable:!0,get:function(){return qn.regexpCode}});Object.defineProperty(ie,"Name",{enumerable:!0,get:function(){return qn.Name}});var xl=gp();Object.defineProperty(ie,"Scope",{enumerable:!0,get:function(){return xl.Scope}});Object.defineProperty(ie,"ValueScope",{enumerable:!0,get:function(){return xl.ValueScope}});Object.defineProperty(ie,"ValueScopeName",{enumerable:!0,get:function(){return xl.ValueScopeName}});Object.defineProperty(ie,"varKinds",{enumerable:!0,get:function(){return xl.varKinds}});ie.operators={GT:new de._Code(">"),GTE:new de._Code(">="),LT:new de._Code("<"),LTE:new de._Code("<="),EQ:new de._Code("==="),NEQ:new de._Code("!=="),NOT:new de._Code("!"),OR:new de._Code("||"),AND:new de._Code("&&"),ADD:new de._Code("+")};var mn=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},_p=class extends mn{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Tr.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Io(this.rhs,t,r)),this}get names(){return this.rhs instanceof de._CodeOrName?this.rhs.names:{}}},vl=class extends mn{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof de.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Io(this.rhs,t,r),this}get names(){let t=this.lhs instanceof de.Name?{}:{...this.lhs.names};return wl(t,this.rhs)}},yp=class extends vl{constructor(t,r,n,i){super(t,n,i),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},vp=class extends mn{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},bp=class extends mn{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},wp=class extends mn{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},xp=class extends mn{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Io(this.code,t,r),this}get names(){return this.code instanceof de._CodeOrName?this.code.names:{}}},ea=class extends mn{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(t,r)||(jC(t,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Zi(t,r.names),{})}},pn=class extends ea{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},kp=class extends ea{},Ro=class extends pn{};Ro.kind="else";var Mi=class e extends pn{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Ro(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(n0(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=Io(this.condition,t,r),this}get names(){let t=super.names;return wl(t,this.condition),this.else&&Zi(t,this.else.names),t}};Mi.kind="if";var Di=class extends pn{};Di.kind="for";var Sp=class extends Di{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=Io(this.iteration,t,r),this}get names(){return Zi(super.names,this.iteration.names)}},Tp=class extends Di{constructor(t,r,n,i){super(),this.varKind=t,this.name=r,this.from=n,this.to=i}render(t){let r=t.es5?Tr.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(t)}get names(){let t=wl(super.names,this.from);return wl(t,this.to)}},bl=class extends Di{constructor(t,r,n,i){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=i}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=Io(this.iterable,t,r),this}get names(){return Zi(super.names,this.iterable.names)}},ta=class extends pn{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};ta.kind="func";var ra=class extends ea{render(t){return"return "+super.render(t)}};ra.kind="return";var $p=class extends pn{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,i;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(i=this.finally)===null||i===void 0||i.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Zi(t,this.catch.names),this.finally&&Zi(t,this.finally.names),t}},na=class extends pn{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};na.kind="catch";var ia=class extends pn{render(t){return"finally"+super.render(t)}};ia.kind="finally";var Ep=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
5
+ `:""},this._extScope=t,this._scope=new Tr.Scope({parent:t}),this._nodes=[new kp]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new _p(t,o,n)),o}const(t,r,n){return this._def(Tr.varKinds.const,t,r,n)}let(t,r,n){return this._def(Tr.varKinds.let,t,r,n)}var(t,r,n){return this._def(Tr.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new vl(t,r,n))}add(t,r){return this._leafNode(new yp(t,ie.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==de.nil&&this._leafNode(new xp(t)),this}object(...t){let r=["{"];for(let[n,i]of t)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,de.addCodeArg)(r,i));return r.push("}"),new de._Code(r)}if(t,r,n){if(this._blockNode(new Mi(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new Mi(t))}else(){return this._elseNode(new Ro)}endIf(){return this._endBlockNode(Mi,Ro)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Sp(t),r)}forRange(t,r,n,i,o=this.opts.es5?Tr.varKinds.var:Tr.varKinds.let){let s=this._scope.toName(t);return this._for(new Tp(o,s,r,n),()=>i(s))}forOf(t,r,n,i=Tr.varKinds.const){let o=this._scope.toName(t);if(this.opts.es5){let s=r instanceof de.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,de._)`${s}.length`,a=>{this.var(o,(0,de._)`${s}[${a}]`),n(o)})}return this._for(new bl("of",i,o,r),()=>n(o))}forIn(t,r,n,i=this.opts.es5?Tr.varKinds.var:Tr.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,de._)`Object.keys(${r})`,n);let o=this._scope.toName(t);return this._for(new bl("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(Di)}label(t){return this._leafNode(new vp(t))}break(t){return this._leafNode(new bp(t))}return(t){let r=new ra;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ra)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new $p;if(this._blockNode(i),this.code(t),r){let o=this.name("e");this._currNode=i.catch=new na(o),r(o)}return n&&(this._currNode=i.finally=new ia,this.code(n)),this._endBlockNode(na,ia)}throw(t){return this._leafNode(new wp(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=de.nil,n,i){return this._blockNode(new ta(t,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(ta)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof Mi))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};ie.CodeGen=Ep;function Zi(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function wl(e,t){return t instanceof de._CodeOrName?Zi(e,t.names):e}function Io(e,t,r){if(e instanceof de.Name)return n(e);if(!i(e))return e;return new de._Code(e._items.reduce((o,s)=>(s instanceof de.Name&&(s=n(s)),s instanceof de._Code?o.push(...s._items):o.push(s),o),[]));function n(o){let s=r[o.str];return s===void 0||t[o.str]!==1?o:(delete t[o.str],s)}function i(o){return o instanceof de._Code&&o._items.some(s=>s instanceof de.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function jC(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function n0(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,de._)`!${zp(e)}`}ie.not=n0;var NC=i0(ie.operators.AND);function MC(...e){return e.reduce(NC)}ie.and=MC;var DC=i0(ie.operators.OR);function ZC(...e){return e.reduce(DC)}ie.or=ZC;function i0(e){return(t,r)=>t===de.nil?r:r===de.nil?t:(0,de._)`${zp(t)} ${e} ${zp(r)}`}function zp(e){return e instanceof de.Name?e:(0,de._)`(${e})`}});var he=z(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.checkStrictMode=oe.getErrorPath=oe.Type=oe.useFunc=oe.setEvaluated=oe.evaluatedPropsToName=oe.mergeEvaluated=oe.eachItem=oe.unescapeJsonPointer=oe.escapeJsonPointer=oe.escapeFragment=oe.unescapeFragment=oe.schemaRefOrVal=oe.schemaHasRulesButRef=oe.schemaHasRules=oe.checkUnknownRules=oe.alwaysValidSchema=oe.toHash=void 0;var $e=ne(),LC=Ys();function qC(e){let t={};for(let r of e)t[r]=!0;return t}oe.toHash=qC;function FC(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(a0(e,t),!c0(t,e.self.RULES.all))}oe.alwaysValidSchema=FC;function a0(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let i=n.RULES.keywords;for(let o in t)i[o]||d0(e,`unknown keyword: "${o}"`)}oe.checkUnknownRules=a0;function c0(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}oe.schemaHasRules=c0;function UC(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}oe.schemaHasRulesButRef=UC;function GC({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,$e._)`${r}`}return(0,$e._)`${e}${t}${(0,$e.getProperty)(n)}`}oe.schemaRefOrVal=GC;function VC(e){return l0(decodeURIComponent(e))}oe.unescapeFragment=VC;function BC(e){return encodeURIComponent(Ap(e))}oe.escapeFragment=BC;function Ap(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}oe.escapeJsonPointer=Ap;function l0(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}oe.unescapeJsonPointer=l0;function JC(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}oe.eachItem=JC;function o0({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,o,s,a)=>{let u=s===void 0?o:s instanceof $e.Name?(o instanceof $e.Name?e(i,o,s):t(i,o,s),s):o instanceof $e.Name?(t(i,s,o),o):r(o,s);return a===$e.Name&&!(u instanceof $e.Name)?n(i,u):u}}oe.mergeEvaluated={props:o0({mergeNames:(e,t,r)=>e.if((0,$e._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,$e._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,$e._)`${r} || {}`).code((0,$e._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,$e._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,$e._)`${r} || {}`),Pp(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:u0}),items:o0({mergeNames:(e,t,r)=>e.if((0,$e._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,$e._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,$e._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,$e._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function u0(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,$e._)`{}`);return t!==void 0&&Pp(e,r,t),r}oe.evaluatedPropsToName=u0;function Pp(e,t,r){Object.keys(r).forEach(n=>e.assign((0,$e._)`${t}${(0,$e.getProperty)(n)}`,!0))}oe.setEvaluated=Pp;var s0={};function WC(e,t){return e.scopeValue("func",{ref:t,code:s0[t.code]||(s0[t.code]=new LC._Code(t.code))})}oe.useFunc=WC;var Op;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Op||(oe.Type=Op={}));function HC(e,t,r){if(e instanceof $e.Name){let n=t===Op.Num;return r?n?(0,$e._)`"[" + ${e} + "]"`:(0,$e._)`"['" + ${e} + "']"`:n?(0,$e._)`"/" + ${e}`:(0,$e._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,$e.getProperty)(e).toString():"/"+Ap(e)}oe.getErrorPath=HC;function d0(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}oe.checkStrictMode=d0});var hn=z(Cp=>{"use strict";Object.defineProperty(Cp,"__esModule",{value:!0});var Tt=ne(),KC={data:new Tt.Name("data"),valCxt:new Tt.Name("valCxt"),instancePath:new Tt.Name("instancePath"),parentData:new Tt.Name("parentData"),parentDataProperty:new Tt.Name("parentDataProperty"),rootData:new Tt.Name("rootData"),dynamicAnchors:new Tt.Name("dynamicAnchors"),vErrors:new Tt.Name("vErrors"),errors:new Tt.Name("errors"),this:new Tt.Name("this"),self:new Tt.Name("self"),scope:new Tt.Name("scope"),json:new Tt.Name("json"),jsonPos:new Tt.Name("jsonPos"),jsonLen:new Tt.Name("jsonLen"),jsonPart:new Tt.Name("jsonPart")};Cp.default=KC});var oa=z($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.extendErrors=$t.resetErrorsCount=$t.reportExtraError=$t.reportError=$t.keyword$DataError=$t.keywordError=void 0;var me=ne(),kl=he(),jt=hn();$t.keywordError={message:({keyword:e})=>(0,me.str)`must pass "${e}" keyword validation`};$t.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,me.str)`"${e}" keyword must be ${t} ($data)`:(0,me.str)`"${e}" keyword is invalid ($data)`};function QC(e,t=$t.keywordError,r,n){let{it:i}=e,{gen:o,compositeRule:s,allErrors:a}=i,u=p0(e,t,r);n??(s||a)?f0(o,u):m0(i,(0,me._)`[${u}]`)}$t.reportError=QC;function XC(e,t=$t.keywordError,r){let{it:n}=e,{gen:i,compositeRule:o,allErrors:s}=n,a=p0(e,t,r);f0(i,a),o||s||m0(n,jt.default.vErrors)}$t.reportExtraError=XC;function YC(e,t){e.assign(jt.default.errors,t),e.if((0,me._)`${jt.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,me._)`${jt.default.vErrors}.length`,t),()=>e.assign(jt.default.vErrors,null)))}$t.resetErrorsCount=YC;function e1({gen:e,keyword:t,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",i,jt.default.errors,a=>{e.const(s,(0,me._)`${jt.default.vErrors}[${a}]`),e.if((0,me._)`${s}.instancePath === undefined`,()=>e.assign((0,me._)`${s}.instancePath`,(0,me.strConcat)(jt.default.instancePath,o.errorPath))),e.assign((0,me._)`${s}.schemaPath`,(0,me.str)`${o.errSchemaPath}/${t}`),o.opts.verbose&&(e.assign((0,me._)`${s}.schema`,r),e.assign((0,me._)`${s}.data`,n))})}$t.extendErrors=e1;function f0(e,t){let r=e.const("err",t);e.if((0,me._)`${jt.default.vErrors} === null`,()=>e.assign(jt.default.vErrors,(0,me._)`[${r}]`),(0,me._)`${jt.default.vErrors}.push(${r})`),e.code((0,me._)`${jt.default.errors}++`)}function m0(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw((0,me._)`new ${e.ValidationError}(${t})`):(r.assign((0,me._)`${n}.errors`,t),r.return(!1))}var Li={keyword:new me.Name("keyword"),schemaPath:new me.Name("schemaPath"),params:new me.Name("params"),propertyName:new me.Name("propertyName"),message:new me.Name("message"),schema:new me.Name("schema"),parentSchema:new me.Name("parentSchema")};function p0(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,me._)`{}`:t1(e,t,r)}function t1(e,t,r={}){let{gen:n,it:i}=e,o=[r1(i,r),n1(e,r)];return i1(e,t,o),n.object(...o)}function r1({errorPath:e},{instancePath:t}){let r=t?(0,me.str)`${e}${(0,kl.getErrorPath)(t,kl.Type.Str)}`:e;return[jt.default.instancePath,(0,me.strConcat)(jt.default.instancePath,r)]}function n1({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:(0,me.str)`${t}/${e}`;return r&&(i=(0,me.str)`${i}${(0,kl.getErrorPath)(r,kl.Type.Str)}`),[Li.schemaPath,i]}function i1(e,{params:t,message:r},n){let{keyword:i,data:o,schemaValue:s,it:a}=e,{opts:u,propertyName:c,topSchemaRef:l,schemaPath:d}=a;n.push([Li.keyword,i],[Li.params,typeof t=="function"?t(e):t||(0,me._)`{}`]),u.messages&&n.push([Li.message,typeof r=="function"?r(e):r]),u.verbose&&n.push([Li.schema,s],[Li.parentSchema,(0,me._)`${l}${d}`],[jt.default.data,o]),c&&n.push([Li.propertyName,c])}});var g0=z(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.boolOrEmptySchema=jo.topBoolOrEmptySchema=void 0;var o1=oa(),s1=ne(),a1=hn(),c1={message:"boolean schema is false"};function l1(e){let{gen:t,schema:r,validateName:n}=e;r===!1?h0(e,!1):typeof r=="object"&&r.$async===!0?t.return(a1.default.data):(t.assign((0,s1._)`${n}.errors`,null),t.return(!0))}jo.topBoolOrEmptySchema=l1;function u1(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),h0(e)):r.var(t,!0)}jo.boolOrEmptySchema=u1;function h0(e,t){let{gen:r,data:n}=e,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,o1.reportError)(i,c1,void 0,t)}});var Rp=z(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.getRules=No.isJSONType=void 0;var d1=["string","number","integer","boolean","null","object","array"],f1=new Set(d1);function m1(e){return typeof e=="string"&&f1.has(e)}No.isJSONType=m1;function p1(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}No.getRules=p1});var Ip=z(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.shouldUseRule=Fn.shouldUseGroup=Fn.schemaHasRulesForType=void 0;function h1({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&_0(e,n)}Fn.schemaHasRulesForType=h1;function _0(e,t){return t.rules.some(r=>y0(e,r))}Fn.shouldUseGroup=_0;function y0(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}Fn.shouldUseRule=y0});var sa=z(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.reportTypeError=Et.checkDataTypes=Et.checkDataType=Et.coerceAndCheckDataType=Et.getJSONTypes=Et.getSchemaTypes=Et.DataType=void 0;var g1=Rp(),_1=Ip(),y1=oa(),te=ne(),v0=he(),Mo;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Mo||(Et.DataType=Mo={}));function v1(e){let t=b0(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}Et.getSchemaTypes=v1;function b0(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(g1.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Et.getJSONTypes=b0;function b1(e,t){let{gen:r,data:n,opts:i}=e,o=w1(t,i.coerceTypes),s=t.length>0&&!(o.length===0&&t.length===1&&(0,_1.schemaHasRulesForType)(e,t[0]));if(s){let a=Np(t,n,i.strictNumbers,Mo.Wrong);r.if(a,()=>{o.length?x1(e,t,o):Mp(e)})}return s}Et.coerceAndCheckDataType=b1;var w0=new Set(["string","number","integer","boolean","null"]);function w1(e,t){return t?e.filter(r=>w0.has(r)||t==="array"&&r==="array"):[]}function x1(e,t,r){let{gen:n,data:i,opts:o}=e,s=n.let("dataType",(0,te._)`typeof ${i}`),a=n.let("coerced",(0,te._)`undefined`);o.coerceTypes==="array"&&n.if((0,te._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,te._)`${i}[0]`).assign(s,(0,te._)`typeof ${i}`).if(Np(t,i,o.strictNumbers),()=>n.assign(a,i))),n.if((0,te._)`${a} !== undefined`);for(let c of r)(w0.has(c)||c==="array"&&o.coerceTypes==="array")&&u(c);n.else(),Mp(e),n.endIf(),n.if((0,te._)`${a} !== undefined`,()=>{n.assign(i,a),k1(e,a)});function u(c){switch(c){case"string":n.elseIf((0,te._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,te._)`"" + ${i}`).elseIf((0,te._)`${i} === null`).assign(a,(0,te._)`""`);return;case"number":n.elseIf((0,te._)`${s} == "boolean" || ${i} === null
6
+ || (${s} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,te._)`+${i}`);return;case"integer":n.elseIf((0,te._)`${s} === "boolean" || ${i} === null
7
+ || (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,te._)`+${i}`);return;case"boolean":n.elseIf((0,te._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,te._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,te._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,te._)`${s} === "string" || ${s} === "number"
8
+ || ${s} === "boolean" || ${i} === null`).assign(a,(0,te._)`[${i}]`)}}}function k1({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,te._)`${t} !== undefined`,()=>e.assign((0,te._)`${t}[${r}]`,n))}function jp(e,t,r,n=Mo.Correct){let i=n===Mo.Correct?te.operators.EQ:te.operators.NEQ,o;switch(e){case"null":return(0,te._)`${t} ${i} null`;case"array":o=(0,te._)`Array.isArray(${t})`;break;case"object":o=(0,te._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=s((0,te._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=s();break;default:return(0,te._)`typeof ${t} ${i} ${e}`}return n===Mo.Correct?o:(0,te.not)(o);function s(a=te.nil){return(0,te.and)((0,te._)`typeof ${t} == "number"`,a,r?(0,te._)`isFinite(${t})`:te.nil)}}Et.checkDataType=jp;function Np(e,t,r,n){if(e.length===1)return jp(e[0],t,r,n);let i,o=(0,v0.toHash)(e);if(o.array&&o.object){let s=(0,te._)`typeof ${t} != "object"`;i=o.null?s:(0,te._)`!${t} || ${s}`,delete o.null,delete o.array,delete o.object}else i=te.nil;o.number&&delete o.integer;for(let s in o)i=(0,te.and)(i,jp(s,t,r,n));return i}Et.checkDataTypes=Np;var S1={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,te._)`{type: ${e}}`:(0,te._)`{type: ${t}}`};function Mp(e){let t=T1(e);(0,y1.reportError)(t,S1)}Et.reportTypeError=Mp;function T1(e){let{gen:t,data:r,schema:n}=e,i=(0,v0.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var k0=z(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});Sl.assignDefaults=void 0;var Do=ne(),$1=he();function E1(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)x0(e,i,r[i].default);else t==="array"&&Array.isArray(n)&&n.forEach((i,o)=>x0(e,o,i.default))}Sl.assignDefaults=E1;function x0(e,t,r){let{gen:n,compositeRule:i,data:o,opts:s}=e;if(r===void 0)return;let a=(0,Do._)`${o}${(0,Do.getProperty)(t)}`;if(i){(0,$1.checkStrictMode)(e,`default is ignored for: ${a}`);return}let u=(0,Do._)`${a} === undefined`;s.useDefaults==="empty"&&(u=(0,Do._)`${u} || ${a} === null || ${a} === ""`),n.if(u,(0,Do._)`${a} = ${(0,Do.stringify)(r)}`)}});var fr=z(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.validateUnion=Te.validateArray=Te.usePattern=Te.callValidateCode=Te.schemaProperties=Te.allSchemaProperties=Te.noPropertyInData=Te.propertyInData=Te.isOwnProperty=Te.hasPropFunc=Te.reportMissingProp=Te.checkMissingProp=Te.checkReportMissingProp=void 0;var Re=ne(),Dp=he(),Un=hn(),z1=he();function O1(e,t){let{gen:r,data:n,it:i}=e;r.if(Lp(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,Re._)`${t}`},!0),e.error()})}Te.checkReportMissingProp=O1;function A1({gen:e,data:t,it:{opts:r}},n,i){return(0,Re.or)(...n.map(o=>(0,Re.and)(Lp(e,t,o,r.ownProperties),(0,Re._)`${i} = ${o}`)))}Te.checkMissingProp=A1;function P1(e,t){e.setParams({missingProperty:t},!0),e.error()}Te.reportMissingProp=P1;function S0(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Re._)`Object.prototype.hasOwnProperty`})}Te.hasPropFunc=S0;function Zp(e,t,r){return(0,Re._)`${S0(e)}.call(${t}, ${r})`}Te.isOwnProperty=Zp;function C1(e,t,r,n){let i=(0,Re._)`${t}${(0,Re.getProperty)(r)} !== undefined`;return n?(0,Re._)`${i} && ${Zp(e,t,r)}`:i}Te.propertyInData=C1;function Lp(e,t,r,n){let i=(0,Re._)`${t}${(0,Re.getProperty)(r)} === undefined`;return n?(0,Re.or)(i,(0,Re.not)(Zp(e,t,r))):i}Te.noPropertyInData=Lp;function T0(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}Te.allSchemaProperties=T0;function R1(e,t){return T0(t).filter(r=>!(0,Dp.alwaysValidSchema)(e,t[r]))}Te.schemaProperties=R1;function I1({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:o},it:s},a,u,c){let l=c?(0,Re._)`${e}, ${t}, ${n}${i}`:t,d=[[Un.default.instancePath,(0,Re.strConcat)(Un.default.instancePath,o)],[Un.default.parentData,s.parentData],[Un.default.parentDataProperty,s.parentDataProperty],[Un.default.rootData,Un.default.rootData]];s.opts.dynamicRef&&d.push([Un.default.dynamicAnchors,Un.default.dynamicAnchors]);let h=(0,Re._)`${l}, ${r.object(...d)}`;return u!==Re.nil?(0,Re._)`${a}.call(${u}, ${h})`:(0,Re._)`${a}(${h})`}Te.callValidateCode=I1;var j1=(0,Re._)`new RegExp`;function N1({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,o=i(r,n);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,Re._)`${i.code==="new RegExp"?j1:(0,z1.useFunc)(e,i)}(${r}, ${n})`})}Te.usePattern=N1;function M1(e){let{gen:t,data:r,keyword:n,it:i}=e,o=t.name("valid");if(i.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(o,!0),s(()=>t.break()),o;function s(a){let u=t.const("len",(0,Re._)`${r}.length`);t.forRange("i",0,u,c=>{e.subschema({keyword:n,dataProp:c,dataPropType:Dp.Type.Num},o),t.if((0,Re.not)(o),a)})}}Te.validateArray=M1;function D1(e){let{gen:t,schema:r,keyword:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(u=>(0,Dp.alwaysValidSchema)(i,u))&&!i.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((u,c)=>{let l=e.subschema({keyword:n,schemaProp:c,compositeRule:!0},a);t.assign(s,(0,Re._)`${s} || ${a}`),e.mergeValidEvaluated(l,a)||t.if((0,Re.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}Te.validateUnion=D1});var z0=z(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.validateKeywordUsage=Vr.validSchemaType=Vr.funcKeywordCode=Vr.macroKeywordCode=void 0;var Nt=ne(),qi=hn(),Z1=fr(),L1=oa();function q1(e,t){let{gen:r,keyword:n,schema:i,parentSchema:o,it:s}=e,a=t.macro.call(s.self,i,o,s),u=E0(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let c=r.name("valid");e.subschema({schema:a,schemaPath:Nt.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:u,compositeRule:!0},c),e.pass(c,()=>e.error(!0))}Vr.macroKeywordCode=q1;function F1(e,t){var r;let{gen:n,keyword:i,schema:o,parentSchema:s,$data:a,it:u}=e;G1(u,t);let c=!a&&t.compile?t.compile.call(u.self,o,s,u):t.validate,l=E0(n,i,c),d=n.let("valid");e.block$data(d,h),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function h(){if(t.errors===!1)f(),t.modifying&&$0(e),g(()=>e.error());else{let y=t.async?m():p();t.modifying&&$0(e),g(()=>U1(e,y))}}function m(){let y=n.let("ruleErrs",null);return n.try(()=>f((0,Nt._)`await `),v=>n.assign(d,!1).if((0,Nt._)`${v} instanceof ${u.ValidationError}`,()=>n.assign(y,(0,Nt._)`${v}.errors`),()=>n.throw(v))),y}function p(){let y=(0,Nt._)`${l}.errors`;return n.assign(y,null),f(Nt.nil),y}function f(y=t.async?(0,Nt._)`await `:Nt.nil){let v=u.opts.passContext?qi.default.this:qi.default.self,b=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,Nt._)`${y}${(0,Z1.callValidateCode)(e,l,v,b)}`,t.modifying)}function g(y){var v;n.if((0,Nt.not)((v=t.valid)!==null&&v!==void 0?v:d),y)}}Vr.funcKeywordCode=F1;function $0(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Nt._)`${n.parentData}[${n.parentDataProperty}]`))}function U1(e,t){let{gen:r}=e;r.if((0,Nt._)`Array.isArray(${t})`,()=>{r.assign(qi.default.vErrors,(0,Nt._)`${qi.default.vErrors} === null ? ${t} : ${qi.default.vErrors}.concat(${t})`).assign(qi.default.errors,(0,Nt._)`${qi.default.vErrors}.length`),(0,L1.extendErrors)(e)},()=>e.error())}function G1({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function E0(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Nt.stringify)(r)})}function V1(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}Vr.validSchemaType=V1;function B1({schema:e,opts:t,self:r,errSchemaPath:n},i,o){if(Array.isArray(i.keyword)?!i.keyword.includes(o):i.keyword!==o)throw new Error("ajv implementation error");let s=i.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${o}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(e[o])){let u=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(u);else throw new Error(u)}}Vr.validateKeywordUsage=B1});var A0=z(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.extendSubschemaMode=Gn.extendSubschemaData=Gn.getSubschema=void 0;var Br=ne(),O0=he();function J1(e,{keyword:t,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:o,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,Br._)`${e.schemaPath}${(0,Br.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,Br._)`${e.schemaPath}${(0,Br.getProperty)(t)}${(0,Br.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,O0.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||o===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:s,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Gn.getSubschema=J1;function W1(e,t,{dataProp:r,dataPropType:n,data:i,dataTypes:o,propertyName:s}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:c,dataPathArr:l,opts:d}=t,h=a.let("data",(0,Br._)`${t.data}${(0,Br.getProperty)(r)}`,!0);u(h),e.errorPath=(0,Br.str)`${c}${(0,O0.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,Br._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(i!==void 0){let c=i instanceof Br.Name?i:a.let("data",i,!0);u(c),s!==void 0&&(e.propertyName=s)}o&&(e.dataTypes=o);function u(c){e.data=c,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,c]}}Gn.extendSubschemaData=W1;function H1(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:o}){n!==void 0&&(e.compositeRule=n),i!==void 0&&(e.createErrors=i),o!==void 0&&(e.allErrors=o),e.jtdDiscriminator=t,e.jtdMetadata=r}Gn.extendSubschemaMode=H1});var qp=z((HU,P0)=>{"use strict";P0.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(o=Object.keys(t),n=o.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;i--!==0;){var s=o[i];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}});var R0=z((KU,C0)=>{"use strict";var Vn=C0.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};Tl(t,n,i,e,"",e)};Vn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Vn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Vn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Vn.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Tl(e,t,r,n,i,o,s,a,u,c){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,i,o,s,a,u,c);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Vn.arrayKeywords)for(var h=0;h<d.length;h++)Tl(e,t,r,d[h],i+"/"+l+"/"+h,o,i,l,n,h)}else if(l in Vn.propsKeywords){if(d&&typeof d=="object")for(var m in d)Tl(e,t,r,d[m],i+"/"+l+"/"+K1(m),o,i,l,n,m)}else(l in Vn.keywords||e.allKeys&&!(l in Vn.skipKeywords))&&Tl(e,t,r,d,i+"/"+l,o,i,l,n)}r(n,i,o,s,a,u,c)}}function K1(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var aa=z(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.getSchemaRefs=Vt.resolveUrl=Vt.normalizeId=Vt._getFullPath=Vt.getFullPath=Vt.inlineRef=void 0;var Q1=he(),X1=qp(),Y1=R0(),eR=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function tR(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Fp(e):t?I0(e)<=t:!1}Vt.inlineRef=tR;var rR=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Fp(e){for(let t in e){if(rR.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Fp)||typeof r=="object"&&Fp(r))return!0}return!1}function I0(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!eR.has(r)&&(typeof e[r]=="object"&&(0,Q1.eachItem)(e[r],n=>t+=I0(n)),t===1/0))return 1/0}return t}function j0(e,t="",r){r!==!1&&(t=Zo(t));let n=e.parse(t);return N0(e,n)}Vt.getFullPath=j0;function N0(e,t){return e.serialize(t).split("#")[0]+"#"}Vt._getFullPath=N0;var nR=/#\/?$/;function Zo(e){return e?e.replace(nR,""):""}Vt.normalizeId=Zo;function iR(e,t,r){return r=Zo(r),e.resolve(t,r)}Vt.resolveUrl=iR;var oR=/^[a-z_][-a-z0-9._]*$/i;function sR(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=Zo(e[r]||t),o={"":i},s=j0(n,i,!1),a={},u=new Set;return Y1(e,{allKeys:!0},(d,h,m,p)=>{if(p===void 0)return;let f=s+h,g=o[p];typeof d[r]=="string"&&(g=y.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),o[h]=g;function y(b){let w=this.opts.uriResolver.resolve;if(b=Zo(g?w(g,b):b),u.has(b))throw l(b);u.add(b);let S=this.refs[b];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?c(d,S.schema,b):b!==Zo(f)&&(b[0]==="#"?(c(d,a[b],b),a[b]=d):this.refs[b]=f),b}function v(b){if(typeof b=="string"){if(!oR.test(b))throw new Error(`invalid anchor "${b}"`);y.call(this,`#${b}`)}}}),a;function c(d,h,m){if(h!==void 0&&!X1(d,h))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Vt.getSchemaRefs=sR});var ua=z(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.getData=Bn.KeywordCxt=Bn.validateFunctionCode=void 0;var q0=g0(),M0=sa(),Gp=Ip(),$l=sa(),aR=k0(),la=z0(),Up=A0(),L=ne(),Q=hn(),cR=aa(),gn=he(),ca=oa();function lR(e){if(G0(e)&&(V0(e),U0(e))){fR(e);return}F0(e,()=>(0,q0.topBoolOrEmptySchema)(e))}Bn.validateFunctionCode=lR;function F0({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},o){i.code.es5?e.func(t,(0,L._)`${Q.default.data}, ${Q.default.valCxt}`,n.$async,()=>{e.code((0,L._)`"use strict"; ${D0(r,i)}`),dR(e,i),e.code(o)}):e.func(t,(0,L._)`${Q.default.data}, ${uR(i)}`,n.$async,()=>e.code(D0(r,i)).code(o))}function uR(e){return(0,L._)`{${Q.default.instancePath}="", ${Q.default.parentData}, ${Q.default.parentDataProperty}, ${Q.default.rootData}=${Q.default.data}${e.dynamicRef?(0,L._)`, ${Q.default.dynamicAnchors}={}`:L.nil}}={}`}function dR(e,t){e.if(Q.default.valCxt,()=>{e.var(Q.default.instancePath,(0,L._)`${Q.default.valCxt}.${Q.default.instancePath}`),e.var(Q.default.parentData,(0,L._)`${Q.default.valCxt}.${Q.default.parentData}`),e.var(Q.default.parentDataProperty,(0,L._)`${Q.default.valCxt}.${Q.default.parentDataProperty}`),e.var(Q.default.rootData,(0,L._)`${Q.default.valCxt}.${Q.default.rootData}`),t.dynamicRef&&e.var(Q.default.dynamicAnchors,(0,L._)`${Q.default.valCxt}.${Q.default.dynamicAnchors}`)},()=>{e.var(Q.default.instancePath,(0,L._)`""`),e.var(Q.default.parentData,(0,L._)`undefined`),e.var(Q.default.parentDataProperty,(0,L._)`undefined`),e.var(Q.default.rootData,Q.default.data),t.dynamicRef&&e.var(Q.default.dynamicAnchors,(0,L._)`{}`)})}function fR(e){let{schema:t,opts:r,gen:n}=e;F0(e,()=>{r.$comment&&t.$comment&&J0(e),_R(e),n.let(Q.default.vErrors,null),n.let(Q.default.errors,0),r.unevaluated&&mR(e),B0(e),bR(e)})}function mR(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,L._)`${r}.evaluated`),t.if((0,L._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,L._)`${e.evaluated}.props`,(0,L._)`undefined`)),t.if((0,L._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,L._)`${e.evaluated}.items`,(0,L._)`undefined`))}function D0(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,L._)`/*# sourceURL=${r} */`:L.nil}function pR(e,t){if(G0(e)&&(V0(e),U0(e))){hR(e,t);return}(0,q0.boolOrEmptySchema)(e,t)}function U0({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function G0(e){return typeof e.schema!="boolean"}function hR(e,t){let{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&J0(e),yR(e),vR(e);let o=n.const("_errs",Q.default.errors);B0(e,o),n.var(t,(0,L._)`${o} === ${Q.default.errors}`)}function V0(e){(0,gn.checkUnknownRules)(e),gR(e)}function B0(e,t){if(e.opts.jtd)return Z0(e,[],!1,t);let r=(0,M0.getSchemaTypes)(e.schema),n=(0,M0.coerceAndCheckDataType)(e,r);Z0(e,r,!n,t)}function gR(e){let{schema:t,errSchemaPath:r,opts:n,self:i}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,gn.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function _R(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,gn.checkStrictMode)(e,"default is ignored in the schema root")}function yR(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,cR.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function vR(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function J0({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){let o=r.$comment;if(i.$comment===!0)e.code((0,L._)`${Q.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let s=(0,L.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,L._)`${Q.default.self}.opts.$comment(${o}, ${s}, ${a}.schema)`)}}function bR(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=e;r.$async?t.if((0,L._)`${Q.default.errors} === 0`,()=>t.return(Q.default.data),()=>t.throw((0,L._)`new ${i}(${Q.default.vErrors})`)):(t.assign((0,L._)`${n}.errors`,Q.default.vErrors),o.unevaluated&&wR(e),t.return((0,L._)`${Q.default.errors} === 0`))}function wR({gen:e,evaluated:t,props:r,items:n}){r instanceof L.Name&&e.assign((0,L._)`${t}.props`,r),n instanceof L.Name&&e.assign((0,L._)`${t}.items`,n)}function Z0(e,t,r,n){let{gen:i,schema:o,data:s,allErrors:a,opts:u,self:c}=e,{RULES:l}=c;if(o.$ref&&(u.ignoreKeywordsWithRef||!(0,gn.schemaHasRulesButRef)(o,l))){i.block(()=>H0(e,"$ref",l.all.$ref.definition));return}u.jtd||xR(e,t),i.block(()=>{for(let h of l.rules)d(h);d(l.post)});function d(h){(0,Gp.shouldUseGroup)(o,h)&&(h.type?(i.if((0,$l.checkDataType)(h.type,s,u.strictNumbers)),L0(e,h),t.length===1&&t[0]===h.type&&r&&(i.else(),(0,$l.reportTypeError)(e)),i.endIf()):L0(e,h),a||i.if((0,L._)`${Q.default.errors} === ${n||0}`))}}function L0(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,aR.assignDefaults)(e,t.type),r.block(()=>{for(let o of t.rules)(0,Gp.shouldUseRule)(n,o)&&H0(e,o.keyword,o.definition,t.type)})}function xR(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(kR(e,t),e.opts.allowUnionTypes||SR(e,t),TR(e,e.dataTypes))}function kR(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{W0(e.dataTypes,r)||Vp(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),ER(e,t)}}function SR(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Vp(e,"use allowUnionTypes to allow union type keyword")}function TR(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,Gp.shouldUseRule)(e.schema,i)){let{type:o}=i.definition;o.length&&!o.some(s=>$R(t,s))&&Vp(e,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function $R(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function W0(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function ER(e,t){let r=[];for(let n of e.dataTypes)W0(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Vp(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,gn.checkStrictMode)(e,t,e.opts.strictTypes)}var El=class{constructor(t,r,n){if((0,la.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,gn.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",K0(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,la.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",Q.default.errors))}result(t,r,n){this.failResult((0,L.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,L.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,L._)`${r} !== undefined && (${(0,L.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?ca.reportExtraError:ca.reportError)(this,this.def.error,r)}$dataError(){(0,ca.reportError)(this,this.def.$dataError||ca.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ca.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=L.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=L.nil,r=L.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:s}=this;n.if((0,L.or)((0,L._)`${i} === undefined`,r)),t!==L.nil&&n.assign(t,!0),(o.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==L.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:i,it:o}=this;return(0,L.or)(s(),a());function s(){if(n.length){if(!(r instanceof L.Name))throw new Error("ajv implementation error");let u=Array.isArray(n)?n:[n];return(0,L._)`${(0,$l.checkDataTypes)(u,r,o.opts.strictNumbers,$l.DataType.Wrong)}`}return L.nil}function a(){if(i.validateSchema){let u=t.scopeValue("validate$data",{ref:i.validateSchema});return(0,L._)`!${u}(${r})`}return L.nil}}subschema(t,r){let n=(0,Up.getSubschema)(this.it,t);(0,Up.extendSubschemaData)(n,this.it,t),(0,Up.extendSubschemaMode)(n,t);let i={...this.it,...n,items:void 0,props:void 0};return pR(i,r),i}mergeEvaluated(t,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=gn.mergeEvaluated.props(i,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=gn.mergeEvaluated.items(i,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(t,L.Name)),!0}};Bn.KeywordCxt=El;function H0(e,t,r,n){let i=new El(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,la.funcKeywordCode)(i,r):"macro"in r?(0,la.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,la.funcKeywordCode)(i,r)}var zR=/^\/(?:[^~]|~0|~1)*$/,OR=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function K0(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,o;if(e==="")return Q.default.rootData;if(e[0]==="/"){if(!zR.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,o=Q.default.rootData}else{let c=OR.exec(e);if(!c)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+c[1];if(i=c[2],i==="#"){if(l>=t)throw new Error(u("property/index",l));return n[t-l]}if(l>t)throw new Error(u("data",l));if(o=r[t-l],!i)return o}let s=o,a=i.split("/");for(let c of a)c&&(o=(0,L._)`${o}${(0,L.getProperty)((0,gn.unescapeJsonPointer)(c))}`,s=(0,L._)`${s} && ${o}`);return s;function u(c,l){return`Cannot access ${c} ${l} levels up, current level is ${t}`}}Bn.getData=K0});var zl=z(Jp=>{"use strict";Object.defineProperty(Jp,"__esModule",{value:!0});var Bp=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Jp.default=Bp});var da=z(Kp=>{"use strict";Object.defineProperty(Kp,"__esModule",{value:!0});var Wp=aa(),Hp=class extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Wp.resolveUrl)(t,r,n),this.missingSchema=(0,Wp.normalizeId)((0,Wp.getFullPath)(t,this.missingRef))}};Kp.default=Hp});var Al=z(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.resolveSchema=mr.getCompilingSchema=mr.resolveRef=mr.compileSchema=mr.SchemaEnv=void 0;var $r=ne(),AR=zl(),Fi=hn(),Er=aa(),Q0=he(),PR=ua(),Lo=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,Er.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};mr.SchemaEnv=Lo;function Xp(e){let t=X0.call(this,e);if(t)return t;let r=(0,Er.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,s=new $r.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),a;e.$async&&(a=s.scopeValue("Error",{ref:AR.default,code:(0,$r._)`require("ajv/dist/runtime/validation_error").default`}));let u=s.scopeName("validate");e.validateName=u;let c={gen:s,allErrors:this.opts.allErrors,data:Fi.default.data,parentData:Fi.default.parentData,parentDataProperty:Fi.default.parentDataProperty,dataNames:[Fi.default.data],dataPathArr:[$r.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,$r.stringify)(e.schema)}:{ref:e.schema}),validateName:u,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:$r.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,$r._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,PR.validateFunctionCode)(c),s.optimize(this.opts.code.optimize);let d=s.toString();l=`${s.scopeRefs(Fi.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let m=new Function(`${Fi.default.self}`,`${Fi.default.scope}`,l)(this,this.scope.get());if(this.scope.value(u,{ref:m}),m.errors=null,m.schema=e.schema,m.schemaEnv=e,e.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:u,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:p,items:f}=c;m.evaluated={props:p instanceof $r.Name?void 0:p,items:f instanceof $r.Name?void 0:f,dynamicProps:p instanceof $r.Name,dynamicItems:f instanceof $r.Name},m.source&&(m.source.evaluated=(0,$r.stringify)(m.evaluated))}return e.validate=m,e}catch(d){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(e)}}mr.compileSchema=Xp;function CR(e,t,r){var n;r=(0,Er.resolveUrl)(this.opts.uriResolver,t,r);let i=e.refs[r];if(i)return i;let o=jR.call(this,e,r);if(o===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(o=new Lo({schema:s,schemaId:a,root:e,baseId:t}))}if(o!==void 0)return e.refs[r]=RR.call(this,o)}mr.resolveRef=CR;function RR(e){return(0,Er.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Xp.call(this,e)}function X0(e){for(let t of this._compilations)if(IR(t,e))return t}mr.getCompilingSchema=X0;function IR(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function jR(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Ol.call(this,e,t)}function Ol(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Er._getFullPath)(this.opts.uriResolver,r),i=(0,Er.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return Qp.call(this,r,e);let o=(0,Er.normalizeId)(n),s=this.refs[o]||this.schemas[o];if(typeof s=="string"){let a=Ol.call(this,e,s);return typeof a?.schema!="object"?void 0:Qp.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||Xp.call(this,s),o===(0,Er.normalizeId)(t)){let{schema:a}=s,{schemaId:u}=this.opts,c=a[u];return c&&(i=(0,Er.resolveUrl)(this.opts.uriResolver,i,c)),new Lo({schema:a,schemaId:u,root:e,baseId:i})}return Qp.call(this,r,s)}}mr.resolveSchema=Ol;var NR=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Qp(e,{baseId:t,schema:r,root:n}){var i;if(((i=e.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let u=r[(0,Q0.unescapeFragment)(a)];if(u===void 0)return;r=u;let c=typeof r=="object"&&r[this.opts.schemaId];!NR.has(a)&&c&&(t=(0,Er.resolveUrl)(this.opts.uriResolver,t,c))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,Q0.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Er.resolveUrl)(this.opts.uriResolver,t,r.$ref);o=Ol.call(this,n,a)}let{schemaId:s}=this.opts;if(o=o||new Lo({schema:r,schemaId:s,root:n,baseId:t}),o.schema!==o.root.schema)return o}});var Y0=z((rG,MR)=>{MR.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var eh=z((nG,nx)=>{"use strict";var DR=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),tx=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Yp(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var ZR=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ex(e){return e.length=0,!0}function LR(e,t,r){if(e.length){let n=Yp(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function qR(e){let t=0,r={error:!1,address:"",zone:""},n=[],i=[],o=!1,s=!1,a=LR;for(let u=0;u<e.length;u++){let c=e[u];if(!(c==="["||c==="]"))if(c===":"){if(o===!0&&(s=!0),!a(i,n,r))break;if(++t>7){r.error=!0;break}u>0&&e[u-1]===":"&&(o=!0),n.push(":");continue}else if(c==="%"){if(!a(i,n,r))break;a=ex}else{i.push(c);continue}}return i.length&&(a===ex?r.zone=i.join(""):s?n.push(i.join("")):n.push(Yp(i))),r.address=n.join(""),r}function rx(e){if(FR(e,":")<2)return{host:e,isIPV6:!1};let t=qR(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}function FR(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function UR(e){let t=e,r=[],n=-1,i=0;for(;i=t.length;){if(i===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(i===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(i===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}function GR(e,t){let r=t!==!0?escape:unescape;return e.scheme!==void 0&&(e.scheme=r(e.scheme)),e.userinfo!==void 0&&(e.userinfo=r(e.userinfo)),e.host!==void 0&&(e.host=r(e.host)),e.path!==void 0&&(e.path=r(e.path)),e.query!==void 0&&(e.query=r(e.query)),e.fragment!==void 0&&(e.fragment=r(e.fragment)),e}function VR(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!tx(r)){let n=rx(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=e.host}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}nx.exports={nonSimpleDomain:ZR,recomposeAuthority:VR,normalizeComponentEncoding:GR,removeDotSegments:UR,isIPv4:tx,isUUID:DR,normalizeIPv6:rx,stringArrayToHexStripped:Yp}});var cx=z((iG,ax)=>{"use strict";var{isUUID:BR}=eh(),JR=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,WR=["http","https","ws","wss","urn","urn:uuid"];function HR(e){return WR.indexOf(e)!==-1}function th(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function ix(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function ox(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function KR(e){return e.secure=th(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function QR(e){if((e.port===(th(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function XR(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(JR);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let i=`${n}:${t.nid||e.nid}`,o=rh(i);e.path=void 0,o&&(e=o.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function YR(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),i=`${r}:${t.nid||n}`,o=rh(i);o&&(e=o.serialize(e,t));let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}function eI(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!BR(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function tI(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var sx={scheme:"http",domainHost:!0,parse:ix,serialize:ox},rI={scheme:"https",domainHost:sx.domainHost,parse:ix,serialize:ox},Pl={scheme:"ws",domainHost:!0,parse:KR,serialize:QR},nI={scheme:"wss",domainHost:Pl.domainHost,parse:Pl.parse,serialize:Pl.serialize},iI={scheme:"urn",parse:XR,serialize:YR,skipNormalize:!0},oI={scheme:"urn:uuid",parse:eI,serialize:tI,skipNormalize:!0},Cl={http:sx,https:rI,ws:Pl,wss:nI,urn:iI,"urn:uuid":oI};Object.setPrototypeOf(Cl,null);function rh(e){return e&&(Cl[e]||Cl[e.toLowerCase()])||void 0}ax.exports={wsIsSecure:th,SCHEMES:Cl,isValidSchemeName:HR,getSchemeHandler:rh}});var dx=z((oG,Il)=>{"use strict";var{normalizeIPv6:sI,removeDotSegments:fa,recomposeAuthority:aI,normalizeComponentEncoding:Rl,isIPv4:cI,nonSimpleDomain:lI}=eh(),{SCHEMES:uI,getSchemeHandler:lx}=cx();function dI(e,t){return typeof e=="string"?e=Jr(_n(e,t),t):typeof e=="object"&&(e=_n(Jr(e,t),t)),e}function fI(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},i=ux(_n(e,n),_n(t,n),n,!0);return n.skipEscape=!0,Jr(i,n)}function ux(e,t,r,n){let i={};return n||(e=_n(Jr(e,r),r),t=_n(Jr(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(i.scheme=t.scheme,i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=fa(t.path||""),i.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=fa(t.path||""),i.query=t.query):(t.path?(t.path[0]==="/"?i.path=fa(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?i.path="/"+t.path:e.path?i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:i.path=t.path,i.path=fa(i.path)),i.query=t.query):(i.path=e.path,t.query!==void 0?i.query=t.query:i.query=e.query),i.userinfo=e.userinfo,i.host=e.host,i.port=e.port),i.scheme=e.scheme),i.fragment=t.fragment,i}function mI(e,t,r){return typeof e=="string"?(e=unescape(e),e=Jr(Rl(_n(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Jr(Rl(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=Jr(Rl(_n(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Jr(Rl(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function Jr(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),i=[],o=lx(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&i.push(r.scheme,":");let s=aI(r);if(s!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(s),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=fa(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return r.query!==void 0&&i.push("?",r.query),r.fragment!==void 0&&i.push("#",r.fragment),i.join("")}var pI=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function _n(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let o=e.match(pI);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(cI(n.host)===!1){let u=sI(n.host);n.host=u.host.toLowerCase(),i=u.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let s=lx(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&i===!1&&lI(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!s||s&&!s.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s&&s.parse&&s.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var nh={SCHEMES:uI,normalize:dI,resolve:fI,resolveComponent:ux,equal:mI,serialize:Jr,parse:_n};Il.exports=nh;Il.exports.default=nh;Il.exports.fastUri=nh});var mx=z(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});var fx=dx();fx.code='require("ajv/dist/runtime/uri").default';ih.default=fx});var wx=z(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.CodeGen=_t.Name=_t.nil=_t.stringify=_t.str=_t._=_t.KeywordCxt=void 0;var hI=ua();Object.defineProperty(_t,"KeywordCxt",{enumerable:!0,get:function(){return hI.KeywordCxt}});var qo=ne();Object.defineProperty(_t,"_",{enumerable:!0,get:function(){return qo._}});Object.defineProperty(_t,"str",{enumerable:!0,get:function(){return qo.str}});Object.defineProperty(_t,"stringify",{enumerable:!0,get:function(){return qo.stringify}});Object.defineProperty(_t,"nil",{enumerable:!0,get:function(){return qo.nil}});Object.defineProperty(_t,"Name",{enumerable:!0,get:function(){return qo.Name}});Object.defineProperty(_t,"CodeGen",{enumerable:!0,get:function(){return qo.CodeGen}});var gI=zl(),yx=da(),_I=Rp(),ma=Al(),yI=ne(),pa=aa(),jl=sa(),sh=he(),px=Y0(),vI=mx(),vx=(e,t)=>new RegExp(e,t);vx.code="new RegExp";var bI=["removeAdditional","useDefaults","coerceTypes"],wI=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),xI={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},kI={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},hx=200;function SI(e){var t,r,n,i,o,s,a,u,c,l,d,h,m,p,f,g,y,v,b,w,S,q,K,ce,C;let G=e.strict,H=(t=e.code)===null||t===void 0?void 0:t.optimize,fe=H===!0||H===void 0?1:H||0,ge=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:vx,j=(i=e.uriResolver)!==null&&i!==void 0?i:vI.default;return{strictSchema:(s=(o=e.strictSchema)!==null&&o!==void 0?o:G)!==null&&s!==void 0?s:!0,strictNumbers:(u=(a=e.strictNumbers)!==null&&a!==void 0?a:G)!==null&&u!==void 0?u:!0,strictTypes:(l=(c=e.strictTypes)!==null&&c!==void 0?c:G)!==null&&l!==void 0?l:"log",strictTuples:(h=(d=e.strictTuples)!==null&&d!==void 0?d:G)!==null&&h!==void 0?h:"log",strictRequired:(p=(m=e.strictRequired)!==null&&m!==void 0?m:G)!==null&&p!==void 0?p:!1,code:e.code?{...e.code,optimize:fe,regExp:ge}:{optimize:fe,regExp:ge},loopRequired:(f=e.loopRequired)!==null&&f!==void 0?f:hx,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:hx,meta:(y=e.meta)!==null&&y!==void 0?y:!0,messages:(v=e.messages)!==null&&v!==void 0?v:!0,inlineRefs:(b=e.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(w=e.schemaId)!==null&&w!==void 0?w:"$id",addUsedSchema:(S=e.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(q=e.validateSchema)!==null&&q!==void 0?q:!0,validateFormats:(K=e.validateFormats)!==null&&K!==void 0?K:!0,unicodeRegExp:(ce=e.unicodeRegExp)!==null&&ce!==void 0?ce:!0,int32range:(C=e.int32range)!==null&&C!==void 0?C:!0,uriResolver:j}}var ha=class{constructor(t={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...SI(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new yI.ValueScope({scope:{},prefixes:wI,es5:r,lines:n}),this.logger=AI(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,_I.getRules)(),gx.call(this,xI,t,"NOT SUPPORTED"),gx.call(this,kI,t,"DEPRECATED","warn"),this._metaOpts=zI.call(this),t.formats&&$I.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&EI.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),TI.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,i=px;n==="id"&&(i={...px},i.id=i.$id,delete i.$id),r&&t&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,t,r);async function i(l,d){await o.call(this,l.$schema);let h=this._addSchema(l,d);return h.validate||s.call(this,h)}async function o(l){l&&!this.getSchema(l)&&await i.call(this,{$ref:l},!0)}async function s(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof yx.default))throw d;return a.call(this,d),await u.call(this,d.missingSchema),s.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function u(l){let d=await c.call(this,l);this.refs[l]||await o.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function c(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(t,r,n,i=this.opts.validateSchema){if(Array.isArray(t)){for(let s of t)this.addSchema(s,void 0,n,i);return this}let o;if(typeof t=="object"){let{schemaId:s}=this.opts;if(o=t[s],o!==void 0&&typeof o!="string")throw new Error(`schema ${s} must be string`)}return r=(0,pa.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,i,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,t);if(!i&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return i}getSchema(t){let r;for(;typeof(r=_x.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,i=new ma.SchemaEnv({schema:{},schemaId:n});if(r=ma.resolveSchema.call(this,i,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=_x.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,pa.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(CI.call(this,n,r),!r)return(0,sh.eachItem)(n,o=>oh.call(this,o)),this;II.call(this,r);let i={...r,type:(0,jl.getJSONTypes)(r.type),schemaType:(0,jl.getJSONTypes)(r.schemaType)};return(0,sh.eachItem)(n,i.type.length===0?o=>oh.call(this,o,i):o=>i.type.forEach(s=>oh.call(this,o,i,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let i=n.rules.findIndex(o=>o.keyword===t);i>=0&&n.rules.splice(i,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,o)=>i+r+o)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let i of r){let o=i.split("/").slice(1),s=t;for(let a of o)s=s[a];for(let a in n){let u=n[a];if(typeof u!="object")continue;let{$data:c}=u.definition,l=s[a];c&&l&&(s[a]=bx(l))}}return t}_removeAllSchemas(t,r){for(let n in t){let i=t[n];(!r||r.test(n))&&(typeof i=="string"?delete t[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete t[n]))}}_addSchema(t,r,n,i=this.opts.validateSchema,o=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof t=="object")s=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let u=this._cache.get(t);if(u!==void 0)return u;n=(0,pa.normalizeId)(s||n);let c=pa.getSchemaRefs.call(this,t,n);return u=new ma.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:c}),this._cache.set(u.schema,u),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=u),i&&this.validateSchema(t,!0),u}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):ma.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{ma.compileSchema.call(this,t)}finally{this.opts=r}}};ha.ValidationError=gI.default;ha.MissingRefError=yx.default;_t.default=ha;function gx(e,t,r,n="error"){for(let i in e){let o=i;o in t&&this.logger[n](`${r}: option ${i}. ${e[o]}`)}}function _x(e){return e=(0,pa.normalizeId)(e),this.schemas[e]||this.refs[e]}function TI(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function $I(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function EI(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function zI(){let e={...this.opts};for(let t of bI)delete e[t];return e}var OI={log(){},warn(){},error(){}};function AI(e){if(e===!1)return OI;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var PI=/^[a-z_$][a-z0-9_$:-]*$/i;function CI(e,t){let{RULES:r}=this;if((0,sh.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!PI.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function oh(e,t,r){var n;let i=t?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,s=i?o.post:o.rules.find(({type:u})=>u===r);if(s||(s={type:r,rules:[]},o.rules.push(s)),o.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,jl.getJSONTypes)(t.type),schemaType:(0,jl.getJSONTypes)(t.schemaType)}};t.before?RI.call(this,s,a,t.before):s.rules.push(a),o.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(u=>this.addKeyword(u))}function RI(e,t,r){let n=e.rules.findIndex(i=>i.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function II(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=bx(t)),e.validateSchema=this.compile(t,!0))}var jI={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function bx(e){return{anyOf:[e,jI]}}});var xx=z(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var NI={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ah.default=NI});var $x=z(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.callRef=Ui.getValidate=void 0;var MI=da(),kx=fr(),Bt=ne(),Fo=hn(),Sx=Al(),Nl=he(),DI={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:i,schemaEnv:o,validateName:s,opts:a,self:u}=n,{root:c}=o;if((r==="#"||r==="#/")&&i===c.baseId)return d();let l=Sx.resolveRef.call(u,c,i,r);if(l===void 0)throw new MI.default(n.opts.uriResolver,i,r);if(l instanceof Sx.SchemaEnv)return h(l);return m(l);function d(){if(o===c)return Ml(e,s,o,o.$async);let p=t.scopeValue("root",{ref:c});return Ml(e,(0,Bt._)`${p}.validate`,c,c.$async)}function h(p){let f=Tx(e,p);Ml(e,f,p,p.$async)}function m(p){let f=t.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,Bt.stringify)(p)}:{ref:p}),g=t.name("valid"),y=e.subschema({schema:p,dataTypes:[],schemaPath:Bt.nil,topSchemaRef:f,errSchemaPath:r},g);e.mergeEvaluated(y),e.ok(g)}}};function Tx(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Bt._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Ui.getValidate=Tx;function Ml(e,t,r,n){let{gen:i,it:o}=e,{allErrors:s,schemaEnv:a,opts:u}=o,c=u.passContext?Fo.default.this:Bt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=i.let("valid");i.try(()=>{i.code((0,Bt._)`await ${(0,kx.callValidateCode)(e,t,c)}`),m(t),s||i.assign(p,!0)},f=>{i.if((0,Bt._)`!(${f} instanceof ${o.ValidationError})`,()=>i.throw(f)),h(f),s||i.assign(p,!1)}),e.ok(p)}function d(){e.result((0,kx.callValidateCode)(e,t,c),()=>m(t),()=>h(t))}function h(p){let f=(0,Bt._)`${p}.errors`;i.assign(Fo.default.vErrors,(0,Bt._)`${Fo.default.vErrors} === null ? ${f} : ${Fo.default.vErrors}.concat(${f})`),i.assign(Fo.default.errors,(0,Bt._)`${Fo.default.vErrors}.length`)}function m(p){var f;if(!o.opts.unevaluated)return;let g=(f=r?.validate)===null||f===void 0?void 0:f.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=Nl.mergeEvaluated.props(i,g.props,o.props));else{let y=i.var("props",(0,Bt._)`${p}.evaluated.props`);o.props=Nl.mergeEvaluated.props(i,y,o.props,Bt.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=Nl.mergeEvaluated.items(i,g.items,o.items));else{let y=i.var("items",(0,Bt._)`${p}.evaluated.items`);o.items=Nl.mergeEvaluated.items(i,y,o.items,Bt.Name)}}}Ui.callRef=Ml;Ui.default=DI});var Ex=z(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var ZI=xx(),LI=$x(),qI=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",ZI.default,LI.default];ch.default=qI});var zx=z(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});var Dl=ne(),Jn=Dl.operators,Zl={maximum:{okStr:"<=",ok:Jn.LTE,fail:Jn.GT},minimum:{okStr:">=",ok:Jn.GTE,fail:Jn.LT},exclusiveMaximum:{okStr:"<",ok:Jn.LT,fail:Jn.GTE},exclusiveMinimum:{okStr:">",ok:Jn.GT,fail:Jn.LTE}},FI={message:({keyword:e,schemaCode:t})=>(0,Dl.str)`must be ${Zl[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Dl._)`{comparison: ${Zl[e].okStr}, limit: ${t}}`},UI={keyword:Object.keys(Zl),type:"number",schemaType:"number",$data:!0,error:FI,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Dl._)`${r} ${Zl[t].fail} ${n} || isNaN(${r})`)}};lh.default=UI});var Ox=z(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var ga=ne(),GI={message:({schemaCode:e})=>(0,ga.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,ga._)`{multipleOf: ${e}}`},VI={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:GI,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,o=i.opts.multipleOfPrecision,s=t.let("res"),a=o?(0,ga._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,ga._)`${s} !== parseInt(${s})`;e.fail$data((0,ga._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};uh.default=VI});var Px=z(dh=>{"use strict";Object.defineProperty(dh,"__esModule",{value:!0});function Ax(e){let t=e.length,r=0,n=0,i;for(;n<t;)r++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<t&&(i=e.charCodeAt(n),(i&64512)===56320&&n++);return r}dh.default=Ax;Ax.code='require("ajv/dist/runtime/ucs2length").default'});var Cx=z(fh=>{"use strict";Object.defineProperty(fh,"__esModule",{value:!0});var Gi=ne(),BI=he(),JI=Px(),WI={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Gi.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Gi._)`{limit: ${e}}`},HI={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:WI,code(e){let{keyword:t,data:r,schemaCode:n,it:i}=e,o=t==="maxLength"?Gi.operators.GT:Gi.operators.LT,s=i.opts.unicode===!1?(0,Gi._)`${r}.length`:(0,Gi._)`${(0,BI.useFunc)(e.gen,JI.default)}(${r})`;e.fail$data((0,Gi._)`${s} ${o} ${n}`)}};fh.default=HI});var Rx=z(mh=>{"use strict";Object.defineProperty(mh,"__esModule",{value:!0});var KI=fr(),Ll=ne(),QI={message:({schemaCode:e})=>(0,Ll.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Ll._)`{pattern: ${e}}`},XI={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:QI,code(e){let{data:t,$data:r,schema:n,schemaCode:i,it:o}=e,s=o.opts.unicodeRegExp?"u":"",a=r?(0,Ll._)`(new RegExp(${i}, ${s}))`:(0,KI.usePattern)(e,n);e.fail$data((0,Ll._)`!${a}.test(${t})`)}};mh.default=XI});var Ix=z(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var _a=ne(),YI={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,_a.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,_a._)`{limit: ${e}}`},ej={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:YI,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?_a.operators.GT:_a.operators.LT;e.fail$data((0,_a._)`Object.keys(${r}).length ${i} ${n}`)}};ph.default=ej});var jx=z(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var ya=fr(),va=ne(),tj=he(),rj={message:({params:{missingProperty:e}})=>(0,va.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,va._)`{missingProperty: ${e}}`},nj={keyword:"required",type:"object",schemaType:"array",$data:!0,error:rj,code(e){let{gen:t,schema:r,schemaCode:n,data:i,$data:o,it:s}=e,{opts:a}=s;if(!o&&r.length===0)return;let u=r.length>=a.loopRequired;if(s.allErrors?c():l(),a.strictRequired){let m=e.parentSchema.properties,{definedProperties:p}=e.it;for(let f of r)if(m?.[f]===void 0&&!p.has(f)){let g=s.schemaEnv.baseId+s.errSchemaPath,y=`required property "${f}" is not defined at "${g}" (strictRequired)`;(0,tj.checkStrictMode)(s,y,s.opts.strictRequired)}}function c(){if(u||o)e.block$data(va.nil,d);else for(let m of r)(0,ya.checkReportMissingProp)(e,m)}function l(){let m=t.let("missing");if(u||o){let p=t.let("valid",!0);e.block$data(p,()=>h(m,p)),e.ok(p)}else t.if((0,ya.checkMissingProp)(e,r,m)),(0,ya.reportMissingProp)(e,m),t.else()}function d(){t.forOf("prop",n,m=>{e.setParams({missingProperty:m}),t.if((0,ya.noPropertyInData)(t,i,m,a.ownProperties),()=>e.error())})}function h(m,p){e.setParams({missingProperty:m}),t.forOf(m,n,()=>{t.assign(p,(0,ya.propertyInData)(t,i,m,a.ownProperties)),t.if((0,va.not)(p),()=>{e.error(),t.break()})},va.nil)}}};hh.default=nj});var Nx=z(gh=>{"use strict";Object.defineProperty(gh,"__esModule",{value:!0});var ba=ne(),ij={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,ba.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,ba._)`{limit: ${e}}`},oj={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ij,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?ba.operators.GT:ba.operators.LT;e.fail$data((0,ba._)`${r}.length ${i} ${n}`)}};gh.default=oj});var ql=z(_h=>{"use strict";Object.defineProperty(_h,"__esModule",{value:!0});var Mx=qp();Mx.code='require("ajv/dist/runtime/equal").default';_h.default=Mx});var Dx=z(vh=>{"use strict";Object.defineProperty(vh,"__esModule",{value:!0});var yh=sa(),yt=ne(),sj=he(),aj=ql(),cj={message:({params:{i:e,j:t}})=>(0,yt.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,yt._)`{i: ${e}, j: ${t}}`},lj={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:cj,code(e){let{gen:t,data:r,$data:n,schema:i,parentSchema:o,schemaCode:s,it:a}=e;if(!n&&!i)return;let u=t.let("valid"),c=o.items?(0,yh.getSchemaTypes)(o.items):[];e.block$data(u,l,(0,yt._)`${s} === false`),e.ok(u);function l(){let p=t.let("i",(0,yt._)`${r}.length`),f=t.let("j");e.setParams({i:p,j:f}),t.assign(u,!0),t.if((0,yt._)`${p} > 1`,()=>(d()?h:m)(p,f))}function d(){return c.length>0&&!c.some(p=>p==="object"||p==="array")}function h(p,f){let g=t.name("item"),y=(0,yh.checkDataTypes)(c,g,a.opts.strictNumbers,yh.DataType.Wrong),v=t.const("indices",(0,yt._)`{}`);t.for((0,yt._)`;${p}--;`,()=>{t.let(g,(0,yt._)`${r}[${p}]`),t.if(y,(0,yt._)`continue`),c.length>1&&t.if((0,yt._)`typeof ${g} == "string"`,(0,yt._)`${g} += "_"`),t.if((0,yt._)`typeof ${v}[${g}] == "number"`,()=>{t.assign(f,(0,yt._)`${v}[${g}]`),e.error(),t.assign(u,!1).break()}).code((0,yt._)`${v}[${g}] = ${p}`)})}function m(p,f){let g=(0,sj.useFunc)(t,aj.default),y=t.name("outer");t.label(y).for((0,yt._)`;${p}--;`,()=>t.for((0,yt._)`${f} = ${p}; ${f}--;`,()=>t.if((0,yt._)`${g}(${r}[${p}], ${r}[${f}])`,()=>{e.error(),t.assign(u,!1).break(y)})))}}};vh.default=lj});var Zx=z(wh=>{"use strict";Object.defineProperty(wh,"__esModule",{value:!0});var bh=ne(),uj=he(),dj=ql(),fj={message:"must be equal to constant",params:({schemaCode:e})=>(0,bh._)`{allowedValue: ${e}}`},mj={keyword:"const",$data:!0,error:fj,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:o}=e;n||o&&typeof o=="object"?e.fail$data((0,bh._)`!${(0,uj.useFunc)(t,dj.default)}(${r}, ${i})`):e.fail((0,bh._)`${o} !== ${r}`)}};wh.default=mj});var Lx=z(xh=>{"use strict";Object.defineProperty(xh,"__esModule",{value:!0});var wa=ne(),pj=he(),hj=ql(),gj={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,wa._)`{allowedValues: ${e}}`},_j={keyword:"enum",schemaType:"array",$data:!0,error:gj,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:o,it:s}=e;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=s.opts.loopEnum,u,c=()=>u??(u=(0,pj.useFunc)(t,hj.default)),l;if(a||n)l=t.let("valid"),e.block$data(l,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let m=t.const("vSchema",o);l=(0,wa.or)(...i.map((p,f)=>h(m,f)))}e.pass(l);function d(){t.assign(l,!1),t.forOf("v",o,m=>t.if((0,wa._)`${c()}(${r}, ${m})`,()=>t.assign(l,!0).break()))}function h(m,p){let f=i[p];return typeof f=="object"&&f!==null?(0,wa._)`${c()}(${r}, ${m}[${p}])`:(0,wa._)`${r} === ${f}`}}};xh.default=_j});var qx=z(kh=>{"use strict";Object.defineProperty(kh,"__esModule",{value:!0});var yj=zx(),vj=Ox(),bj=Cx(),wj=Rx(),xj=Ix(),kj=jx(),Sj=Nx(),Tj=Dx(),$j=Zx(),Ej=Lx(),zj=[yj.default,vj.default,bj.default,wj.default,xj.default,kj.default,Sj.default,Tj.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},$j.default,Ej.default];kh.default=zj});var Th=z(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.validateAdditionalItems=void 0;var Vi=ne(),Sh=he(),Oj={message:({params:{len:e}})=>(0,Vi.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Vi._)`{limit: ${e}}`},Aj={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Oj,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Sh.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Fx(e,n)}};function Fx(e,t){let{gen:r,schema:n,data:i,keyword:o,it:s}=e;s.items=!0;let a=r.const("len",(0,Vi._)`${i}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Vi._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Sh.alwaysValidSchema)(s,n)){let c=r.var("valid",(0,Vi._)`${a} <= ${t.length}`);r.if((0,Vi.not)(c),()=>u(c)),e.ok(c)}function u(c){r.forRange("i",t.length,a,l=>{e.subschema({keyword:o,dataProp:l,dataPropType:Sh.Type.Num},c),s.allErrors||r.if((0,Vi.not)(c),()=>r.break())})}}xa.validateAdditionalItems=Fx;xa.default=Aj});var $h=z(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.validateTuple=void 0;var Ux=ne(),Fl=he(),Pj=fr(),Cj={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Gx(e,"additionalItems",t);r.items=!0,!(0,Fl.alwaysValidSchema)(r,t)&&e.ok((0,Pj.validateArray)(e))}};function Gx(e,t,r=e.schema){let{gen:n,parentSchema:i,data:o,keyword:s,it:a}=e;l(i),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Fl.mergeEvaluated.items(n,r.length,a.items));let u=n.name("valid"),c=n.const("len",(0,Ux._)`${o}.length`);r.forEach((d,h)=>{(0,Fl.alwaysValidSchema)(a,d)||(n.if((0,Ux._)`${c} > ${h}`,()=>e.subschema({keyword:s,schemaProp:h,dataProp:h},u)),e.ok(u))});function l(d){let{opts:h,errSchemaPath:m}=a,p=r.length,f=p===d.minItems&&(p===d.maxItems||d[t]===!1);if(h.strictTuples&&!f){let g=`"${s}" is ${p}-tuple, but minItems or maxItems/${t} are not specified or different at path "${m}"`;(0,Fl.checkStrictMode)(a,g,h.strictTuples)}}}ka.validateTuple=Gx;ka.default=Cj});var Vx=z(Eh=>{"use strict";Object.defineProperty(Eh,"__esModule",{value:!0});var Rj=$h(),Ij={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Rj.validateTuple)(e,"items")};Eh.default=Ij});var Jx=z(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});var Bx=ne(),jj=he(),Nj=fr(),Mj=Th(),Dj={message:({params:{len:e}})=>(0,Bx.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Bx._)`{limit: ${e}}`},Zj={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Dj,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;n.items=!0,!(0,jj.alwaysValidSchema)(n,t)&&(i?(0,Mj.validateAdditionalItems)(e,i):e.ok((0,Nj.validateArray)(e)))}};zh.default=Zj});var Wx=z(Oh=>{"use strict";Object.defineProperty(Oh,"__esModule",{value:!0});var pr=ne(),Ul=he(),Lj={message:({params:{min:e,max:t}})=>t===void 0?(0,pr.str)`must contain at least ${e} valid item(s)`:(0,pr.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,pr._)`{minContains: ${e}}`:(0,pr._)`{minContains: ${e}, maxContains: ${t}}`},qj={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Lj,code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:o}=e,s,a,{minContains:u,maxContains:c}=n;o.opts.next?(s=u===void 0?1:u,a=c):s=1;let l=t.const("len",(0,pr._)`${i}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,Ul.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Ul.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Ul.alwaysValidSchema)(o,r)){let f=(0,pr._)`${l} >= ${s}`;a!==void 0&&(f=(0,pr._)`${f} && ${l} <= ${a}`),e.pass(f);return}o.items=!0;let d=t.name("valid");a===void 0&&s===1?m(d,()=>t.if(d,()=>t.break())):s===0?(t.let(d,!0),a!==void 0&&t.if((0,pr._)`${i}.length > 0`,h)):(t.let(d,!1),h()),e.result(d,()=>e.reset());function h(){let f=t.name("_valid"),g=t.let("count",0);m(f,()=>t.if(f,()=>p(g)))}function m(f,g){t.forRange("i",0,l,y=>{e.subschema({keyword:"contains",dataProp:y,dataPropType:Ul.Type.Num,compositeRule:!0},f),g()})}function p(f){t.code((0,pr._)`${f}++`),a===void 0?t.if((0,pr._)`${f} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,pr._)`${f} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,pr._)`${f} >= ${s}`,()=>t.assign(d,!0)))}}};Oh.default=qj});var Qx=z(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.validateSchemaDeps=Wr.validatePropertyDeps=Wr.error=void 0;var Ah=ne(),Fj=he(),Sa=fr();Wr.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Ah.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Ah._)`{property: ${e},
8
9
  missingProperty: ${n},
9
10
  depsCount: ${t},
10
- deps: ${r}}`};var HR={keyword:"dependencies",type:"object",schemaType:"object",error:Vr.error,code(e){let[t,r]=KR(e);A0(e,t),O0(e,r)}};function KR({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let i=Array.isArray(e[n])?t:r;i[n]=e[n]}return[t,r]}function A0(e,t=e.schema){let{gen:r,data:n,it:i}=e;if(Object.keys(t).length===0)return;let o=r.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let l=(0,ta.propertyInData)(r,n,s,i.opts.ownProperties);e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),i.allErrors?r.if(l,()=>{for(let c of a)(0,ta.checkReportMissingProp)(e,c)}):(r.if((0,Dp._)`${l} && (${(0,ta.checkMissingProp)(e,a,o)})`),(0,ta.reportMissingProp)(e,o),r.else())}}Vr.validatePropertyDeps=A0;function O0(e,t=e.schema){let{gen:r,data:n,keyword:i,it:o}=e,s=r.name("valid");for(let a in t)(0,WR.alwaysValidSchema)(o,t[a])||(r.if((0,ta.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let l=e.subschema({keyword:i,schemaProp:a},s);e.mergeValidEvaluated(l,s)},()=>r.var(s,!0)),e.ok(s))}Vr.validateSchemaDeps=O0;Vr.default=HR});var R0=E(Zp=>{"use strict";Object.defineProperty(Zp,"__esModule",{value:!0});var C0=H(),QR=ae(),XR={message:"property name must be valid",params:({params:e})=>(0,C0._)`{propertyName: ${e.propertyName}}`},YR={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:XR,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,QR.alwaysValidSchema)(i,r))return;let o=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),t.if((0,C0.not)(o),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(o)}};Zp.default=YR});var Lp=E(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});var ul=ar(),wr=H(),eI=an(),dl=ae(),tI={message:"must NOT have additional properties",params:({params:e})=>(0,wr._)`{additionalProperty: ${e.additionalProperty}}`},rI={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:tI,code(e){let{gen:t,schema:r,parentSchema:n,data:i,errsCount:o,it:s}=e;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=s;if(s.props=!0,l.removeAdditional!=="all"&&(0,dl.alwaysValidSchema)(s,r))return;let c=(0,ul.allSchemaProperties)(n.properties),u=(0,ul.allSchemaProperties)(n.patternProperties);d(),e.ok((0,wr._)`${o} === ${eI.default.errors}`);function d(){t.forIn("key",i,g=>{!c.length&&!u.length?m(g):t.if(h(g),()=>m(g))})}function h(g){let y;if(c.length>8){let v=(0,dl.schemaRefOrVal)(s,n.properties,"properties");y=(0,ul.isOwnProperty)(t,v,g)}else c.length?y=(0,wr.or)(...c.map(v=>(0,wr._)`${g} === ${v}`)):y=wr.nil;return u.length&&(y=(0,wr.or)(y,...u.map(v=>(0,wr._)`${(0,ul.usePattern)(e,v)}.test(${g})`))),(0,wr.not)(y)}function p(g){t.code((0,wr._)`delete ${i}[${g}]`)}function m(g){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){p(g);return}if(r===!1){e.setParams({additionalProperty:g}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,dl.alwaysValidSchema)(s,r)){let y=t.name("valid");l.removeAdditional==="failing"?(f(g,y,!1),t.if((0,wr.not)(y),()=>{e.reset(),p(g)})):(f(g,y),a||t.if((0,wr.not)(y),()=>t.break()))}}function f(g,y,v){let b={keyword:"additionalProperties",dataProp:g,dataPropType:dl.Type.Str};v===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(b,y)}}};qp.default=rI});var N0=E(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});var nI=Ls(),I0=ar(),Vp=ae(),j0=Lp(),iI={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:o}=e;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&j0.default.code(new nI.KeywordCxt(o,j0.default,"additionalProperties"));let s=(0,I0.allSchemaProperties)(r);for(let d of s)o.definedProperties.add(d);o.opts.unevaluated&&s.length&&o.props!==!0&&(o.props=Vp.mergeEvaluated.props(t,(0,Vp.toHash)(s),o.props));let a=s.filter(d=>!(0,Vp.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let l=t.name("valid");for(let d of a)c(d)?u(d):(t.if((0,I0.propertyInData)(t,i,d,o.opts.ownProperties)),u(d),o.allErrors||t.else().var(l,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(l);function c(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},l)}}};Up.default=iI});var q0=E(Fp=>{"use strict";Object.defineProperty(Fp,"__esModule",{value:!0});var M0=ar(),fl=H(),D0=ae(),Z0=ae(),oI={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:i,it:o}=e,{opts:s}=o,a=(0,M0.allSchemaProperties)(r),l=a.filter(f=>(0,D0.alwaysValidSchema)(o,r[f]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let c=s.strictSchema&&!s.allowMatchingProperties&&i.properties,u=t.name("valid");o.props!==!0&&!(o.props instanceof fl.Name)&&(o.props=(0,Z0.evaluatedPropsToName)(t,o.props));let{props:d}=o;h();function h(){for(let f of a)c&&p(f),o.allErrors?m(f):(t.var(u,!0),m(f),t.if(u))}function p(f){for(let g in c)new RegExp(f).test(g)&&(0,D0.checkStrictMode)(o,`property ${g} matches pattern ${f} (use allowMatchingProperties)`)}function m(f){t.forIn("key",n,g=>{t.if((0,fl._)`${(0,M0.usePattern)(e,f)}.test(${g})`,()=>{let y=l.includes(f);y||e.subschema({keyword:"patternProperties",schemaProp:f,dataProp:g,dataPropType:Z0.Type.Str},u),o.opts.unevaluated&&d!==!0?t.assign((0,fl._)`${d}[${g}]`,!0):!y&&!o.allErrors&&t.if((0,fl.not)(u),()=>t.break())})})}}};Fp.default=oI});var L0=E(Gp=>{"use strict";Object.defineProperty(Gp,"__esModule",{value:!0});var sI=ae(),aI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,sI.alwaysValidSchema)(n,r)){e.fail();return}let i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Gp.default=aI});var V0=E(Bp=>{"use strict";Object.defineProperty(Bp,"__esModule",{value:!0});var cI=ar(),lI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:cI.validateUnion,error:{message:"must match a schema in anyOf"}};Bp.default=lI});var U0=E(Jp=>{"use strict";Object.defineProperty(Jp,"__esModule",{value:!0});var ml=H(),uI=ae(),dI={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,ml._)`{passingSchemas: ${e.passing}}`},fI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:dI,code(e){let{gen:t,schema:r,parentSchema:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let o=r,s=t.let("valid",!1),a=t.let("passing",null),l=t.name("_valid");e.setParams({passing:a}),t.block(c),e.result(s,()=>e.reset(),()=>e.error(!0));function c(){o.forEach((u,d)=>{let h;(0,uI.alwaysValidSchema)(i,u)?t.var(l,!0):h=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},l),d>0&&t.if((0,ml._)`${l} && ${s}`).assign(s,!1).assign(a,(0,ml._)`[${a}, ${d}]`).else(),t.if(l,()=>{t.assign(s,!0),t.assign(a,d),h&&e.mergeEvaluated(h,ml.Name)})})}}};Jp.default=fI});var F0=E(Wp=>{"use strict";Object.defineProperty(Wp,"__esModule",{value:!0});var mI=ae(),pI={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=t.name("valid");r.forEach((o,s)=>{if((0,mI.alwaysValidSchema)(n,o))return;let a=e.subschema({keyword:"allOf",schemaProp:s},i);e.ok(i),e.mergeEvaluated(a)})}};Wp.default=pI});var J0=E(Hp=>{"use strict";Object.defineProperty(Hp,"__esModule",{value:!0});var pl=H(),B0=ae(),hI={message:({params:e})=>(0,pl.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,pl._)`{failingKeyword: ${e.ifClause}}`},gI={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:hI,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,B0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=G0(n,"then"),o=G0(n,"else");if(!i&&!o)return;let s=t.let("valid",!0),a=t.name("_valid");if(l(),e.reset(),i&&o){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(a,c("then",u),c("else",u))}else i?t.if(a,c("then")):t.if((0,pl.not)(a),c("else"));e.pass(s,()=>e.error(!0));function l(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(u)}function c(u,d){return()=>{let h=e.subschema({keyword:u},a);t.assign(s,a),e.mergeValidEvaluated(h,s),d?t.assign(d,(0,pl._)`${u}`):e.setParams({ifClause:u})}}}};function G0(e,t){let r=e.schema[t];return r!==void 0&&!(0,B0.alwaysValidSchema)(e,r)}Hp.default=gI});var W0=E(Kp=>{"use strict";Object.defineProperty(Kp,"__esModule",{value:!0});var _I=ae(),yI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,_I.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Kp.default=yI});var H0=E(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});var vI=Rp(),bI=$0(),wI=Ip(),xI=z0(),kI=E0(),SI=P0(),$I=R0(),TI=Lp(),zI=N0(),EI=q0(),AI=L0(),OI=V0(),PI=U0(),CI=F0(),RI=J0(),II=W0();function jI(e=!1){let t=[AI.default,OI.default,PI.default,CI.default,RI.default,II.default,$I.default,TI.default,SI.default,zI.default,EI.default];return e?t.push(bI.default,xI.default):t.push(vI.default,wI.default),t.push(kI.default),t}Qp.default=jI});var K0=E(Xp=>{"use strict";Object.defineProperty(Xp,"__esModule",{value:!0});var Le=H(),NI={message:({schemaCode:e})=>(0,Le.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,Le._)`{format: ${e}}`},MI={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:NI,code(e,t){let{gen:r,data:n,$data:i,schema:o,schemaCode:s,it:a}=e,{opts:l,errSchemaPath:c,schemaEnv:u,self:d}=a;if(!l.validateFormats)return;i?h():p();function h(){let m=r.scopeValue("formats",{ref:d.formats,code:l.code.formats}),f=r.const("fDef",(0,Le._)`${m}[${s}]`),g=r.let("fType"),y=r.let("format");r.if((0,Le._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>r.assign(g,(0,Le._)`${f}.type || "string"`).assign(y,(0,Le._)`${f}.validate`),()=>r.assign(g,(0,Le._)`"string"`).assign(y,f)),e.fail$data((0,Le.or)(v(),b()));function v(){return l.strictSchema===!1?Le.nil:(0,Le._)`${s} && !${y}`}function b(){let w=u.$async?(0,Le._)`(${f}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Le._)`${y}(${n})`,S=(0,Le._)`(typeof ${y} == "function" ? ${w} : ${y}.test(${n}))`;return(0,Le._)`${y} && ${y} !== true && ${g} === ${t} && !${S}`}}function p(){let m=d.formats[o];if(!m){v();return}if(m===!0)return;let[f,g,y]=b(m);f===t&&e.pass(w());function v(){if(l.strictSchema===!1){d.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${o}" ignored in schema at path "${c}"`}}function b(S){let Z=S instanceof RegExp?(0,Le.regexpCode)(S):l.code.formats?(0,Le._)`${l.code.formats}${(0,Le.getProperty)(o)}`:void 0,F=r.scopeValue("formats",{key:o,ref:S,code:Z});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,Le._)`${F}.validate`]:["string",S,F]}function w(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Le._)`await ${y}(${n})`}return typeof g=="function"?(0,Le._)`${y}(${n})`:(0,Le._)`${y}.test(${n})`}}}};Xp.default=MI});var Q0=E(Yp=>{"use strict";Object.defineProperty(Yp,"__esModule",{value:!0});var DI=K0(),ZI=[DI.default];Yp.default=ZI});var X0=E(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.contentVocabulary=wo.metadataVocabulary=void 0;wo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];wo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ex=E(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});var qI=a0(),LI=w0(),VI=H0(),UI=Q0(),Y0=X0(),FI=[qI.default,LI.default,(0,VI.default)(),UI.default,Y0.metadataVocabulary,Y0.contentVocabulary];eh.default=FI});var rx=E(hl=>{"use strict";Object.defineProperty(hl,"__esModule",{value:!0});hl.DiscrError=void 0;var tx;(function(e){e.Tag="tag",e.Mapping="mapping"})(tx||(hl.DiscrError=tx={}))});var ix=E(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});var xo=H(),th=rx(),nx=Kc(),GI=Vs(),BI=ae(),JI={message:({params:{discrError:e,tagName:t}})=>e===th.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,xo._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},WI={keyword:"discriminator",type:"object",schemaType:"object",error:JI,code(e){let{gen:t,data:r,schema:n,parentSchema:i,it:o}=e,{oneOf:s}=i;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let l=t.let("valid",!1),c=t.const("tag",(0,xo._)`${r}${(0,xo.getProperty)(a)}`);t.if((0,xo._)`typeof ${c} == "string"`,()=>u(),()=>e.error(!1,{discrError:th.DiscrError.Tag,tag:c,tagName:a})),e.ok(l);function u(){let p=h();t.if(!1);for(let m in p)t.elseIf((0,xo._)`${c} === ${m}`),t.assign(l,d(p[m]));t.else(),e.error(!1,{discrError:th.DiscrError.Mapping,tag:c,tagName:a}),t.endIf()}function d(p){let m=t.name("valid"),f=e.subschema({keyword:"oneOf",schemaProp:p},m);return e.mergeEvaluated(f,xo.Name),m}function h(){var p;let m={},f=y(i),g=!0;for(let w=0;w<s.length;w++){let S=s[w];if(S?.$ref&&!(0,BI.schemaHasRulesButRef)(S,o.self.RULES)){let F=S.$ref;if(S=nx.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,F),S instanceof nx.SchemaEnv&&(S=S.schema),S===void 0)throw new GI.default(o.opts.uriResolver,o.baseId,F)}let Z=(p=S?.properties)===null||p===void 0?void 0:p[a];if(typeof Z!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(f||y(S)),v(Z,w)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return m;function y({required:w}){return Array.isArray(w)&&w.includes(a)}function v(w,S){if(w.const)b(w.const,S);else if(w.enum)for(let Z of w.enum)b(Z,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(w,S){if(typeof w!="string"||w in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[w]=S}}}};rh.default=WI});var ox=E((LV,HI)=>{HI.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var ih=E((ze,nh)=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.MissingRefError=ze.ValidationError=ze.CodeGen=ze.Name=ze.nil=ze.stringify=ze.str=ze._=ze.KeywordCxt=ze.Ajv=void 0;var KI=t0(),QI=ex(),XI=ix(),sx=ox(),YI=["/properties"],gl="http://json-schema.org/draft-07/schema",ko=class extends KI.default{_addVocabularies(){super._addVocabularies(),QI.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(XI.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(sx,YI):sx;this.addMetaSchema(t,gl,!1),this.refs["http://json-schema.org/schema"]=gl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(gl)?gl:void 0)}};ze.Ajv=ko;nh.exports=ze=ko;nh.exports.Ajv=ko;Object.defineProperty(ze,"__esModule",{value:!0});ze.default=ko;var ej=Ls();Object.defineProperty(ze,"KeywordCxt",{enumerable:!0,get:function(){return ej.KeywordCxt}});var So=H();Object.defineProperty(ze,"_",{enumerable:!0,get:function(){return So._}});Object.defineProperty(ze,"str",{enumerable:!0,get:function(){return So.str}});Object.defineProperty(ze,"stringify",{enumerable:!0,get:function(){return So.stringify}});Object.defineProperty(ze,"nil",{enumerable:!0,get:function(){return So.nil}});Object.defineProperty(ze,"Name",{enumerable:!0,get:function(){return So.Name}});Object.defineProperty(ze,"CodeGen",{enumerable:!0,get:function(){return So.CodeGen}});var tj=Wc();Object.defineProperty(ze,"ValidationError",{enumerable:!0,get:function(){return tj.default}});var rj=Vs();Object.defineProperty(ze,"MissingRefError",{enumerable:!0,get:function(){return rj.default}})});var px=E(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.formatNames=Fr.fastFormats=Fr.fullFormats=void 0;function Ur(e,t){return{validate:e,compare:t}}Fr.fullFormats={date:Ur(ux,ch),time:Ur(sh(!0),lh),"date-time":Ur(ax(!0),fx),"iso-time":Ur(sh(),dx),"iso-date-time":Ur(ax(),mx),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:cj,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:hj,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:lj,int32:{type:"number",validate:fj},int64:{type:"number",validate:mj},float:{type:"number",validate:lx},double:{type:"number",validate:lx},password:!0,binary:!0};Fr.fastFormats={...Fr.fullFormats,date:Ur(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ch),time:Ur(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,lh),"date-time":Ur(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,fx),"iso-time":Ur(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,dx),"iso-date-time":Ur(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,mx),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Fr.formatNames=Object.keys(Fr.fullFormats);function nj(e){return e%4===0&&(e%100!==0||e%400===0)}var ij=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,oj=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ux(e){let t=ij.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],i=+t[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&nj(r)?29:oj[n])}function ch(e,t){if(e&&t)return e>t?1:e<t?-1:0}var oh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function sh(e){return function(r){let n=oh.exec(r);if(!n)return!1;let i=+n[1],o=+n[2],s=+n[3],a=n[4],l=n[5]==="-"?-1:1,c=+(n[6]||0),u=+(n[7]||0);if(c>23||u>59||e&&!a)return!1;if(i<=23&&o<=59&&s<60)return!0;let d=o-u*l,h=i-c*l-(d<0?1:0);return(h===23||h===-1)&&(d===59||d===-1)&&s<61}}function lh(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}function dx(e,t){if(!(e&&t))return;let r=oh.exec(e),n=oh.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}var ah=/t|\s/i;function ax(e){let t=sh(e);return function(n){let i=n.split(ah);return i.length===2&&ux(i[0])&&t(i[1])}}function fx(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function mx(e,t){if(!(e&&t))return;let[r,n]=e.split(ah),[i,o]=t.split(ah),s=ch(r,i);if(s!==void 0)return s||lh(n,o)}var sj=/\/|:/,aj=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function cj(e){return sj.test(e)&&aj.test(e)}var cx=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function lj(e){return cx.lastIndex=0,cx.test(e)}var uj=-(2**31),dj=2**31-1;function fj(e){return Number.isInteger(e)&&e<=dj&&e>=uj}function mj(e){return Number.isInteger(e)}function lx(){return!0}var pj=/[^\\]\\Z/;function hj(e){if(pj.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var hx=E($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.formatLimitDefinition=void 0;var gj=ih(),xr=H(),Mn=xr.operators,_l={formatMaximum:{okStr:"<=",ok:Mn.LTE,fail:Mn.GT},formatMinimum:{okStr:">=",ok:Mn.GTE,fail:Mn.LT},formatExclusiveMaximum:{okStr:"<",ok:Mn.LT,fail:Mn.GTE},formatExclusiveMinimum:{okStr:">",ok:Mn.GT,fail:Mn.LTE}},_j={message:({keyword:e,schemaCode:t})=>(0,xr.str)`should be ${_l[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,xr._)`{comparison: ${_l[e].okStr}, limit: ${t}}`};$o.formatLimitDefinition={keyword:Object.keys(_l),type:"string",schemaType:"string",$data:!0,error:_j,code(e){let{gen:t,data:r,schemaCode:n,keyword:i,it:o}=e,{opts:s,self:a}=o;if(!s.validateFormats)return;let l=new gj.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?c():u();function c(){let h=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=t.const("fmt",(0,xr._)`${h}[${l.schemaCode}]`);e.fail$data((0,xr.or)((0,xr._)`typeof ${p} != "object"`,(0,xr._)`${p} instanceof RegExp`,(0,xr._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let h=l.schema,p=a.formats[h];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${i}": format "${h}" does not define "compare" function`);let m=t.scopeValue("formats",{key:h,ref:p,code:s.code.formats?(0,xr._)`${s.code.formats}${(0,xr.getProperty)(h)}`:void 0});e.fail$data(d(m))}function d(h){return(0,xr._)`${h}.compare(${r}, ${n}) ${_l[i].fail} 0`}},dependencies:["format"]};var yj=e=>(e.addKeyword($o.formatLimitDefinition),e);$o.default=yj});var vx=E((ra,yx)=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});var To=px(),vj=hx(),uh=H(),gx=new uh.Name("fullFormats"),bj=new uh.Name("fastFormats"),dh=(e,t={keywords:!0})=>{if(Array.isArray(t))return _x(e,t,To.fullFormats,gx),e;let[r,n]=t.mode==="fast"?[To.fastFormats,bj]:[To.fullFormats,gx],i=t.formats||To.formatNames;return _x(e,i,r,n),t.keywords&&(0,vj.default)(e),e};dh.get=(e,t="full")=>{let n=(t==="fast"?To.fastFormats:To.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function _x(e,t,r,n){var i,o;(i=(o=e.opts.code).formats)!==null&&i!==void 0||(o.formats=(0,uh._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}yx.exports=ra=dh;Object.defineProperty(ra,"__esModule",{value:!0});ra.default=dh});import*as jx from"node:url";import*as le from"node:fs";import*as sa from"node:crypto";function ur(e){return e===void 0?{BS_PRIVATE_NESTED_SOME_NONE:0}:e!==null&&e.BS_PRIVATE_NESTED_SOME_NONE!==void 0?{BS_PRIVATE_NESTED_SOME_NONE:e.BS_PRIVATE_NESTED_SOME_NONE+1|0}:e}function Oi(e){if(e!=null)return ur(e)}function de(e){if(e===null||e.BS_PRIVATE_NESTED_SOME_NONE===void 0)return e;let t=e.BS_PRIVATE_NESTED_SOME_NONE;if(t!==0)return{BS_PRIVATE_NESTED_SOME_NONE:t-1|0}}function $r(e){if(e.RE_EXN_ID==="JsExn")return ur(e._1)}var oa=(e=>t=>t&&typeof t[e]=="string"?t[e]:void 0),Lj=oa("stack"),Tr=oa("message"),Vj=oa("name"),Uj=oa("fileName");function ft(e,t){if(e!==void 0)return ur(t(de(e)))}function He(e,t){if(e!==void 0)return t(de(e))}function xt(e,t){return e!==void 0?de(e):t}var wh=(function(e,t){for(var r in e)t(r)});function kt(e,t){if(e===t)return!0;let r=typeof e;if(r==="string"||r==="number"||r==="bigint"||r==="boolean"||r==="undefined"||e===null)return!1;let n=typeof t;if(r==="function"||n==="function")throw{RE_EXN_ID:"Invalid_argument",_1:"equal: functional value",Error:new Error};if(n==="number"||n==="bigint"||n==="undefined"||t===null)return!1;let i=e.TAG,o=t.TAG;if(i!==o)return!1;let s=e.length|0,a=t.length|0;if(s===a)if(Array.isArray(e)){let l=0;for(;;){let c=l;if(c===s)return!0;if(!kt(e[c],t[c]))return!1;l=c+1|0}}else{if(e instanceof Date&&t instanceof Date)return!(e>t||e<t);{let l={contents:!0},c=d=>{if(!Object.prototype.hasOwnProperty.call(t,d)){l.contents=!1;return}},u=d=>{if(!Object.prototype.hasOwnProperty.call(e,d)||!kt(t[d],e[d])){l.contents=!1;return}};return wh(e,c),l.contents&&wh(t,u),l.contents}}else return!1}import*as kh from"node:child_process";function Hx(e){return e==null?!1:typeof e.RE_EXN_ID=="string"}function ee(e){return Hx(e)?e:{RE_EXN_ID:"JsExn",_1:e}}var El={};function xh(e){let t=El[e];if(t!==void 0){let r=t+1|0;return El[e]=r,e+("/"+r)}return El[e]=1,e}function mt(e){let t=$r(e);if(t===void 0)return{code:void 0,message:"unknown error"};let r=de(t);return{code:Oi(r.code),message:xt(Tr(r),"unknown error")}}function Sh(e,t){return kt(e.code,t)}function fr(e){try{return{TAG:"Ok",_0:le.readFileSync(e,"utf8")}}catch(t){let r=ee(t);return{TAG:"Error",_0:mt(r)}}}function $h(e,t){try{return{TAG:"Ok",_0:(le.writeFileSync(e,t,"utf8"),void 0)}}catch(r){let n=ee(r);return{TAG:"Error",_0:mt(n)}}}function Oo(e,t,r){try{return{TAG:"Ok",_0:(le.writeFileSync(e,t,r),void 0)}}catch(n){let i=ee(n);return{TAG:"Error",_0:mt(i)}}}function zr(e){try{return{TAG:"Ok",_0:(le.mkdirSync(e,{recursive:!0}),void 0)}}catch(t){let r=ee(t);return{TAG:"Error",_0:mt(r)}}}function aa(e,t){try{return{TAG:"Ok",_0:(le.chmodSync(e,t),void 0)}}catch(r){let n=ee(r);return{TAG:"Error",_0:mt(n)}}}function Th(e,t){try{return{TAG:"Ok",_0:(le.linkSync(e,t),void 0)}}catch(r){let n=ee(r);return{TAG:"Error",_0:mt(n)}}}function zh(e){try{return{TAG:"Ok",_0:(le.unlinkSync(e),void 0)}}catch(t){let r=ee(t);return{TAG:"Error",_0:mt(r)}}}function ca(e,t){try{return{TAG:"Ok",_0:(le.renameSync(e,t),void 0)}}catch(r){let n=ee(r);return{TAG:"Error",_0:mt(n)}}}function Pi(e){try{return{TAG:"Ok",_0:(le.rmSync(e,{force:!0}),void 0)}}catch(t){let r=ee(t);return{TAG:"Error",_0:mt(r)}}}function la(e){return sa.createHash("sha256").update(e).digest("hex")}function Eh(e){try{return sa.randomBytes(e).toString("hex")}catch{return""}}function Ah(e){try{return{TAG:"Ok",_0:le.readdirSync(e)}}catch(t){let r=ee(t);return{TAG:"Error",_0:mt(r)}}}function Oh(e,t,r,n){try{return{TAG:"Ok",_0:kh.execFileSync(e,t,{encoding:"utf8",timeout:r,maxBuffer:n})}}catch(i){let o=ee(i);return{TAG:"Error",_0:mt(o)}}}function Po(e){try{return process.stderr.write(e)}catch{return!1}}function Al(e,t){return e[t]}function Ol(e,t){try{return process.kill(e,t),{TAG:"Ok",_0:void 0}}catch(r){let n=ee(r);return{TAG:"Error",_0:mt(n)}}}function Ci(e){try{return ur(new URL(e))}catch{return}}function Br(e,t){try{return{TAG:"Ok",_0:new URL(e,t)}}catch(r){let n=ee(r),i=$r(n);return{TAG:"Error",_0:i!==void 0?xt(Tr(de(i)),"unknown error"):"unknown error"}}}var Fe={};Fe["api-url"]="ValueKind";Fe.token="ValueKind";Fe["auth-file"]="ValueKind";Fe["delegation-auth-file"]="ValueKind";Fe.workspace="ValueKind";Fe.channel="ValueKind";Fe["owner-username"]="ValueKind";Fe.mode="ValueKind";Fe.cwd="ValueKind";Fe["thread-id"]="ValueKind";Fe.format="ValueKind";Fe.command="ValueKind";Fe["tool-scope"]="ValueKind";Fe["agent-session"]="BooleanKind";Fe["ask-user-question-tool"]="BooleanKind";Fe["multi-agent-jobs"]="BooleanKind";Fe["include-token"]="BooleanKind";Fe.help="BooleanKind";function ua(e){let t={},r,n=0;for(;r===void 0&&n<e.length;){let o=e[n];if(o!==void 0)if(o.startsWith("--")){let s=o.slice(2),a=Fe[s];if(a!==void 0)if(a==="ValueKind"){let l=e[n+1|0];l!==void 0?l.startsWith("--")?r="--"+s+" requires a value":(t[s]={TAG:"ValueFlag",_0:l},n=n+2|0):r="--"+s+" requires a value"}else t[s]="BoolFlag",n=n+1|0;else r="unsupported option --"+s}else r="unexpected argument "+o;else n=n+1|0}let i=r;return i!==void 0?{TAG:"Error",_0:i}:{TAG:"Ok",_0:t}}function Me(e,t){let r=e[t];if(r===void 0||typeof r!="object")return;let n=r._0;if(n.trim()!=="")return n}function Ri(e,t){let r=e[t];return r!==void 0?typeof r!="object":!1}function da(e,t){let r=Me(e,t);return r!==void 0?{TAG:"Ok",_0:r}:{TAG:"Error",_0:"--"+t+" is required"}}function fa(e){if(e===void 0)return{TAG:"Ok",_0:"Text"};switch(e){case"text":return{TAG:"Ok",_0:"Text"};case"voice":return{TAG:"Ok",_0:"Voice"};default:return{TAG:"Error",_0:"--mode must be voice or text"}}}function Pl(e){if(e===void 0)return{TAG:"Ok",_0:"All"};switch(e){case"all":return{TAG:"Ok",_0:"All"};case"coding":return{TAG:"Ok",_0:"Coding"};case"onboarding-discovery":return{TAG:"Ok",_0:"OnboardingDiscovery"};default:return{TAG:"Error",_0:"--tool-scope must be all, coding, or onboarding-discovery"}}}function Ph(e){return e[0]==="mcp"?e.slice(1):e}function ma(){return`Linzumi MCP
11
+ deps: ${r}}`};var Uj={keyword:"dependencies",type:"object",schemaType:"object",error:Wr.error,code(e){let[t,r]=Gj(e);Hx(e,t),Kx(e,r)}};function Gj({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let i=Array.isArray(e[n])?t:r;i[n]=e[n]}return[t,r]}function Hx(e,t=e.schema){let{gen:r,data:n,it:i}=e;if(Object.keys(t).length===0)return;let o=r.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let u=(0,Sa.propertyInData)(r,n,s,i.opts.ownProperties);e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),i.allErrors?r.if(u,()=>{for(let c of a)(0,Sa.checkReportMissingProp)(e,c)}):(r.if((0,Ah._)`${u} && (${(0,Sa.checkMissingProp)(e,a,o)})`),(0,Sa.reportMissingProp)(e,o),r.else())}}Wr.validatePropertyDeps=Hx;function Kx(e,t=e.schema){let{gen:r,data:n,keyword:i,it:o}=e,s=r.name("valid");for(let a in t)(0,Fj.alwaysValidSchema)(o,t[a])||(r.if((0,Sa.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let u=e.subschema({keyword:i,schemaProp:a},s);e.mergeValidEvaluated(u,s)},()=>r.var(s,!0)),e.ok(s))}Wr.validateSchemaDeps=Kx;Wr.default=Uj});var Yx=z(Ph=>{"use strict";Object.defineProperty(Ph,"__esModule",{value:!0});var Xx=ne(),Vj=he(),Bj={message:"property name must be valid",params:({params:e})=>(0,Xx._)`{propertyName: ${e.propertyName}}`},Jj={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Bj,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,Vj.alwaysValidSchema)(i,r))return;let o=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),t.if((0,Xx.not)(o),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(o)}};Ph.default=Jj});var Rh=z(Ch=>{"use strict";Object.defineProperty(Ch,"__esModule",{value:!0});var Gl=fr(),zr=ne(),Wj=hn(),Vl=he(),Hj={message:"must NOT have additional properties",params:({params:e})=>(0,zr._)`{additionalProperty: ${e.additionalProperty}}`},Kj={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Hj,code(e){let{gen:t,schema:r,parentSchema:n,data:i,errsCount:o,it:s}=e;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:u}=s;if(s.props=!0,u.removeAdditional!=="all"&&(0,Vl.alwaysValidSchema)(s,r))return;let c=(0,Gl.allSchemaProperties)(n.properties),l=(0,Gl.allSchemaProperties)(n.patternProperties);d(),e.ok((0,zr._)`${o} === ${Wj.default.errors}`);function d(){t.forIn("key",i,g=>{!c.length&&!l.length?p(g):t.if(h(g),()=>p(g))})}function h(g){let y;if(c.length>8){let v=(0,Vl.schemaRefOrVal)(s,n.properties,"properties");y=(0,Gl.isOwnProperty)(t,v,g)}else c.length?y=(0,zr.or)(...c.map(v=>(0,zr._)`${g} === ${v}`)):y=zr.nil;return l.length&&(y=(0,zr.or)(y,...l.map(v=>(0,zr._)`${(0,Gl.usePattern)(e,v)}.test(${g})`))),(0,zr.not)(y)}function m(g){t.code((0,zr._)`delete ${i}[${g}]`)}function p(g){if(u.removeAdditional==="all"||u.removeAdditional&&r===!1){m(g);return}if(r===!1){e.setParams({additionalProperty:g}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,Vl.alwaysValidSchema)(s,r)){let y=t.name("valid");u.removeAdditional==="failing"?(f(g,y,!1),t.if((0,zr.not)(y),()=>{e.reset(),m(g)})):(f(g,y),a||t.if((0,zr.not)(y),()=>t.break()))}}function f(g,y,v){let b={keyword:"additionalProperties",dataProp:g,dataPropType:Vl.Type.Str};v===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(b,y)}}};Ch.default=Kj});var rk=z(jh=>{"use strict";Object.defineProperty(jh,"__esModule",{value:!0});var Qj=ua(),ek=fr(),Ih=he(),tk=Rh(),Xj={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:o}=e;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&tk.default.code(new Qj.KeywordCxt(o,tk.default,"additionalProperties"));let s=(0,ek.allSchemaProperties)(r);for(let d of s)o.definedProperties.add(d);o.opts.unevaluated&&s.length&&o.props!==!0&&(o.props=Ih.mergeEvaluated.props(t,(0,Ih.toHash)(s),o.props));let a=s.filter(d=>!(0,Ih.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let u=t.name("valid");for(let d of a)c(d)?l(d):(t.if((0,ek.propertyInData)(t,i,d,o.opts.ownProperties)),l(d),o.allErrors||t.else().var(u,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(u);function c(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function l(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},u)}}};jh.default=Xj});var sk=z(Nh=>{"use strict";Object.defineProperty(Nh,"__esModule",{value:!0});var nk=fr(),Bl=ne(),ik=he(),ok=he(),Yj={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:i,it:o}=e,{opts:s}=o,a=(0,nk.allSchemaProperties)(r),u=a.filter(f=>(0,ik.alwaysValidSchema)(o,r[f]));if(a.length===0||u.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let c=s.strictSchema&&!s.allowMatchingProperties&&i.properties,l=t.name("valid");o.props!==!0&&!(o.props instanceof Bl.Name)&&(o.props=(0,ok.evaluatedPropsToName)(t,o.props));let{props:d}=o;h();function h(){for(let f of a)c&&m(f),o.allErrors?p(f):(t.var(l,!0),p(f),t.if(l))}function m(f){for(let g in c)new RegExp(f).test(g)&&(0,ik.checkStrictMode)(o,`property ${g} matches pattern ${f} (use allowMatchingProperties)`)}function p(f){t.forIn("key",n,g=>{t.if((0,Bl._)`${(0,nk.usePattern)(e,f)}.test(${g})`,()=>{let y=u.includes(f);y||e.subschema({keyword:"patternProperties",schemaProp:f,dataProp:g,dataPropType:ok.Type.Str},l),o.opts.unevaluated&&d!==!0?t.assign((0,Bl._)`${d}[${g}]`,!0):!y&&!o.allErrors&&t.if((0,Bl.not)(l),()=>t.break())})})}}};Nh.default=Yj});var ak=z(Mh=>{"use strict";Object.defineProperty(Mh,"__esModule",{value:!0});var eN=he(),tN={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,eN.alwaysValidSchema)(n,r)){e.fail();return}let i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Mh.default=tN});var ck=z(Dh=>{"use strict";Object.defineProperty(Dh,"__esModule",{value:!0});var rN=fr(),nN={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:rN.validateUnion,error:{message:"must match a schema in anyOf"}};Dh.default=nN});var lk=z(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});var Jl=ne(),iN=he(),oN={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Jl._)`{passingSchemas: ${e.passing}}`},sN={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:oN,code(e){let{gen:t,schema:r,parentSchema:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let o=r,s=t.let("valid",!1),a=t.let("passing",null),u=t.name("_valid");e.setParams({passing:a}),t.block(c),e.result(s,()=>e.reset(),()=>e.error(!0));function c(){o.forEach((l,d)=>{let h;(0,iN.alwaysValidSchema)(i,l)?t.var(u,!0):h=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},u),d>0&&t.if((0,Jl._)`${u} && ${s}`).assign(s,!1).assign(a,(0,Jl._)`[${a}, ${d}]`).else(),t.if(u,()=>{t.assign(s,!0),t.assign(a,d),h&&e.mergeEvaluated(h,Jl.Name)})})}}};Zh.default=sN});var uk=z(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});var aN=he(),cN={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=t.name("valid");r.forEach((o,s)=>{if((0,aN.alwaysValidSchema)(n,o))return;let a=e.subschema({keyword:"allOf",schemaProp:s},i);e.ok(i),e.mergeEvaluated(a)})}};Lh.default=cN});var mk=z(qh=>{"use strict";Object.defineProperty(qh,"__esModule",{value:!0});var Wl=ne(),fk=he(),lN={message:({params:e})=>(0,Wl.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Wl._)`{failingKeyword: ${e.ifClause}}`},uN={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:lN,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,fk.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=dk(n,"then"),o=dk(n,"else");if(!i&&!o)return;let s=t.let("valid",!0),a=t.name("_valid");if(u(),e.reset(),i&&o){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,c("then",l),c("else",l))}else i?t.if(a,c("then")):t.if((0,Wl.not)(a),c("else"));e.pass(s,()=>e.error(!0));function u(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function c(l,d){return()=>{let h=e.subschema({keyword:l},a);t.assign(s,a),e.mergeValidEvaluated(h,s),d?t.assign(d,(0,Wl._)`${l}`):e.setParams({ifClause:l})}}}};function dk(e,t){let r=e.schema[t];return r!==void 0&&!(0,fk.alwaysValidSchema)(e,r)}qh.default=uN});var pk=z(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});var dN=he(),fN={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,dN.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Fh.default=fN});var hk=z(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});var mN=Th(),pN=Vx(),hN=$h(),gN=Jx(),_N=Wx(),yN=Qx(),vN=Yx(),bN=Rh(),wN=rk(),xN=sk(),kN=ak(),SN=ck(),TN=lk(),$N=uk(),EN=mk(),zN=pk();function ON(e=!1){let t=[kN.default,SN.default,TN.default,$N.default,EN.default,zN.default,vN.default,bN.default,yN.default,wN.default,xN.default];return e?t.push(pN.default,gN.default):t.push(mN.default,hN.default),t.push(_N.default),t}Uh.default=ON});var gk=z(Gh=>{"use strict";Object.defineProperty(Gh,"__esModule",{value:!0});var Xe=ne(),AN={message:({schemaCode:e})=>(0,Xe.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,Xe._)`{format: ${e}}`},PN={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:AN,code(e,t){let{gen:r,data:n,$data:i,schema:o,schemaCode:s,it:a}=e,{opts:u,errSchemaPath:c,schemaEnv:l,self:d}=a;if(!u.validateFormats)return;i?h():m();function h(){let p=r.scopeValue("formats",{ref:d.formats,code:u.code.formats}),f=r.const("fDef",(0,Xe._)`${p}[${s}]`),g=r.let("fType"),y=r.let("format");r.if((0,Xe._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>r.assign(g,(0,Xe._)`${f}.type || "string"`).assign(y,(0,Xe._)`${f}.validate`),()=>r.assign(g,(0,Xe._)`"string"`).assign(y,f)),e.fail$data((0,Xe.or)(v(),b()));function v(){return u.strictSchema===!1?Xe.nil:(0,Xe._)`${s} && !${y}`}function b(){let w=l.$async?(0,Xe._)`(${f}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Xe._)`${y}(${n})`,S=(0,Xe._)`(typeof ${y} == "function" ? ${w} : ${y}.test(${n}))`;return(0,Xe._)`${y} && ${y} !== true && ${g} === ${t} && !${S}`}}function m(){let p=d.formats[o];if(!p){v();return}if(p===!0)return;let[f,g,y]=b(p);f===t&&e.pass(w());function v(){if(u.strictSchema===!1){d.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${o}" ignored in schema at path "${c}"`}}function b(S){let q=S instanceof RegExp?(0,Xe.regexpCode)(S):u.code.formats?(0,Xe._)`${u.code.formats}${(0,Xe.getProperty)(o)}`:void 0,K=r.scopeValue("formats",{key:o,ref:S,code:q});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,Xe._)`${K}.validate`]:["string",S,K]}function w(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Xe._)`await ${y}(${n})`}return typeof g=="function"?(0,Xe._)`${y}(${n})`:(0,Xe._)`${y}.test(${n})`}}}};Gh.default=PN});var _k=z(Vh=>{"use strict";Object.defineProperty(Vh,"__esModule",{value:!0});var CN=gk(),RN=[CN.default];Vh.default=RN});var yk=z(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.contentVocabulary=Uo.metadataVocabulary=void 0;Uo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Uo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var bk=z(Bh=>{"use strict";Object.defineProperty(Bh,"__esModule",{value:!0});var IN=Ex(),jN=qx(),NN=hk(),MN=_k(),vk=yk(),DN=[IN.default,jN.default,(0,NN.default)(),MN.default,vk.metadataVocabulary,vk.contentVocabulary];Bh.default=DN});var xk=z(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});Hl.DiscrError=void 0;var wk;(function(e){e.Tag="tag",e.Mapping="mapping"})(wk||(Hl.DiscrError=wk={}))});var Sk=z(Wh=>{"use strict";Object.defineProperty(Wh,"__esModule",{value:!0});var Go=ne(),Jh=xk(),kk=Al(),ZN=da(),LN=he(),qN={message:({params:{discrError:e,tagName:t}})=>e===Jh.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Go._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},FN={keyword:"discriminator",type:"object",schemaType:"object",error:qN,code(e){let{gen:t,data:r,schema:n,parentSchema:i,it:o}=e,{oneOf:s}=i;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let u=t.let("valid",!1),c=t.const("tag",(0,Go._)`${r}${(0,Go.getProperty)(a)}`);t.if((0,Go._)`typeof ${c} == "string"`,()=>l(),()=>e.error(!1,{discrError:Jh.DiscrError.Tag,tag:c,tagName:a})),e.ok(u);function l(){let m=h();t.if(!1);for(let p in m)t.elseIf((0,Go._)`${c} === ${p}`),t.assign(u,d(m[p]));t.else(),e.error(!1,{discrError:Jh.DiscrError.Mapping,tag:c,tagName:a}),t.endIf()}function d(m){let p=t.name("valid"),f=e.subschema({keyword:"oneOf",schemaProp:m},p);return e.mergeEvaluated(f,Go.Name),p}function h(){var m;let p={},f=y(i),g=!0;for(let w=0;w<s.length;w++){let S=s[w];if(S?.$ref&&!(0,LN.schemaHasRulesButRef)(S,o.self.RULES)){let K=S.$ref;if(S=kk.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,K),S instanceof kk.SchemaEnv&&(S=S.schema),S===void 0)throw new ZN.default(o.opts.uriResolver,o.baseId,K)}let q=(m=S?.properties)===null||m===void 0?void 0:m[a];if(typeof q!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(f||y(S)),v(q,w)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:w}){return Array.isArray(w)&&w.includes(a)}function v(w,S){if(w.const)b(w.const,S);else if(w.enum)for(let q of w.enum)b(q,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(w,S){if(typeof w!="string"||w in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[w]=S}}}};Wh.default=FN});var Tk=z((JG,UN)=>{UN.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Kh=z((Ie,Hh)=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.MissingRefError=Ie.ValidationError=Ie.CodeGen=Ie.Name=Ie.nil=Ie.stringify=Ie.str=Ie._=Ie.KeywordCxt=Ie.Ajv=void 0;var GN=wx(),VN=bk(),BN=Sk(),$k=Tk(),JN=["/properties"],Kl="http://json-schema.org/draft-07/schema",Vo=class extends GN.default{_addVocabularies(){super._addVocabularies(),VN.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(BN.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema($k,JN):$k;this.addMetaSchema(t,Kl,!1),this.refs["http://json-schema.org/schema"]=Kl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Kl)?Kl:void 0)}};Ie.Ajv=Vo;Hh.exports=Ie=Vo;Hh.exports.Ajv=Vo;Object.defineProperty(Ie,"__esModule",{value:!0});Ie.default=Vo;var WN=ua();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return WN.KeywordCxt}});var Bo=ne();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return Bo._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return Bo.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return Bo.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return Bo.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return Bo.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return Bo.CodeGen}});var HN=zl();Object.defineProperty(Ie,"ValidationError",{enumerable:!0,get:function(){return HN.default}});var KN=da();Object.defineProperty(Ie,"MissingRefError",{enumerable:!0,get:function(){return KN.default}})});var Ik=z(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.formatNames=Kr.fastFormats=Kr.fullFormats=void 0;function Hr(e,t){return{validate:e,compare:t}}Kr.fullFormats={date:Hr(Ak,eg),time:Hr(Xh(!0),tg),"date-time":Hr(Ek(!0),Ck),"iso-time":Hr(Xh(),Pk),"iso-date-time":Hr(Ek(),Rk),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:rM,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:lM,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:nM,int32:{type:"number",validate:sM},int64:{type:"number",validate:aM},float:{type:"number",validate:Ok},double:{type:"number",validate:Ok},password:!0,binary:!0};Kr.fastFormats={...Kr.fullFormats,date:Hr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,eg),time:Hr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,tg),"date-time":Hr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ck),"iso-time":Hr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Pk),"iso-date-time":Hr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Rk),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Kr.formatNames=Object.keys(Kr.fullFormats);function QN(e){return e%4===0&&(e%100!==0||e%400===0)}var XN=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,YN=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Ak(e){let t=XN.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],i=+t[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&QN(r)?29:YN[n])}function eg(e,t){if(e&&t)return e>t?1:e<t?-1:0}var Qh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Xh(e){return function(r){let n=Qh.exec(r);if(!n)return!1;let i=+n[1],o=+n[2],s=+n[3],a=n[4],u=n[5]==="-"?-1:1,c=+(n[6]||0),l=+(n[7]||0);if(c>23||l>59||e&&!a)return!1;if(i<=23&&o<=59&&s<60)return!0;let d=o-l*u,h=i-c*u-(d<0?1:0);return(h===23||h===-1)&&(d===59||d===-1)&&s<61}}function tg(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}function Pk(e,t){if(!(e&&t))return;let r=Qh.exec(e),n=Qh.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}var Yh=/t|\s/i;function Ek(e){let t=Xh(e);return function(n){let i=n.split(Yh);return i.length===2&&Ak(i[0])&&t(i[1])}}function Ck(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Rk(e,t){if(!(e&&t))return;let[r,n]=e.split(Yh),[i,o]=t.split(Yh),s=eg(r,i);if(s!==void 0)return s||tg(n,o)}var eM=/\/|:/,tM=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function rM(e){return eM.test(e)&&tM.test(e)}var zk=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function nM(e){return zk.lastIndex=0,zk.test(e)}var iM=-(2**31),oM=2**31-1;function sM(e){return Number.isInteger(e)&&e<=oM&&e>=iM}function aM(e){return Number.isInteger(e)}function Ok(){return!0}var cM=/[^\\]\\Z/;function lM(e){if(cM.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var jk=z(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.formatLimitDefinition=void 0;var uM=Kh(),Or=ne(),Wn=Or.operators,Ql={formatMaximum:{okStr:"<=",ok:Wn.LTE,fail:Wn.GT},formatMinimum:{okStr:">=",ok:Wn.GTE,fail:Wn.LT},formatExclusiveMaximum:{okStr:"<",ok:Wn.LT,fail:Wn.GTE},formatExclusiveMinimum:{okStr:">",ok:Wn.GT,fail:Wn.LTE}},dM={message:({keyword:e,schemaCode:t})=>(0,Or.str)`should be ${Ql[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Or._)`{comparison: ${Ql[e].okStr}, limit: ${t}}`};Jo.formatLimitDefinition={keyword:Object.keys(Ql),type:"string",schemaType:"string",$data:!0,error:dM,code(e){let{gen:t,data:r,schemaCode:n,keyword:i,it:o}=e,{opts:s,self:a}=o;if(!s.validateFormats)return;let u=new uM.KeywordCxt(o,a.RULES.all.format.definition,"format");u.$data?c():l();function c(){let h=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),m=t.const("fmt",(0,Or._)`${h}[${u.schemaCode}]`);e.fail$data((0,Or.or)((0,Or._)`typeof ${m} != "object"`,(0,Or._)`${m} instanceof RegExp`,(0,Or._)`typeof ${m}.compare != "function"`,d(m)))}function l(){let h=u.schema,m=a.formats[h];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${i}": format "${h}" does not define "compare" function`);let p=t.scopeValue("formats",{key:h,ref:m,code:s.code.formats?(0,Or._)`${s.code.formats}${(0,Or.getProperty)(h)}`:void 0});e.fail$data(d(p))}function d(h){return(0,Or._)`${h}.compare(${r}, ${n}) ${Ql[i].fail} 0`}},dependencies:["format"]};var fM=e=>(e.addKeyword(Jo.formatLimitDefinition),e);Jo.default=fM});var Zk=z((Ta,Dk)=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});var Wo=Ik(),mM=jk(),rg=ne(),Nk=new rg.Name("fullFormats"),pM=new rg.Name("fastFormats"),ng=(e,t={keywords:!0})=>{if(Array.isArray(t))return Mk(e,t,Wo.fullFormats,Nk),e;let[r,n]=t.mode==="fast"?[Wo.fastFormats,pM]:[Wo.fullFormats,Nk],i=t.formats||Wo.formatNames;return Mk(e,i,r,n),t.keywords&&(0,mM.default)(e),e};ng.get=(e,t="full")=>{let n=(t==="fast"?Wo.fastFormats:Wo.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Mk(e,t,r,n){var i,o;(i=(o=e.opts.code).formats)!==null&&i!==void 0||(o.formats=(0,rg._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}Dk.exports=Ta=ng;Object.defineProperty(Ta,"__esModule",{value:!0});Ta.default=ng});import*as tS from"node:url";import*as be from"node:fs";import*as Oa from"node:crypto";function gr(e){return e===void 0?{BS_PRIVATE_NESTED_SOME_NONE:0}:e!==null&&e.BS_PRIVATE_NESTED_SOME_NONE!==void 0?{BS_PRIVATE_NESTED_SOME_NONE:e.BS_PRIVATE_NESTED_SOME_NONE+1|0}:e}function Ji(e){if(e!=null)return gr(e)}function ve(e){if(e===null||e.BS_PRIVATE_NESTED_SOME_NONE===void 0)return e;let t=e.BS_PRIVATE_NESTED_SOME_NONE;if(t!==0)return{BS_PRIVATE_NESTED_SOME_NONE:t-1|0}}function Cr(e){if(e.RE_EXN_ID==="JsExn")return gr(e._1)}var za=(e=>t=>t&&typeof t[e]=="string"?t[e]:void 0),jM=za("stack"),Rr=za("message"),NM=za("name"),MM=za("fileName");function wt(e,t){if(e!==void 0)return gr(t(ve(e)))}function it(e,t){if(e!==void 0)return t(ve(e))}function lt(e,t){return e!==void 0?ve(e):t}var fg=(function(e,t){for(var r in e)t(r)});function Ot(e,t){if(e===t)return!0;let r=typeof e;if(r==="string"||r==="number"||r==="bigint"||r==="boolean"||r==="undefined"||e===null)return!1;let n=typeof t;if(r==="function"||n==="function")throw{RE_EXN_ID:"Invalid_argument",_1:"equal: functional value",Error:new Error};if(n==="number"||n==="bigint"||n==="undefined"||t===null)return!1;let i=e.TAG,o=t.TAG;if(i!==o)return!1;let s=e.length|0,a=t.length|0;if(s===a)if(Array.isArray(e)){let u=0;for(;;){let c=u;if(c===s)return!0;if(!Ot(e[c],t[c]))return!1;u=c+1|0}}else{if(e instanceof Date&&t instanceof Date)return!(e>t||e<t);{let u={contents:!0},c=d=>{if(!Object.prototype.hasOwnProperty.call(t,d)){u.contents=!1;return}},l=d=>{if(!Object.prototype.hasOwnProperty.call(e,d)||!Ot(t[d],e[d])){u.contents=!1;return}};return fg(e,c),u.contents&&fg(t,l),u.contents}}else return!1}import*as pg from"node:child_process";function hS(e){return e==null?!1:typeof e.RE_EXN_ID=="string"}function X(e){return hS(e)?e:{RE_EXN_ID:"JsExn",_1:e}}var lu={};function mg(e){let t=lu[e];if(t!==void 0){let r=t+1|0;return lu[e]=r,e+("/"+r)}return lu[e]=1,e}function Ge(e){let t=Cr(e);if(t===void 0)return{code:void 0,message:"unknown error"};let r=ve(t);return{code:Ji(r.code),message:lt(Rr(r),"unknown error")}}function hg(e,t){return Ot(e.code,t)}function yr(e){try{return{TAG:"Ok",_0:be.readFileSync(e,"utf8")}}catch(t){let r=X(t);return{TAG:"Error",_0:Ge(r)}}}function gg(e,t){try{return{TAG:"Ok",_0:(be.writeFileSync(e,t,"utf8"),void 0)}}catch(r){let n=X(r);return{TAG:"Error",_0:Ge(n)}}}function Xo(e,t,r){try{return{TAG:"Ok",_0:(be.writeFileSync(e,t,r),void 0)}}catch(n){let i=X(n);return{TAG:"Error",_0:Ge(i)}}}function vr(e){try{return{TAG:"Ok",_0:(be.mkdirSync(e,{recursive:!0}),void 0)}}catch(t){let r=X(t);return{TAG:"Error",_0:Ge(r)}}}function Aa(e,t){try{return{TAG:"Ok",_0:(be.chmodSync(e,t),void 0)}}catch(r){let n=X(r);return{TAG:"Error",_0:Ge(n)}}}function _g(e,t){try{return{TAG:"Ok",_0:(be.linkSync(e,t),void 0)}}catch(r){let n=X(r);return{TAG:"Error",_0:Ge(n)}}}function yg(e){try{return{TAG:"Ok",_0:(be.unlinkSync(e),void 0)}}catch(t){let r=X(t);return{TAG:"Error",_0:Ge(r)}}}function Pa(e,t){try{return{TAG:"Ok",_0:(be.renameSync(e,t),void 0)}}catch(r){let n=X(r);return{TAG:"Error",_0:Ge(n)}}}function Qn(e){try{return{TAG:"Ok",_0:(be.rmSync(e,{force:!0}),void 0)}}catch(t){let r=X(t);return{TAG:"Error",_0:Ge(r)}}}function Ca(e){return Oa.createHash("sha256").update(e).digest("hex")}function vg(e){try{return Oa.randomBytes(e).toString("hex")}catch{return""}}function bg(e){try{return{TAG:"Ok",_0:be.readdirSync(e)}}catch(t){let r=X(t);return{TAG:"Error",_0:Ge(r)}}}function wg(e,t,r,n){try{return{TAG:"Ok",_0:pg.execFileSync(e,t,{encoding:"utf8",timeout:r,maxBuffer:n})}}catch(i){let o=X(i);return{TAG:"Error",_0:Ge(o)}}}function Yo(e){try{return process.stderr.write(e)}catch{return!1}}function uu(e,t){return e[t]}function du(e,t){try{return process.kill(e,t),{TAG:"Ok",_0:void 0}}catch(r){let n=X(r);return{TAG:"Error",_0:Ge(n)}}}function Wi(e){try{return gr(new URL(e))}catch{return}}function Xr(e,t){try{return{TAG:"Ok",_0:new URL(e,t)}}catch(r){let n=X(r),i=Cr(n);return{TAG:"Error",_0:i!==void 0?lt(Rr(ve(i)),"unknown error"):"unknown error"}}}var et={};et["api-url"]="ValueKind";et.token="ValueKind";et["auth-file"]="ValueKind";et["delegation-auth-file"]="ValueKind";et.workspace="ValueKind";et.channel="ValueKind";et["owner-username"]="ValueKind";et.mode="ValueKind";et.cwd="ValueKind";et["thread-id"]="ValueKind";et.format="ValueKind";et.command="ValueKind";et["tool-scope"]="ValueKind";et["agent-session"]="BooleanKind";et["ask-user-question-tool"]="BooleanKind";et["multi-agent-jobs"]="BooleanKind";et["include-token"]="BooleanKind";et.help="BooleanKind";function Ra(e){let t={},r,n=0;for(;r===void 0&&n<e.length;){let o=e[n];if(o!==void 0)if(o.startsWith("--")){let s=o.slice(2),a=et[s];if(a!==void 0)if(a==="ValueKind"){let u=e[n+1|0];u!==void 0?u.startsWith("--")?r="--"+s+" requires a value":(t[s]={TAG:"ValueFlag",_0:u},n=n+2|0):r="--"+s+" requires a value"}else t[s]="BoolFlag",n=n+1|0;else r="unsupported option --"+s}else r="unexpected argument "+o;else n=n+1|0}let i=r;return i!==void 0?{TAG:"Error",_0:i}:{TAG:"Ok",_0:t}}function We(e,t){let r=e[t];if(r===void 0||typeof r!="object")return;let n=r._0;if(n.trim()!=="")return n}function Hi(e,t){let r=e[t];return r!==void 0?typeof r!="object":!1}function Ia(e,t){let r=We(e,t);return r!==void 0?{TAG:"Ok",_0:r}:{TAG:"Error",_0:"--"+t+" is required"}}function ja(e){if(e===void 0)return{TAG:"Ok",_0:"Text"};switch(e){case"text":return{TAG:"Ok",_0:"Text"};case"voice":return{TAG:"Ok",_0:"Voice"};default:return{TAG:"Error",_0:"--mode must be voice or text"}}}function fu(e){if(e===void 0)return{TAG:"Ok",_0:"All"};switch(e){case"all":return{TAG:"Ok",_0:"All"};case"coding":return{TAG:"Ok",_0:"Coding"};case"onboarding-discovery":return{TAG:"Ok",_0:"OnboardingDiscovery"};default:return{TAG:"Error",_0:"--tool-scope must be all, coding, or onboarding-discovery"}}}function xg(e){return e[0]==="mcp"?e.slice(1):e}function Na(){return`Linzumi MCP
11
12
 
12
13
  Usage:
13
14
  linzumi mcp server --api-url <url> [--mode voice|text] [--workspace <slug> --channel <slug>]
@@ -101,35 +102,42 @@ Tools:
101
102
  Auth:
102
103
  Uses --token, LINZUMI_MCP_ACCESS_TOKEN, or cached local runner OAuth from linzumi auth.
103
104
  Hosted personal agents use --delegation-auth-file with a signed delegation grant.
104
- `}function Rh(e){throw e}function Ih(e){throw e}function Cl(e){throw e}function je(e){throw new Error(e)}function fn(e){let t=$r(e);if(t===void 0)return"unknown error";let r=de(t);return xt(Tr(r),String(r))}function Kx(e,t){return fetch(e,t)}function Qx(e,t){return fetch(e,t)}var pa={json:Kx,binary:Qx};function jh(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength|0)}function ha(e){return new Promise((t,r)=>{setTimeout(()=>t(),e)})}function Rl(e){process.exitCode=e}function Ln(e){process.stdout.write(e)}function tt(e,t){return e.TAG==="Ok"?{TAG:"Ok",_0:t(e._0)}:e}function Q(e,t){return e.TAG==="Ok"?t(e._0):e}function Ae(e,t){return e.TAG==="Ok"?e:{TAG:"Error",_0:t(e._0)}}function Mh(e,t,r){return e.reduce(r,t)}function Ft(e,t){let r=e.length,n=new Array(r),i=0;for(let o=0;o<r;++o){let s=e[o],a=t(s);a!==void 0&&(n[i]=de(a),i=i+1|0)}return n.length=i,n}var Lh={},za=[],tk=(e=>({...e}));function qi(e){let t=0;for(;;){let r=t,n=e[r];if(n===void 0)return'"'+e+'"';switch(n){case'"':case`
105
- `:return JSON.stringify(e);default:t=r+1|0;continue}}}function rk(e){return e===""?[]:JSON.parse(e.split('"]["').join('","'))}function nk(e){return"["+qi(e)+"]"}function ik(e){let t=e.length;return t!==1?t!==0?e.map(nk).join(""):"":"["+qi(e[0])+"]"}var ql="sury",Ll=Symbol(ql),Vl=Symbol(ql+":item"),Ni="string",hn="number",ok="bigint",sk="boolean",ak="symbol",Mi="null",Pr="undefined",Ml="nan";var Ul="instance",Fn="array",Qe="object",gn="union",Dl="never",Zo="unknown",ck="ref",Fl=xh("Sury.Exn"),Cr="const";function lk(e){return e.type===Pr?!0:e.type===gn?Pr in e.has:!1}function uk(e,t){return(e&t)!==0}var Ze={[Zo]:1,[Ni]:2,[hn]:4,[sk]:8,[Pr]:16,[Mi]:32,[Qe]:64,[Fn]:128,[gn]:256,[ck]:512,[ok]:1024,[Ml]:2048,function:4096,[Ul]:8192,[Dl]:32768,[ak]:16384};function ya(e){let t=Ze[typeof e];if(t&16)return Pr;if(!(t&64))return t&2?'"'+e+'"':t&1024?e+"n":t&4096?"Function":e.toString();if(e===null)return Mi;if(Array.isArray(e)){let i="[";for(let o=0,s=e.length;o<s;++o)o!==0&&(i=i+", "),i=i+ya(e[o]);return i+"]"}if(e.constructor!==Object)return Object.prototype.toString.call(e);let r=Object.keys(e),n="{ ";for(let i=0,o=r.length;i<o;++i){let s=r[i],a=e[s];n=n+s+": "+ya(a)+"; "}return n+"}"}function De(e){let t=e.type,r=e.to,n=e.const,i=e.name;if(i!==void 0)return i;if(n!==void 0)return ya(n);let o=e.format,s=e.anyOf;if(s!==void 0)return s.map(De).join(" | ");if(o!==void 0){if(o!=="compactColumns")return o;let a=e.additionalItems;if(r===void 0)return a!==void 0&&a!=="strip"&&a!=="strict"?De(a)+"[]":"unknown[][]";let l=r.properties;return l===void 0?"unknown[][]":"["+Object.keys(l).map(u=>{let d=l[u];return De(d)+"[]"}).join(", ")+"]"}switch(t){case"nan":return"NaN";case"object":let a=e.additionalItems,l=e.properties,c=Object.keys(l);return c.length===0?typeof a===Qe?"{ [key: string]: "+De(a)+"; }":"{}":"{ "+c.map(u=>u+": "+De(l[u])+";").join(" ")+" }";default:if(e.b)return t;switch(t){case"instance":return e.class.name;case"array":let u=e.additionalItems,d=e.items;if(typeof u!==Qe)return"["+d.map(De).join(", ")+"]";let h=De(u);return(u.type===gn?"("+h+")":h)+"[]";default:return t}}}var Gn=class extends Error{constructor(t){super();for(let r in t)this[r]=t[r]}},mr=Object.defineProperty,qo=Gn.prototype;mr(qo,"message",{get(){return Uh(this)}});mr(qo,"name",{value:"SuryError"});mr(qo,"s",{value:Ll});mr(qo,"_1",{get(){return this}});mr(qo,"RE_EXN_ID",{value:Fl});var Vh=1,Gl=function(){},Bl=Object.create(null);mr(Bl,"with",{get(){return(e,...t)=>e(this,...t)}});Gl.prototype=Bl;function Ea(e){if(e&&e.s===Ll)return e;throw e}function Uh(e){let t=e.path;return(t===""?"":"Failed at "+t+": ")+e.reason}var Co={m:Uh,d:void 0,a:"strip",f:0},mn={};var va="value",Ii="r";function St(e,t){let r=new Gl;return r.type=e,r.seq=Vh++,t&&(mn[va]=r,mr(r,Ii,mn)),r}function Fh(e){return e}var Il={};function Li(e,t,r){if(Il[e])return Il[e];let n=St(t,!0);return r(n),Il[e]=n,n}var Ke=St(Zo,!0);Ke.decoder=Fh;var Di=(e=>{let t=new Gl;for(let r in e)t[r]=e[r];return t.seq=Vh++,t});function _n(e,t){let r=Di(e),n=r;for(;n.to;){let i=Di(n.to);n.to=i,n=i}return t(n),r}function Bn(e,t){let r=e.g.e,n=r.length;return r[n]=t,"e["+n+"]"}function Lo(e,t){let r=Ze[t.type],n=t.const;return r&16?"void 0":r&2?qi(n):r&1024?n+"n":r&28672?Bn(e,t.const):n}function Jn(e,t){let r='"'+t+'"',n=e[r];if(n!==void 0)return n;let i=qi(t);return e[r]=i,i}function Ot(){return this.i}function dk(){return this.b.v()}function fk(){return this.prev.v()}function Qt(e){let t=e.v+1;return e.v=t,"v"+t}function ba(e,t){e.hd=e.hd===""?t:e.hd+","+t}function mk(){let e=this,t=Qt(e.g);return e.cp="let "+t+"="+e.i+";",e.i=t,e.v=Ot,t}function Zl(){let e=this,t=e.p;if(t.fz)return e.v=Ot,e.i;let r=Qt(e.g);return ba(t,r+"="+e.i),e.v=Ot,e.i=r,r}function wa(){let e=this;if(e.fz)return e.v=Ot,e.i="("+e.i+")",e.i;let t=Qt(e.g);if(e.prev!==void 0){let n=e.i;n===""?e.cp="let "+t+";"+e.cp:e.cp=e.cp+("let "+t+"="+n+";")}else{let n=e.i;n===""?ba(e,t):ba(e,t+"="+n)}return e.v=Ot,e.i=t,t}function pk(e,t,r,n){return{v:Ot,i:"i",s:e,e:t,f:0,cp:"",hd:"",path:"",g:{v:-1,o:r,e:[],d:n}}}function Vo(e,t,r){let n=e.path,i="Can't decode "+De(t)+" to "+De(r)+". Use S.to to define a custom decoder",o={code:"unsupported_decode",path:n,reason:i,from:t,to:r};throw new Gn(o)}function Ro(e,t,r){return Bn(e,n=>{let i=t(n);throw new Gn(i)})+"("+r+")"}function Gh(e,t,r,n,i,o,s){let a=s!==void 0?s:"Expected "+De(e)+", received "+(i?ya(n):De(t));if(o!==void 0){let c={};for(let u=0,d=o.length;u<d;++u){let h=o[u],p=h.reason.split(`
105
+ `}function Sg(e){throw e}function Tg(e){throw e}function mu(e){throw e}function Ve(e){throw new Error(e)}function wn(e){let t=Cr(e);if(t===void 0)return"unknown error";let r=ve(t);return lt(Rr(r),String(r))}function gS(e,t){return fetch(e,t)}function _S(e,t){return fetch(e,t)}var Ma={json:gS,binary:_S};function $g(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength|0)}function Da(e){return new Promise((t,r)=>{setTimeout(()=>t(),e)})}function pu(e){process.exitCode=e}function Xn(e){process.stdout.write(e)}function tt(e,t){return e.TAG==="Ok"?{TAG:"Ok",_0:t(e._0)}:e}function Y(e,t){return e.TAG==="Ok"?t(e._0):e}function ke(e,t){return e.TAG==="Ok"?e:{TAG:"Error",_0:t(e._0)}}function zg(e,t,r){return e.reduce(r,t)}function Ht(e,t){let r=e.length,n=new Array(r),i=0;for(let o=0;o<r;++o){let s=e[o],a=t(s);a!==void 0&&(n[i]=ve(a),i=i+1|0)}return n.length=i,n}var Cg={},Ka=[],wS=(e=>({...e}));function ro(e){let t=0;for(;;){let r=t,n=e[r];if(n===void 0)return'"'+e+'"';switch(n){case'"':case`
106
+ `:return JSON.stringify(e);default:t=r+1|0;continue}}}function xS(e){return e===""?[]:JSON.parse(e.split('"]["').join('","'))}function kS(e){return"["+ro(e)+"]"}function SS(e){let t=e.length;return t!==1?t!==0?e.map(kS).join(""):"":"["+ro(e[0])+"]"}var wu="sury",xu=Symbol(wu),ku=Symbol(wu+":item"),Xi="string",Sn="number",TS="bigint",$S="boolean",ES="symbol",Yi="null",Mr="undefined",yu="nan";var Su="instance",ti="array",st="object",Tn="union",vu="never",as="unknown",zS="ref",Tu=mg("Sury.Exn"),Dr="const";function OS(e){return e.type===Mr?!0:e.type===Tn?Mr in e.has:!1}function AS(e,t){return(e&t)!==0}var Ke={[as]:1,[Xi]:2,[Sn]:4,[$S]:8,[Mr]:16,[Yi]:32,[st]:64,[ti]:128,[Tn]:256,[zS]:512,[TS]:1024,[yu]:2048,function:4096,[Su]:8192,[vu]:32768,[ES]:16384};function qa(e){let t=Ke[typeof e];if(t&16)return Mr;if(!(t&64))return t&2?'"'+e+'"':t&1024?e+"n":t&4096?"Function":e.toString();if(e===null)return Yi;if(Array.isArray(e)){let i="[";for(let o=0,s=e.length;o<s;++o)o!==0&&(i=i+", "),i=i+qa(e[o]);return i+"]"}if(e.constructor!==Object)return Object.prototype.toString.call(e);let r=Object.keys(e),n="{ ";for(let i=0,o=r.length;i<o;++i){let s=r[i],a=e[s];n=n+s+": "+qa(a)+"; "}return n+"}"}function He(e){let t=e.type,r=e.to,n=e.const,i=e.name;if(i!==void 0)return i;if(n!==void 0)return qa(n);let o=e.format,s=e.anyOf;if(s!==void 0)return s.map(He).join(" | ");if(o!==void 0){if(o!=="compactColumns")return o;let a=e.additionalItems;if(r===void 0)return a!==void 0&&a!=="strip"&&a!=="strict"?He(a)+"[]":"unknown[][]";let u=r.properties;return u===void 0?"unknown[][]":"["+Object.keys(u).map(l=>{let d=u[l];return He(d)+"[]"}).join(", ")+"]"}switch(t){case"nan":return"NaN";case"object":let a=e.additionalItems,u=e.properties,c=Object.keys(u);return c.length===0?typeof a===st?"{ [key: string]: "+He(a)+"; }":"{}":"{ "+c.map(l=>l+": "+He(u[l])+";").join(" ")+" }";default:if(e.b)return t;switch(t){case"instance":return e.class.name;case"array":let l=e.additionalItems,d=e.items;if(typeof l!==st)return"["+d.map(He).join(", ")+"]";let h=He(l);return(l.type===Tn?"("+h+")":h)+"[]";default:return t}}}var ri=class extends Error{constructor(t){super();for(let r in t)this[r]=t[r]}},br=Object.defineProperty,cs=ri.prototype;br(cs,"message",{get(){return Ig(this)}});br(cs,"name",{value:"SuryError"});br(cs,"s",{value:xu});br(cs,"_1",{get(){return this}});br(cs,"RE_EXN_ID",{value:Tu});var Rg=1,$u=function(){},Eu=Object.create(null);br(Eu,"with",{get(){return(e,...t)=>e(this,...t)}});$u.prototype=Eu;function Qa(e){if(e&&e.s===xu)return e;throw e}function Ig(e){let t=e.path;return(t===""?"":"Failed at "+t+": ")+e.reason}var es={m:Ig,d:void 0,a:"strip",f:0},xn={};var Fa="value",Ki="r";function At(e,t){let r=new $u;return r.type=e,r.seq=Rg++,t&&(xn[Fa]=r,br(r,Ki,xn)),r}function jg(e){return e}var hu={};function no(e,t,r){if(hu[e])return hu[e];let n=At(t,!0);return r(n),hu[e]=n,n}var ot=At(as,!0);ot.decoder=jg;var eo=(e=>{let t=new $u;for(let r in e)t[r]=e[r];return t.seq=Rg++,t});function $n(e,t){let r=eo(e),n=r;for(;n.to;){let i=eo(n.to);n.to=i,n=i}return t(n),r}function ni(e,t){let r=e.g.e,n=r.length;return r[n]=t,"e["+n+"]"}function ls(e,t){let r=Ke[t.type],n=t.const;return r&16?"void 0":r&2?ro(n):r&1024?n+"n":r&28672?ni(e,t.const):n}function ii(e,t){let r='"'+t+'"',n=e[r];if(n!==void 0)return n;let i=ro(t);return e[r]=i,i}function Mt(){return this.i}function PS(){return this.b.v()}function CS(){return this.prev.v()}function rr(e){let t=e.v+1;return e.v=t,"v"+t}function Ua(e,t){e.hd=e.hd===""?t:e.hd+","+t}function RS(){let e=this,t=rr(e.g);return e.cp="let "+t+"="+e.i+";",e.i=t,e.v=Mt,t}function bu(){let e=this,t=e.p;if(t.fz)return e.v=Mt,e.i;let r=rr(e.g);return Ua(t,r+"="+e.i),e.v=Mt,e.i=r,r}function Ga(){let e=this;if(e.fz)return e.v=Mt,e.i="("+e.i+")",e.i;let t=rr(e.g);if(e.prev!==void 0){let n=e.i;n===""?e.cp="let "+t+";"+e.cp:e.cp=e.cp+("let "+t+"="+n+";")}else{let n=e.i;n===""?Ua(e,t):Ua(e,t+"="+n)}return e.v=Mt,e.i=t,t}function IS(e,t,r,n){return{v:Mt,i:"i",s:e,e:t,f:0,cp:"",hd:"",path:"",g:{v:-1,o:r,e:[],d:n}}}function us(e,t,r){let n=e.path,i="Can't decode "+He(t)+" to "+He(r)+". Use S.to to define a custom decoder",o={code:"unsupported_decode",path:n,reason:i,from:t,to:r};throw new ri(o)}function ts(e,t,r){return ni(e,n=>{let i=t(n);throw new ri(i)})+"("+r+")"}function Ng(e,t,r,n,i,o,s){let a=s!==void 0?s:"Expected "+He(e)+", received "+(i?qa(n):He(t));if(o!==void 0){let c={};for(let l=0,d=o.length;l<d;++l){let h=o[l],m=h.reason.split(`
106
107
  `).join(`
107
- `),m=h.path,g=`
108
- - `+(m===""?"":"At "+m+": ")+p;c[g]||(c[g]=1,a=a+g)}}let l={code:"invalid_input",path:r,reason:a,expected:e,received:t,unionErrors:o};return i&&(l.input=n),l}function Jl(e,t,r,n){return i=>{let o=t!==void 0?t:"",s=n!==void 0?n:!0,a=e!==void 0?e:i.e,l=i.prev,c=l!==void 0?l.s:i.s,u=o===""?i.path:i.path+o;return d=>Gh(a,c,u,d,s,void 0,r)}}function rt(e){let t=e.e.errorMessage,r;if(t!==void 0){let n=t.type;r=n!==void 0?n:t._}else r=void 0;return Jl(void 0,void 0,r,void 0)(e)}function hk(e,t){let r=t!==void 0?t:e.e;return Ro(e,Jl(r,void 0,void 0,void 0)(e),e.v())}function gk(e,t){let r=e.vc,n=r.length;if(n===1){let s=r[0];return s.c(t)+"||"+Ro(e,s.f(e),t)+";"}let i="",o=0;for(;o<n;){let s=r[o],a=s.f,l=s.c(t);for(o=o+1|0;o<n&&r[o].f===a;)l=l+"&&"+r[o].c(t),o=o+1|0;i=i+(l+"||"+Ro(e,a(e),t)+";")}return i}function Bh(e){return e.t===!0?e.prev.t!==!0?e.cp==="":!1:!0}function Or(e,t){let r=e,n="";for(;r!==void 0;){let i=r;r=i.prev;let o="";if(i.vc)if(t!==void 0&&Bh(i)){let a=r.v(),l=i.vc,c="";for(let u=0,d=l.length;u<d;++u){let h=l[u],p=h.c(a);h.f===rt?c=c?c+"&&"+p:p:i.e.noValidation!==!0&&(o=o+(p+"||"+Ro(i,h.f(i),a)+";"))}c&&(t.contents?t.contents=c+"&&"+t.contents:t.contents=c)}else i.e.noValidation!==!0&&(o=gk(i,r.v()));i.hd!==""&&(o=o+("let "+i.hd+";")),i.fz=!0,o=i.cp+o,n=o+n}return n}function Rr(e,t,r,n){let i=n!==void 0?n:e.e;return{v:wa,i:t,s:r,e:i,prev:e,f:0,d:e.d,cp:"",hd:"",t:!0,path:e.path,g:e.g}}function Oe(e,t,r,n){let i=t!==void 0?t:e.s,o=n!==void 0?n:e.e,s=e.v!==Ot,a={v:s?fk:Ot,i:e.i,s:i,e:o,prev:e,f:e.f,d:e.d,cp:"",hd:"",vc:r,t:e.t,path:e.path,g:e.g};if(s){let l=e.v.bind(e);e.v=()=>{let c=l();return a.i=c,a.v=Ot,c}}return a}function Wl(e,t){let r=e.vc;r!==void 0?r.push(t):e.vc=[t]}function Io(e,t){let r=t.e.inputRefiner,n;if(r!==void 0){let a=r(t);if(a.length!==0)if(t.prev!==void 0){for(let c=0,u=a.length;c<u;++c)Wl(t,a[c]);n=void 0}else n=a;else n=void 0}else n=void 0;let i=e.e.refiner,o;if(i!==void 0){let a=i(e);o=a.length!==0?a:void 0}else o=void 0;let s=n!==void 0?o!==void 0?Oe(e,void 0,n.concat(o),void 0):Oe(e,void 0,n,void 0):o!==void 0?Oe(e,void 0,o,void 0):e;return s.io=!0,s}function Jh(e,t,r){if(!t.vc)return;let i="["+Jn(e.g,r)+"]";t.vc.forEach(o=>Wl(e,{c:s=>o.c(s+i),f:o.f})),t.vc=void 0}function Wh(e,t){let r=e.s.additionalItems,n;n=r!==void 0&&r!=="strip"&&r!=="strict"?r:Ke;let i=e.e.additionalItems,o;return o=i!==void 0&&i!=="strip"&&i!=="strict"?i:Ke,{p:e,v:mk,i:e.v()+"["+t+"]",s:n,e:o,f:e.f,cp:"",hd:"",path:"",g:e.g}}function Un(e,t,r){return Rr(e,Lo(e,t),t,r)}function Hh(e,t){let r=Rr(e,t,e.s,void 0);return r.f=1,r}function pn(e,t,r){e.s.type===Fn?e.s.items.push(r.s):(r.o||e.s.required.push(t),e.s.properties[t]=r.s),r.f&1&&r.v(),e.cp=e.cp+Or(r,void 0),e.d[t]=r}function Kh(e,t,r){return e.v()+"["+t+"]="+r.i}function Wr(e){let t=e.v!==Ot,r={b:e,v:t?dk:Ot,i:e.i,s:e.s,io:e.io,e:e.e,f:0,d:e.d,cp:"",hd:"",u:!1,t:!1,path:e.path,g:e.g};if(t){let n=e.v.bind(e);e.v=()=>{let i=n();return r.i=i,r.v=Ot,i}}return r}function _k(e,t){throw new Gn({code:"invalid_operation",path:e.path,reason:t})}function Qh(e,t,r,n){if(e.path===""&&r===void 0)return Or(e,void 0);{let i=l=>{let c=t.path,u=c===""?"":qi(c)+"+";return l+".path="+u+(r!==void 0?`'["'+`+r+`+'"]'+`:"")+l+".path"},o=Or(e,void 0);if(o===""&&!(e.f&1))return o+(n!==void 0?n():"");let s=Qt(e.g),a=i(s)+";throw "+s;return e.f&1&&(e.i=e.i+".catch("+s+"=>{"+a+"})"),"try{"+o+(n!==void 0?n():"")+"}catch("+s+"){"+a+"}"}}function Xh(e){return e}Xh.embedded=za;function jl(e){return e+"<=2147483647&&"+e+">=-2147483648&&"+e+"%1===0"}function jo(e){return t=>"typeof "+t+'==="'+e+'"'}function ji(e){return"Number.isNaN("+e+")"}function xa(e){return"Array.isArray("+e+")"}function Yh(e){return jo(Qe)(e)+"&&"+e}function yk(e,t){return r=>r+" instanceof "+Bn(e,t)}function vk(e){let t=Ze[e.s.type];if(t&1){let i=[{c:jo(hn),f:rt}],o=e.e.format,s=0;return o==="int32"?i.push({c:jl,f:rt}):s=1,s===1&&(e.g.o&2||i.push({c:a=>"!"+ji(a),f:rt})),Oe(e,e.e,i,void 0)}if(!(t&2))return t&4?e.s.format!==e.e.format&&e.e.format==="int32"?Oe(e,e.e,[{c:jl,f:rt}],void 0):e:Vo(e,e.s,e.e);let r=Qt(e.g),n=Rr(e,r,e.e,void 0);return n.v=Ot,n.cp="let "+r+"=+"+e.v()+";",n.vc=[{c:i=>{let o=e.e.format;return o!==void 0&&o==="int32"?jl(r):"!"+ji(r)},f:rt}],n}function eg(){return Li(hn,hn,e=>{e.decoder=vk})}function bk(e){return Rr(e,'""+'+e.i,Hl(),void 0)}function wk(e){let t=Ze[e.s.type];if(t&1)return Oe(e,e.e,[{c:jo(Ni),f:rt}],void 0);if(!(t&3132&&Cr in e.s))return t&1036?bk(e):t&2?e:Vo(e,e.s,e.e);let r=""+e.s.const,n=St(Ni,!1);return n.const=r,Rr(e,'"'+r+'"',n,void 0)}function Hl(){return Li(Ni,Ni,e=>{e.decoder=wk})}function tg(e,t){e[Ze[t]&768?Zo:t]=!0}var xk="JSON";function Zi(e){let t=e.e;if(t.noValidation&&!e.u)return Un(e,t,void 0);if(Cr in e.s)return e.s.const===t.const?e:Un(e,t,void 0);let r=Ze[t.type];if(!(Ze[e.s.type]&2&&r&3132))return r&2048?Oe(e,t,[{c:ji,f:rt}],void 0):Oe(e,t,[{c:o=>o+"==="+Lo(e,t),f:rt}],void 0);let n=St(Ni,!1);n.const=""+t.const;let i=Un(e,n,n);return i.vc=[{c:o=>o+'==="'+n.const+'"',f:rt}],Un(i,t,t)}function Aa(){return Li(Pr,Pr,e=>{e.const=void 0,e.decoder=Zi})}function kk(){return Li(Mi,Mi,e=>{e.const=null,e.decoder=Zi})}function rg(){return Li(Ml,Ml,e=>{e.const=NaN,e.decoder=Zi})}function Kl(e){if(e===null)return kk();let t=typeof e;if(t===Pr)return Aa();if(t===hn&&Number.isNaN(e))return rg();if(t===Qe){let n=St(Ul,!0);return n.class=e.constructor,n.const=e,n.decoder=Zi,n}let r=St(t,!0);return r.const=e,r.decoder=Zi,r}function Xt(e){let t=e,r,n=0;for(;!t.io||t.e.to;){let i=r;r=void 0;let o=t;if(n=n+1|0,n>50)throw new Error("Loop count exceeded 100");if(o.e.$defs&&(o.g.d?Object.assign(o.g.d,o.e.$defs):o.g.d=o.e.$defs),o.f&1){let s=o.v(),a=Wr(o),l=Xt(a),c=Or(l,void 0);t=a.i!==l.i||c!==""?Rr(o,s+".then("+s+"=>{"+c+"return "+l.i+"})",l.s,l.e):Oe(o,l.s,void 0,l.e),t.f=t.f|1,t.io=!0}else if(o.io){let s=o.e.to,l=o.e.parser;t=l!==void 0?l(o):Oe(t,void 0,void 0,s)}else{let s=o.s.encoder;s&&s!==i&&o.s!==o.e&&o.e.type!==Zo&&(t=s(o,o.e)),o!==t?r=s:(t=o.e.decoder(o),t.io||(t=Io(t,t)))}}return t}function yn(e){for(;;){let t=e,r=t.to;if(r===void 0)return t;e=r}}function Jr(e){if(Ii in e)return e[Ii];let t,r=e;for(;r;){let i=Di(r),o=i.to,s=t;s!==void 0?i.to=s:delete i.to;let a=i.parser,l=i.serializer;l!==void 0?i.parser=l:delete i.parser,a!==void 0?i.serializer=a:delete i.serializer;let c=i.refiner,u=i.inputRefiner;u!==void 0?i.refiner=u:delete i.refiner,c!==void 0?i.inputRefiner=c:delete i.inputRefiner;let d=i.fromDefault,h=i.default;h!==void 0?i.fromDefault=h:delete i.fromDefault,d!==void 0?i.default=d:delete i.default;let p=i.items;p!==void 0&&(i.items=p.map(Jr));let m=i.properties;if(m!==void 0){let y={},v=Object.keys(m);for(let b=0,w=v.length;b<w;++b){let S=v[b];y[S]=Jr(m[S])}i.properties=y}typeof i.additionalItems===Qe&&(i.additionalItems=Jr(i.additionalItems));let f=i.anyOf;if(f!==void 0){let y={},v=[];for(let b=0,w=f.length;b<w;++b){let S=f[b],Z=Jr(S);v.push(Z),tg(y,Z.type)}i.has=y,i.anyOf=v}let g=i.$defs;if(g!==void 0){let y={};for(let v=0,b=Object.keys(g).length;v<b;++v){let w=Object.keys(g)[v];y[w]=Jr(g[w])}i.$defs=y}t=i,r=o}let n=t;return mn[va]=n,mr(e,Ii,mn),mn[va]=e,mr(n,Ii,mn),n}function ng(e){try{return Xt(e)}catch(t){let r=Ea(t),n=e.p;throw r.path=(n!==void 0?n.path:"")+(e.path+"[]"+r.path),r}}function Sk(e,t,r,n){let i=pk(Cr in e?Ke:e,t,r,n),o=Xt(i),s=Or(o,void 0),a=uk(o.f,1);t.isAsync=a;let l=o.t===!0;if(t.hasTransform=l,s===""&&(o===i||o.i===i.i)&&!(r&1))return Xh;let c=o.i;r&1&&!a&&!n&&(c="Promise.resolve("+c+")");let u="i=>{"+s+"return "+c+"}",d=i.g.e,h=new Function("e","s","return "+u)(d,Ll);return h.embedded=i.g.e,h}function ka(e,t){let r=arguments,n=0,i,o="",s=0,a;for(;i===void 0;){let c=r[n];if(c)if(typeof c===hn){let u=c|Co.f;i=u,o=o+"-"+u}else{let u=c.seq;u>s&&(s=u,a=c),o=o+u+"-",n=n+1|0}else{let u=Co.f;i=u,o=o+"-"+u}}let l=a;if(l!==void 0){let c=o;if(c in l)return l[c];let u=r[n-1|0];for(let h=n-2|0;h>=0;--h){let p=u;u=_n(r[h],m=>{m.to=p})}let d=Sk(u,u,i,0);return mn[va]=d,mr(l,c,mn),d}throw new Error("[Sury] No schema provided for decoder.")}var Wn="BS_PRIVATE_NESTED_SOME_NONE";function $k(e){let t=Oe(e,void 0,void 0,Ql());return t.cp=hk(e,void 0)+";",t}function Ql(){return Li(Dl,Dl,e=>{e.decoder=$k})}function Tk(e){let t=e.e.to;return Rr(e,"{"+Wn+":"+yn(e.e).properties[Wn].const+"}",t,t)}function No(e,t){return{v:wa,i:"",s:t.type===Fn?{type:Fn,decoder:Yl,additionalItems:"strict",items:[]}:{type:Qe,decoder:Uo,additionalItems:"strict",required:[],properties:{}},e:e.e,prev:e,f:0,d:{},cp:"",hd:"",t:!0,path:e.path,g:e.g}}function Xl(e){return tu(e,Aa())}function Uo(e){let t=e.u,r=e.e,n=Ze[e.s.type],i;if(n&65){let u=n&64,d;if(u)d=e.s;else{let p=St(Qe,!1);p.properties=Lh,p.additionalItems=Ke,d=p}let h=[];u||(h.push({c:Yh,f:rt}),r.additionalItems!=="strip"&&h.push({c:p=>"!"+xa(p),f:rt})),i=h.length!==0?Oe(e,d,h,void 0):Oe(e,d,void 0,void 0)}else i=Vo(e,e.s,r);let o=r.additionalItems,s;s=o==="strip"||o==="strict"?void 0:o;let a=i.s.additionalItems,l;l=a!=="strip"&&a!=="strict";let c;if(s!==void 0)if(s===Ke)c=i;else if(l){let u=i.v(),d=Qt(i.g),h=Wh(i,d),p=ng(h),m=p.t,f=m?Rr(i,"{}",r,void 0):Oe(i,r,void 0,void 0),g=Qh(p,i,d,m?()=>Kh(f,d,p):void 0);if((m||g!=="")&&(f.cp=f.cp+("for(let "+d+" in "+u+"){"+g+"}")),p.f&1){let y=Qt(f.g),v=Qt(f.g),b=Qt(f.g),w=Qt(f.g),S=f.v();c=Hh(f,"new Promise(("+y+","+v+")=>{let "+w+"=Object.keys("+S+").length;for(let "+d+" in "+S+"){"+S+"["+d+"].then("+b+"=>{"+S+"["+d+"]="+b+";if("+w+"--===1){"+y+"("+S+")}},"+v+")}})")}else c=f}else{let u=No(i,r),d=Object.keys(i.s.properties);for(let h=0,p=d.length;h<p;++h){let m=d[h],f=Sa(i,m);f.e=s,f.io=!1,f.u=t,pn(u,m,Xt(f))}c=Mo(u)}else{let u=r.properties,d=Object.keys(u),h=d.length,p=No(i,r),m=r.additionalItems,f;f=m==="strip"||m==="strict"?m==="strip"?l||Object.keys(i.s.properties).length!==h:!1:!0;let g=i.s.additionalItems,y;y=g==="strip"||g==="strict"?!1:g.name===xk;for(let b=0;b<h;++b){let w=d[b],S=u[w],Z=Sa(i,w);Z.e=S,Z.io=!1,Z.u=t,y&&S.type===gn&&S.has[Pr]&&(Z.i="("+Z.i+"??null)");let F=Xt(Z);t&&Cr in S&&Jh(i,F,w),pn(p,w,F),f||(f=F.t)}let v=!1;if(r.additionalItems==="strict"){let b=i.s.additionalItems,w;w=b!=="strip"&&b!=="strict",v=w}if(v){let b=Qt(p.g);if(ba(i,b),p.cp=p.cp+("for("+b+" in "+i.v()+"){if("),d.length!==0)for(let w=0,S=d.length;w<S;++w){let Z=d[w];w!==0&&(p.cp=p.cp+"&&"),p.cp=p.cp+(b+"!=="+Jn(i.g,Z))}else p.cp=p.cp+"true";p.cp=p.cp+("){"+Ro(i,w=>({code:"unrecognized_keys",path:p.path,reason:'Unrecognized key "'+w+'"',keys:[w]}),b)+"}}")}if(f)c=Mo(p);else{let b=Oe(i,void 0,void 0,void 0);b.cp=p.cp,b.d=p.d,c=b}}return Io(c,i)}function zk(){let e=Kl(0),t={};return t[Wn]=e,{type:Qe,serializer:r=>{let n=r.e.to;return Un(r,n,n)},decoder:Uo,additionalItems:"strip",required:[Wn],properties:t}}function Yl(e){let t=e.u,r=e.e,n=Ze[e.s.type],i=r.items,o=i.length,s;if(n&129){let u=n&128,d=u?e.s:eu(Ke),h=[];u||h.push({c:xa,f:rt});let p=d.additionalItems,m;if(m=p==="strip"||p==="strict"?d.items.length===o:!1,!m){let f=r.additionalItems;(f==="strip"||f==="strict")&&(f==="strip"?h.push({c:g=>g+".length>="+o,f:rt}):h.push({c:g=>g+".length==="+o,f:rt}))}s=h.length!==0?Oe(e,d,h,void 0):Oe(e,d,void 0,void 0)}else s=Vo(e,e.s,r);let a=r.additionalItems,l,c=0;if(a==="strip"||a==="strict")c=1;else if(a===Ke)l=s;else{let u=s.v(),d=Qt(s.g),h=Wh(s,d),p=ng(h),m=p.t,f=m?Rr(s,"new Array("+u+".length)",r,void 0):Oe(s,r,void 0,void 0),g=Qh(p,s,d,m?()=>Kh(f,d,p):void 0);(m||g!=="")&&(f.cp=f.cp+("for(let "+d+"="+o+";"+d+"<"+u+".length;++"+d+"){"+g+"}")),l=p.f&1?Hh(f,"Promise.all("+f.i+")"):f}if(c===1){let u=No(s,r),d=r.additionalItems,h;if(d==="strip"||d==="strict")if(d==="strip"){let p=s.s.additionalItems;h=p==="strip"||p==="strict"?s.s.items.length!==o:!0}else h=!1;else h=!0;for(let p=0;p<o;++p){let m=i[p],f=p.toString(),g=Sa(s,f);g.e=m,g.io=!1,g.u=t;let y=Xt(g);t&&Cr in m&&Jh(s,y,f),pn(u,f,y),h||(h=y.t)}if(h)l=Mo(u);else{let p=Oe(s,void 0,void 0,void 0);p.cp=u.cp,p.d=u.d,l=p}}return Io(l,s)}function Ek(e,t){let r=e.s.anyOf;return t.type===gn&&og(t)===void 0&&ig(t.anyOf,r)||!Pk(r,t)?e:Ok(e,t)}function Ak(e){let t=e.e,r=t.anyOf,n=Ze[e.s.type],i=og(t);if(e.s===t&&i===void 0&&r.every(ga)||n&256&&ig(r,e.s.anyOf)&&i===void 0||e.io&&e.e===e.s)return e;(n&256||e.s.encoder===void 0&&n&512)&&(e.s=Ke);let o="";if(!(n&769)){let R=Nl(e.s),D=!1,ve=!1,pe=r.length,B=0;for(;o===""&&B<pe;){let he=r[B];Nl(he)===R?o=R:he.type===Mi?D=!0:he.type===Pr&&(ve=!0),B=B+1|0}o===""&&(n&16&&D?o=Mi:n&32&&ve&&(o=Pr))}let s=o,a=e.i,l=R=>Bn(e,function(){let D=arguments,ve=Gh(t,Ke,e.path,D[0],!0,D.length>1?Array.from(D).slice(1):void 0,void 0);throw new Gn(ve)})+"("+e.v()+R+")",c=Oe(e,void 0,void 0,void 0),u=[],d={contents:""},h=(R,D)=>{let ve=R[0],pe=R[1],B="",he="",ge=!1,Ve={contents:""},et="",Kt={},wt=2,_e=R.length-1|0;for(;wt<=_e;){let Ue=Wr(pe);Ue.u=!0,Ue.t=pe.t,Ue.io=!1,Ue.e=R[wt];let We=wt===_e,Lt=wt===2,Zn=Lt&&We,Ai=!Zn,kr=!1,Gr="",un={contents:""};try{let Se=Xt(Ue);if(u.push(Se.s),Gr=Or(Se,un),Se.t){c.t=!0,Se.f&1&&(c.f=c.f|1);let Sr=ve.v();Se.i!==Sr&&(Gr=Gr+(Sr+"="+Se.i))}}catch(Se){let Sr=Bn(Ue,Ea(Se));et=et+","+Sr,D&&Zn?(d.contents=Sr,kr=!0):We?(Ai=!1,Gr=D?"throw "+Sr:l(et)):kr=!0}let dn=un.contents,qn=Gr;if(!kr&&dn)if(qn){let Se=Kt[dn];Se!==void 0?typeof Se=="string"?Kt[dn]=[Se,qn]:Se.push(qn):Kt[dn]=qn}else Ve.contents=Ve.contents?Ve.contents+"||"+dn:dn;if(!kr&&(!dn||We)){let Se=Object.keys(Kt);for(let Sr=0,Nx=Se.length;Sr<Nx;++Sr){let _h=Se[Sr];B=B+(ge?"else if":"if")+("("+_h+"){");let zo=Kt[_h];if(typeof zo=="string")B=B+zo+"}";else{let $l="";for(let ia=0,Mx=zo.length;ia<Mx;++ia){let Dx=zo[ia],yh="e"+ia;B=B+("try{"+Dx+"}catch("+yh+"){"),$l=$l+","+yh}B=B+l($l)+"}".repeat(zo.length)+"}"}ge=!0}Kt={}}if(!kr&&!dn)if(qn)if(Ve.contents&&(B=B+(ge?"else if":"if")+("(!("+Ve.contents+")){"),he="}"+he,Ve.contents="",ge=!1),We&&(D||!Ai||Lt))B=B+((ge?"else{":"")+qn),he=(ge?"}":"")+he;else{let Se="e"+(wt-2|0);B=B+((ge?"else{":"")+"try{"+qn+"}catch("+Se+"){"),he=(ge?"}":"")+"}"+he,et=et+","+Se,ge=!1}else Ve.contents="",wt=_e,Ai=!1;if(We){if(Ve.contents)B||et?B=B+(ge?"else if":"if")+("(!("+Ve.contents+")){"+l(et)+"}"):Wl(pe,{c:Se=>"("+Ve.contents+")",f:rt});else if(Ai){let Se=l(et);B=B+(ge?"else{"+Se+"}":Se)}}wt=wt+1}return B+he},p="",m="",f="",g=!1,y=r.length-1|0,v={},b=[],w=t.refiner,S=t.inputRefiner,Z={contents:void 0},F={contents:void 0},ce=(R,D,ve)=>{if(D===void 0)return R;let pe=B=>{let he=ve.contents;if(he!==void 0)return he;let ge=D(B);return ve.contents=ge,ge};return R!==void 0?B=>{let he=R(B),ge=pe(B);for(let Ve=0,et=ge.length;Ve<et;++Ve)he.push(ge[Ve]);return he}:pe},Je=R=>{let D=ce(R.refiner,w,Z);D!==void 0&&(R.refiner=D);let ve=ce(R.inputRefiner,S,F);if(ve!==void 0){R.inputRefiner=ve;return}},Ee;if(Cr in e.s){let R=[],D=[];for(let ve=0;ve<=y;++ve){let pe=r[ve];Cr in pe&&pe.const===e.s.const?R.push(pe):D.push(pe)}Ee=R.concat(D)}else Ee=r;for(let R=0;R<=y;++R){let D=i!==void 0?_n(Ee[R],he=>{Je(he),he.to=i}):Ee[R],ve=D.type,pe=Ze[ve],B=Nl(D);if((s===""||s===B)&&!(pe&16&&"fromDefault"in t)){let he=v[B];if(he!==void 0)pe&64&&Wn in D.properties?he.splice(he.length-1|0,0,D):pe&2096||he.push(D);else{let ge=Wr(e),Ve;if(pe&37633)Ve=Ke;else{let _e=St(D.type,!1);_e.encoder=D.encoder,pe&8192?_e.class=D.class:pe&64?(_e.properties=Lh,_e.additionalItems=Ke):pe&128?(_e.additionalItems=Ke,_e.items=za):pe&2096&&(_e.const=D.const),_e.decoder=Ue=>Ze[Ue.s.type]&1?Oe(Ue,Ue.e,[{c:We=>{let Lt=Ze[D.type];if(Lt&64)return Yh(We)+"&&!"+xa(We);if(Lt&128)return xa(We);if(Lt&8192)return yk(Ue,D.class)(We);if(!(Lt&4))return Lt&2048?ji(We):Lt&48?We+"==="+Lo(Ue,D):Lt&17418?jo(D.type)(We):"";let Zn=jo(hn)(We);return Ue.g.o&2?Zn:Zn+"&&!"+ji(We)},f:rt}],void 0):D.decoder(Ue),Ve=_e}ge.e=Ve;let et;try{et=Xt(ge)}catch{ge.vc=void 0,et=ge}Dh(pe,v)?b.unshift(B):b.push(B),v[B]=[ge,et,D];let Kt=!0,wt=et;for(;wt!==void 0&&Kt;){let _e=wt;wt=_e.prev,Kt=!(_e.vc&&Bh(_e))}if(Kt){for(let _e=0,Ue=b.length;_e<Ue;++_e){let We=b[_e];if(!g){let Lt=v[We],Zn=Lt[1],Ai=h(Lt,!0),kr=Or(Zn,void 0)+Ai,Gr=d.contents;if(Gr)if(d.contents="",kr){let un="e"+(R+_e|0);p=p+("try{"+kr+"throw "+Gr+"}catch("+un+"){"),m="}"+m,f=f+","+un}else f=f+","+Gr;else if(kr){let un="e"+(R+_e|0);p=p+("try{"+kr+"}catch("+un+"){"),m="}"+m,f=f+","+un}else g=!0}}v={},b=[]}}}}let bt=v,ut=b;if(!g){let R=!1,D="";for(let B=0,he=ut.length;B<he;++B){let ge=bt[ut[B]],Ve=ge[1],et=ge[2],Kt=h(ge,!1),wt={contents:""},_e=Or(Ve,wt)+Kt,Ue=wt.contents;_e||Dh(Ze[et.type],bt)?(p=p+(R?"else if":"if")+("("+Ue+"){"+_e+"}"),R=!0):D=D?D+"||"+Ue:Ue}let ve=l(f),pe;D?pe=(R?"else if":"if")+("(!("+D+")){"+ve+"}"):pe=R?"else{"+ve+"}":m===""?ve+";":ve,p=p+pe}c.cp=c.cp+p+m,e.i!==c.i&&(c.i=e.i);let Ye=c.f&1?(c.i="Promise.resolve("+c.i+")",c.v=wa,c):c.v===Ot&&e.cp===""&&c.cp===""&&a==="i"?(e.hd="",e.v=wa,e.i=a,e):c;return Ye.s=u.length?Do(u):Ql(),Ye.e=i!==void 0?(Ye.io=!0,yn(i)):t,Ye}function ig(e,t){return t.every((r,n)=>{let i=e[n];return i!==void 0&&!(Ze[r.type]&9152)&&r.type===i.type&&r.const===i.const?r.to===void 0:!1})}function Ok(e,t){return Oe(e,Ke,void 0,_n(e.s,r=>{r.to=t}))}function Pk(e,t){return!(Ze[yn(t).type]&512)&&!(t.type===gn&&t.anyOf.some(r=>Ze[r.type]&512))?!e.some(r=>r.to!==void 0||r.parser!==void 0?!0:Ze[r.type]&512):!1}function og(e){if(e.parser!==void 0)return;let r=e.to;if(r!==void 0)return r}function Sa(e,t){let r=e.d,n;if(r!==void 0)n=r;else{let u={};e.d=u,n=u}let i=n[t];if(i!==void 0)return Wr(i);let o=e.s.type===Qe?e.s.properties[t]:e.s.items[t],s;if(o!==void 0)s=o;else{let u=e.s.additionalItems;s=u==="strip"||u==="strict"?Vo(e,e.s,e.e):e.s.type===Qe&&u.type!==Zo&&!(Ze[u.type]&512)&&!lk(u)?Xl(u):u}let l="["+Jn(e.g,t)+"]",c={p:e,v:Zl,i:Cr in s?Lo(e,s):e.v()+l,s,e:s,f:0,cp:"",hd:"",path:e.path+l,g:e.g};return n[t]=c,c}function Mo(e){let t=e.s.type===Fn,r="",n="",i,o=Object.keys(e.d);for(let c=0,u=o.length;c<u;++c){let d=o[c],h=e.d[d];if(h.f&1&&(n=n+h.i+","),h.o){let p=i;i=m=>(p!==void 0?p(m):"")+("if("+h.v()+"!==void 0){"+m+"["+Jn(e.g,d)+"]="+h.i+"}")}else r=r+(t?h.i:Jn(e.g,d)+":"+h.i)+","}if(e.i=t?"["+r+"]":"{"+r+"}",n){let c=Wr(e);c.io=!0;let u=Xt(c),d=Or(u,void 0);return d===""&&n===u.i+","?e.i=u.i:e.i="Promise.all(["+n+"]).then((["+n+"])=>{"+d+"return "+u.i+"})",e.f=e.f|1,e.s=u.s,e.e=u.e,e.io=!0,e}let s=i;if(s===void 0)return e;let a=s(e.v()),l=Oe(e,void 0,void 0,void 0);return l.cp=l.cp+a,l}function Do(e){let t=e.length;if(t===1)return e[0];if(t!==0){let r={},n=new Set;for(let o=0,s=e.length;o<s;++o){let a=e[o];a.type===gn&&a.to===void 0?(a.anyOf.forEach(l=>{n.add(l)}),Object.assign(r,a.has)):(n.add(a),tg(r,a.type))}let i=St(gn,!1);return i.anyOf=Array.from(n),i.decoder=Ak,i.encoder=Ek,i.has=r,i}throw new Error("[Sury] S.union requires at least one item")}function Dh(e,t){return e&8320&&Qe in t?!0:e&2048?hn in t:!1}function Nl(e){return Ze[e.type]&8192?e.class.name:e.type}function ga(e){for(;;){let t=e,r=!1,n=!1,i=!1;if(t.to===void 0&&t.parser===void 0&&!(Ze[t.type]&512)){let s=t.anyOf;i=s!==void 0?s.every(ga):!0}if(i){let s=t.items;n=s!==void 0?s.every(ga):!0}if(n){let s=t.properties;r=s!==void 0?Object.values(s).every(ga):!0}if(!r)return!1;let o=t.additionalItems;if(o===void 0||o==="strip"||o==="strict")return!0;e=o}}function eu(e){let t=St(Fn,e[Ii]===e);return t.additionalItems=e,t.items=za,t.decoder=Yl,t}function tu(e,t){let r=t!==void 0?t:Aa(),n=yn(e);switch(n.type){case"undefined":return Do([r,Zh(e)]);case"union":let o=n.has,s=n.anyOf;return _n(e,a=>{let l=tk(o),c=[];for(let u=0,d=s.length;u<d;++u){let h=s[u],p=yn(h),m=p.type,f;if(m==="undefined")l[r.type]=!0,c.push(r),f=Zh(h);else{let g=p.properties;if(g!==void 0){let y=g[Wn];f=y!==void 0?_n(h,v=>{let b={},w={...y};w.const=y.const+1,b[Wn]=w,v.properties=b}):h}else f=h}c.push(f)}c.length===s.length&&(l[r.type]=!0,c.push(r)),a.anyOf=c,a.has=l});default:return Do([e,r])}}function Zh(e){return _n(e,t=>{t.to=zk(),t.parser=Tk})}mr(Bl,"~standard",{get:function(){let e=this;return{version:1,vendor:ql,validate:t=>{try{return{value:ka(Ke,e)(t)}}catch(r){let n=Ea(r);return{issues:[{message:n.reason,path:n.path===""?void 0:rk(n.path)}]}}}}}});function sg(e,t){return ka(Ke,t)(e)}function Ck(e,t){return _n(e,r=>{let n=t(r),i=r.refiner;i!==void 0?r.refiner=o=>{let s=i(o),a=n(o);for(let l=0,c=a.length;l<c;++l)s.push(a[l]);return s}:r.refiner=n})}function ag(e,t,r,n){let i=r!==void 0?r:"Refinement failed",o=n!==void 0?ik(n):"";return Ck(e,s=>(a=>{let l=Bn(a,t);return[{c:c=>l+"("+c+")",f:Jl(void 0,o,i,void 0)}]}))}function cg(e,t){return _n(e,r=>{let n=r.anyOf;if(n!==void 0){let o=[],s=[];for(let h=0,p=n.length;h<p;++h){let m=n[h],f=yn(m);f.type!=="undefined"&&(o.push(f),s.push(m))}let a=o.length,l;if(a!==1)if(a!==0)l=Do(o);else{let h="Can't set default for "+De(r);throw new Error("[Sury] "+h)}else l=o[0];let c=s.length!==1?Do(s):s[0];if(t.TAG==="Value"){let h=t._0;try{ka(Ke,l)(h)}catch(p){let m=Ea(p),f="Invalid default for "+De(r)+": "+m.message;throw new Error("[Sury] "+f)}try{r.default=ka(Jr(c),void 0)(h)}catch{}}r.parser=h=>{let p=h.e.to,m=h.v(),f;return f=t.TAG==="Value"?Lo(h,Kl(t._0)):Bn(h,t._0)+"()",Rr(h,m+"===void 0?"+f+":"+m,p,p)};let u=Di(l),d=u.decoder;u.serializer=h=>{let p=Jr(c);return Oe(d(h),p,void 0,p)},u.decoder=Fh,r.to=u;return}let i="Can't set default for "+De(r);throw new Error("[Sury] "+i)})}function Rk(e){return e[Vl]}function $a(e,t,r){let n=Di(yn(e));return n.from=t,r!==void 0&&(n.fromFlattened=r),new Proxy(n,{get:(i,o)=>{if(o===Vl)return i;let s=i.items,a=i.properties,l=a!==void 0?a[o]:s!==void 0?s[o]:void 0;if(l===void 0){let c='Cannot read property "'+o+'" of '+De(i);throw new Error("[Sury] "+c)}return $a(l,i.from.concat(o),i.fromFlattened)}})}function lg(e,t,r){let n=No(e,t);n.io=!0;let i=t.items;if(i!==void 0)for(let o=0,s=i.length;o<s;++o){let a=o.toString();pn(n,a,r(a,i[o]))}else{let o=t.properties;if(o!==void 0){let s=Object.keys(o);for(let a=0,l=s.length;a<l;++a){let c=s[a];pn(n,c,r(c,o[c]))}}else{let s="Don't know where the value is coming from: "+De(t);throw new Error("[Sury] "+s)}}return Mo(n)}function ug(e,t){let r=t.from,n=t.fromFlattened,i=n!==void 0?Wr(qh(e.fv[n],t.from,0)):r!==void 0?Wr(qh(e,r,0)):Cr in t?Un(e,t,void 0):lg(e,t,(o,s)=>ug(e,s));return i.prev=void 0,i.e=t,i}function dg(e,t){let r=t.e,n=r.from;if(n!==void 0){let s=r.fromFlattened,a;if(s!==void 0){e.flattened===void 0&&(e.flattened=[]);let l=e.flattened[s];if(l!==void 0)a=l;else{let c={};e.flattened[s]=c,a=c}}else a=e;for(let l=0,c=n.length;l<c;++l){let u=n[l],d=a.properties,h;if(d!==void 0)h=d;else{let f={};a.properties=f,h=f}let p=h[u],m;if(p!==void 0)m=p;else{let f={};h[u]=f,m=f}a=m}a.val=t;return}let i=t.d;if(i===void 0)return;let o=Object.keys(i);for(let s=0,a=o.length;s<a;++s)dg(e,i[o[s]])}function _a(e,t,r,n){let i=0;if(t!==void 0){let o=t.val;if(o!==void 0){let s=Wr(o);return s.t=!0,s.s=r,s.e=r,Xt(s)}i=1}else i=1;if(i===1){if(Cr in r){let d=Un(e,r,r);return d.prev=void 0,d.p=e,d.v=Zl,d.io=!0,Xt(d)}let o=t===void 0?yn(r):r,s=No(e,o);s.e=o,s.io=!0,s.prev=void 0,s.p=e,s.v=Zl;let a=o.flattened,l=o.items,c=0,u=0;if(l!==void 0&&(t!==void 0||typeof o.additionalItems!==Qe))for(let d=0,h=l.length;d<h;++d){let p=d.toString(),m;if(t!==void 0){let g=t.properties;m=g!==void 0?g[p]:void 0}else m=void 0;let f=Jn(e.g,p);pn(s,p,_a(e,m,l[d],n+("["+f+"]")))}else u=3;if(u===3){let d=o.properties;if(d!==void 0&&(t!==void 0||typeof o.additionalItems!==Qe)){if(a!==void 0&&t!==void 0){let p=t.flattened;p!==void 0&&p.forEach((m,f)=>{let y=_a(e,m,Jr(a[f]),n).d,v=Object.keys(y);for(let b=0,w=v.length;b<w;++b){let S=v[b];pn(s,S,y[S])}})}let h=Object.keys(d);for(let p=0,m=h.length;p<m;++p){let f=h[p];if(!(f in s.d)){let g;if(t!==void 0){let v=t.properties;g=v!==void 0?v[f]:void 0}else g=void 0;let y=Jn(e.g,f);pn(s,f,_a(e,g,d[f],n+("["+y+"]")))}}}else c=2}if(c===2){let d=r.from,h=d!==void 0?n+d.map(m=>'["'+m+'"]').join(""):n,p=h===""?"":" at "+h;_k(e,"Missing input for "+De(r)+p)}return Mo(s)}}function qh(e,t,r){for(;;){let n=r,i=e,o=t[n];if(o===void 0)return i;r=n+1|0,e=i.d[o]}}function Ta(e,t){if(typeof e!==Qe||e===null)return Kl(e);let r=t(e);if(r!==void 0)return r;if(Array.isArray(e)){for(let l=0,c=e.length;l<c;++l){let u=Ta(e[l],t);e[l]=u}let a=St(Fn,!1);return a.items=e,a.additionalItems="strict",a.decoder=Yl,a}let n=e.constructor;if(n&&n!==Object){let a=St(Ul,!0);return a.class=n,a.const=e,a.decoder=Zi,a}let i=Object.keys(e),o=i.length;for(let a=0;a<o;++a){let l=i[a],c=Ta(e[l],t);e[l]=c}let s=St(Qe,!1);return s.required=i,s.properties=e,s.additionalItems=Co.a,s.decoder=Uo,s}function Ik(e){let t={};dg(t,e);let r=e.e.to,n=_a(e,t,r,"");return n.t=!0,n.prev=e,n}function fg(e){return Ta(e,t=>{if(t["~standard"])return t})}function mg(e){let t=this,r="~"+e,n=t[r];if(n!==void 0)return de(n);let i={},o=[],s=St(Qe,!1);s.required=o,s.properties=i,s.additionalItems=Co.a,s.decoder=Uo;let a=t.f(e,s)[Vl],l=(p,m)=>{let f=qi(p);if(p in i)throw new Error("[Sury] "+("The field "+f+" defined twice"));return o.push(p),i[p]=m,$a(m,a.from.concat(p),a.fromFlattened)},h={field:l,f:l,fieldOr:(p,m,f)=>{let g=tu(m,void 0);return l(p,cg(g,{TAG:"Value",_0:f}))},tag:(p,m)=>{l(p,fg(m))},nested:mg,flatten:p=>{if(p.type==="object"){let g=p.to,y=p.properties;if(g){let w="Unsupported nested flatten for transformed object schema "+De(p);throw new Error("[Sury] "+w)}let v=Object.keys(y),b={};for(let w=0,S=v.length;w<S;++w){let Z=v[w];b[Z]=l(Z,y[Z])}return b}let f="Can't flatten "+De(p)+" schema";throw new Error("[Sury] "+f)}};return t[r]=h,h}function jk(e){let t=Di(Ta(e,Rk));return t.serializer=Ik,t}function Nk(e){let t=e.e.flattened;if(t!==void 0){let i=[];for(let o=0,s=t.length;o<s;++o){let a=t[o],l=a.to,c;if(l!==void 0){let u=Wr(e);u.e=a,u.io=!0,c=Xt(u)}else{let u=lg(e,a,(d,h)=>Sa(e,d));u.e=a,u.prev=void 0,c=Io(u,u)}i.push(c),e.cp=e.cp+Or(c,void 0)}e.fv=i}let r=e.e.to,n=ug(e,r);return n.t=!0,n.prev=e,Io(n,e)}function pg(e){let t,r={},n=u=>{if(u.type==="object"){let p=u.properties,m=Object.keys(p);for(let g=0,y=m.length;g<y;++g){let v=m[g],b=p[v],w=r[v];if(w!==void 0){if(w!==b)throw new Error("[Sury] "+('The field "'+v+'" defined twice with incompatible schemas'))}else r[v]=b}let f=t||(t=[]);return $a(u,za,f.push(u)-1|0)}let h="The '"+De(u)+"' schema can't be flattened";throw new Error("[Sury] "+h)},i=(u,d)=>{if(u in r)throw new Error("[Sury] "+('The field "'+u+'" defined twice with incompatible schemas'));return r[u]=d,$a(d,[u],void 0)},l=e({field:i,f:i,fieldOr:(u,d,h)=>{let p=tu(d,void 0);return i(u,cg(p,{TAG:"Value",_0:h}))},tag:(u,d)=>{i(u,fg(d))},nested:mg,flatten:n}),c=St(Qe,!1);return c.required=Object.keys(r),c.properties=r,c.additionalItems=Co.a,c.decoder=Uo,c.parser=Nk,c.to=jk(l),t!==void 0&&(c.flattened=t),c}var vn=Hl();var hg=eg();var gg=Fl;var _g=eu;var Fo=Xl;var Hr=ag;var yg=sg;var Oa=pg;function Dk(e){return{path:e.path,summary:e.message}}function N(e){return{path:"",summary:e}}function ru(e,t){try{return{TAG:"Ok",_0:yg(e,t)}}catch(r){let n=ee(r);if(n.RE_EXN_ID===gg)return{TAG:"Error",_0:Dk(n._1)};throw n}}import*as Go from"node:fs";import*as Sg from"node:os";import*as Pa from"node:path";var Zk="--api-url must be ws://, wss://, http://, or https://";function $t(e){let t=Ci(e);if(t===void 0)return{TAG:"Error",_0:"invalid URL: "+e};let r=de(t),n=r.protocol,i;switch(n){case"http:":case"https:":i={TAG:"Ok",_0:void 0};break;case"ws:":r.protocol="http:",i={TAG:"Ok",_0:void 0};break;case"wss:":r.protocol="https:",i={TAG:"Ok",_0:void 0};break;default:i={TAG:"Error",_0:Zk}}return tt(i,()=>{r.pathname="",r.search="",r.hash="";let o=r.toString();return o.endsWith("/")?o.slice(0,o.length-1|0):o})}var bg="wss://serve.linzumi.com";function Bo(){return Pa.join(Sg.homedir(),".linzumi","auth.json")}var wg="Kandan auth cache must contain a JSON object",qk="Kandan auth cache local_codex_runner must be an object",Lk="Kandan auth cache personal_agent_delegation must be an object";function xg(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.access_token,r=e.issued_at;if(t===void 0||typeof t!="string"||r===void 0||typeof r!="string")return;let n=e.expires_at,i;return i=typeof n=="string"?n:void 0,{accessToken:t,issuedAt:r,expiresAt:i}}function $g(e){let t;try{t=JSON.parse(e)}catch{t=void 0}if(t===void 0)return{TAG:"Error",_0:N(wg)};if(typeof t!="object"||t===null||Array.isArray(t))return{TAG:"Error",_0:N(wg)};let r=t.local_codex_runner,n=t.personal_agent_delegation,i=r!==void 0?typeof r=="object"&&r!==null&&!Array.isArray(r):!0,o=n!==void 0?typeof n=="object"&&n!==null&&!Array.isArray(n):!0;if(!i)return{TAG:"Error",_0:N(qk)};if(!o)return{TAG:"Error",_0:N(Lk)};let s;return s=typeof r=="object"&&r!==null&&!Array.isArray(r)?Object.fromEntries(Ft(Object.entries(r),a=>{let l=a[0];return ft(xg(a[1]),c=>[l,c])})):void 0,{TAG:"Ok",_0:{serverTokens:s,personalAgentDelegation:He(n,xg)}}}function Tg(e){return Go.existsSync(e)?Q(Ae(fr(e),t=>N(t.message)),t=>tt($g(t),r=>r)):{TAG:"Ok",_0:void 0}}function zg(e,t){return e!==void 0?new Date(e).getTime()<=t:!1}function Ca(e,t,r){return Go.existsSync(t)?Q(Tg(t),n=>tt(Ae($t(e),N),i=>He(He(He(n,o=>o.serverTokens),o=>o[i]),o=>{if(!(o.accessToken.trim()===""||zg(o.expiresAt,r)))return{accessToken:o.accessToken,serverBaseUrl:i,issuedAt:o.issuedAt,expiresAt:o.expiresAt}}))):{TAG:"Ok",_0:void 0}}function Vk(e){return"missing personal-agent delegation auth file: "+e}var Uk="personal-agent delegation auth file is missing access_token",Fk="personal-agent delegation auth file token is expired";function Eg(e,t){return Go.existsSync(e)?Q(Tg(e),r=>{let n=He(r,i=>i.personalAgentDelegation);return n!==void 0&&n.accessToken.trim()!==""?zg(n.expiresAt,t)?{TAG:"Error",_0:N(Fk)}:{TAG:"Ok",_0:n}:{TAG:"Error",_0:N(Uk)}}):{TAG:"Error",_0:N(Vk(e))}}function kg(e){let t={};t.access_token=e.accessToken,t.issued_at=e.issuedAt;let r=e.expiresAt;return r!==void 0&&(t.expires_at=r),t}function Gk(e){let t={};t.version=1;let r=e.serverTokens;r!==void 0&&(t.local_codex_runner=Object.fromEntries(Object.entries(r).map(i=>[i[0],kg(i[1])])));let n=e.personalAgentDelegation;return n!==void 0&&(t.personal_agent_delegation=kg(n)),t}function nu(e,t,r,n,i){return Q(Ae($t(e),N),o=>{let s=Go.existsSync(n)?Q(Ae(fr(n),a=>N(a.message)),$g):{TAG:"Ok",_0:{serverTokens:void 0,personalAgentDelegation:void 0}};return Q(s,a=>{let l=i.toISOString(),c=ft(r,y=>new Date(i.getTime()+y*1e3).toISOString()),u={accessToken:t,issuedAt:l,expiresAt:c},d=a.serverTokens,h=d!==void 0?Object.fromEntries(Object.entries(d)):{};h[o]=u;let p=Gk({serverTokens:h,personalAgentDelegation:a.personalAgentDelegation}),m=JSON.stringify(p,void 0,2)+`
109
- `,f=n+".tmp."+process.pid.toString()+"."+Eh(6),g=y=>N(y.message);return Q(Ae(zr(Pa.dirname(n)),g),()=>{let y=Q(Oo(f,m,{encoding:"utf8",mode:384}),()=>ca(f,n));return y.TAG==="Ok"?{TAG:"Ok",_0:{accessToken:t,serverBaseUrl:o,issuedAt:l,expiresAt:c}}:(Pi(f),{TAG:"Error",_0:N(y._0.message)})})})})}function ou(e){let t=$r(e);return t!==void 0?xt(Tr(de(t)),"unknown error"):"unknown error"}async function Jo(e,t){try{return{TAG:"Ok",_0:await fetch(e,t)}}catch(r){let n=ee(r);return{TAG:"Error",_0:{message:ou(n)}}}}async function Bk(e){try{return{TAG:"Ok",_0:await e.text()}}catch(t){let r=ee(t);return{TAG:"Error",_0:{message:ou(r)}}}}async function Wo(e){let t=await Bk(e);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};try{return{TAG:"Ok",_0:JSON.parse(t._0)}}catch(r){let n=ee(r);return{TAG:"Error",_0:{message:ou(n)}}}}function Jk(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}async function Vi(e,t,r,n,i){let o=i!==void 0?i:[],s=Ae($t(e),N);if(s.TAG!=="Ok")return{TAG:"Error",_0:s._0};let a=Br("/api/v2/local-codex-runner/oauth/validate",s._0);if(a.TAG!=="Ok")return{TAG:"Error",_0:N(a._0)};let l=a._0,c=l.searchParams;r!==void 0&&c.set("workspace",r),n!==void 0&&c.set("channel",n),o.forEach(m=>{c.append("required_scope",m)});let u={};u.authorization="Bearer "+t;let d=await Jo(l.toString(),{method:"GET",headers:u});if(d.TAG!=="Ok")return{TAG:"Error",_0:N(d._0.message)};let h=d._0,p=h.status;if(p>404||p<401){if(p===200){let m=await Wo(h);return m.TAG!=="Ok"?{TAG:"Error",_0:N(m._0.message)}:He(Jk(m._0),g=>g.ok)===!0?{TAG:"Ok",_0:"Usable"}:{TAG:"Ok",_0:"Rejected"}}}else{if(p<402)return{TAG:"Ok",_0:"Rejected"};switch(p){case 402:break;case 403:return{TAG:"Ok",_0:"Rejected"};case 404:return{TAG:"Ok",_0:"NotFound"}}}return{TAG:"Error",_0:N("local runner auth validation failed with HTTP "+p.toString())}}import*as Kg from"node:os";import*as ja from"node:fs";import*as du from"node:os";import*as pt from"node:path";import*as fu from"node:crypto";function au(e){return isFinite(e)?Math.trunc(e)===e:!1}var Wk=new RegExp("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$","i"),Hk=new RegExp("^[a-zA-Z0-9_.-]+$");function cu(e){return Wk.test(e)}function Ia(e){return Hk.test(e)}var Kk=Hr(vn,e=>e.trim()!=="","allowedCwds entries must be non-empty strings",void 0);function Rg(e){return{version:1,machineId:e.f("machineId",Fo(Hr(vn,cu,"invalid machine id",void 0))),runnerId:e.f("runnerId",Fo(Hr(vn,Ia,"invalid runner id",void 0))),allowedCwds:e.f("allowedCwds",_g(Kk))}}var Qk=Oa(Rg),Xk=Oa(e=>(e.tag("version",1),Rg(e)));function lu(e){let t=new Set;return Ft(e,r=>{let n=r.trim();if(!(n===""||t.has(n)))return t.add(n),n})}function Ig(e){return{version:e.version,machineId:e.machineId,runnerId:e.runnerId,allowedCwds:lu(e.allowedCwds)}}function uu(e){return tt(ru(e,Xk),Ig)}function jg(e){return tt(ru(e,Qk),Ig)}var Ra=Fo(Hr(vn,e=>e.trim()!=="","must be a non-empty string",void 0)),Pg=Fo(Hr(hg,e=>au(e)?e>0:!1,"must be a positive integer",void 0));function Yk(e){return!Number.isNaN(new Date(e).getTime())}var Cg=Hr(vn,Yk,"must be a parseable date",void 0),yM=Oa(e=>({email:e.f("email",Hr(vn,t=>t.trim()!=="","must be a non-empty string",void 0)),serviceUrl:e.f("service_url",Hr(vn,t=>t.trim()!=="","must be a non-empty string",void 0)),accessToken:e.f("access_token",Ra),refreshToken:e.f("refresh_token",Ra),expiresInSeconds:e.f("expires_in_seconds",Pg),userId:e.f("user_id",Pg),workspaceSlug:e.f("workspace_slug",Ra),launchUrl:e.f("launch_url",Ra),createdAt:e.f("created_at",Cg),updatedAt:e.f("updated_at",Cg)}));var Ir="prod";function Ng(e){let t=e!==void 0?e:process.env,r=Al(t,"HOME");return r!==void 0&&r.trim()!==""?r:du.homedir()}function tS(e,t){let r=e!==void 0?e:process.env;return t==="~"?Ng(r):t.startsWith("~/")?pt.resolve(Ng(r),t.slice(2)):t}function Zg(e){let t=Al(e,"LINZUMI_CONFIG_FILE");return t!==void 0&&t.trim()!==""?pt.resolve(tS(e,t)):pt.resolve(du.homedir(),".linzumi","config.json")}function Ho(e){let t=$t(e),r=$t(bg);if(t.TAG!=="Ok")return{TAG:"Error",_0:N(t._0)};let n=t._0;return r.TAG==="Ok"?{TAG:"Ok",_0:n===r._0?Ir:n}:{TAG:"Error",_0:N(r._0)}}function rS(e){return tt(Ho(e),t=>t===Ir?Ir:Buffer.from(t).toString("base64url"))}function nS(e,t,r){let n=pt.dirname(e),i=pt.basename(e);return t!==void 0?Q(Ho(t),o=>o===Ir?{TAG:"Ok",_0:pt.join(n,i+"."+r)}:tt(rS(t),s=>pt.join(n,i+"."+s+"."+r))):{TAG:"Ok",_0:pt.join(n,i+"."+r)}}function qg(e){if(ja.existsSync(e))return Q(Ae(fr(e),r=>N(r.message)),r=>{let n;try{n=JSON.parse(r)}catch{n=void 0}return typeof n=="object"&&n!==null&&!Array.isArray(n)?uu(n).TAG==="Ok"?{TAG:"Ok",_0:n}:{TAG:"Error",_0:N("invalid Linzumi config: "+e)}:{TAG:"Error",_0:N("invalid Linzumi config: "+e)}});let t={};return t.version=1,t.allowedCwds=[],{TAG:"Ok",_0:t}}function iS(){let e={};return e.allowedCwds=[],e}function Mg(e,t){return Q(qg(e),r=>{let n=t!==void 0?Ho(t):{TAG:"Ok",_0:Ir};return Q(n,i=>{let o=i===Ir?r:xt(r[i],iS()),s=i===Ir?uu(o):jg(o);return Ae(s,a=>N("invalid Linzumi config section "+i+": "+e))})})}function oS(e,t){let r=i=>N(i.message),n=ja.existsSync(e)?Ae(aa(e,384),r):{TAG:"Ok",_0:void 0};return Q(Q(n,()=>Ae(Oo(e,JSON.stringify(t,void 0,2)+`
110
- `,{encoding:"utf8",mode:384}),r)),()=>Ae(aa(e,384),r))}function sS(e){let t={},r=e.machineId;r!==void 0&&(t.machineId=r);let n=e.runnerId;return n!==void 0&&(t.runnerId=n),t.allowedCwds=lu(e.allowedCwds).map(i=>i),t}function aS(e){let t=e.version===1,r=e.machineId,n=r!==void 0?cu(r):!0,i=e.runnerId,o=i!==void 0?Ia(i):!0,s=e.allowedCwds.every(a=>a.trim()!=="");return t&&n&&o&&s?{TAG:"Ok",_0:void 0}:{TAG:"Error",_0:N("invalid Linzumi config")}}function cS(e,t,r){return Q(aS(e),()=>{let n=r!==void 0?Ho(r):{TAG:"Ok",_0:Ir};return Q(n,i=>Q(qg(t),o=>{let s=Object.fromEntries(Object.entries(o)),a=sS(e);return i===Ir?(Object.entries(a).forEach(l=>{s[l[0]]=l[1]}),s.version=1):(s.version=1,s[i]=a),Q(Ae(zr(pt.dirname(t)),l=>N(l.message)),()=>oS(t,s))}))})}function Dg(e,t,r){return Q(Ae(fr(e),n=>N(n.message)),n=>{let i=n.trim();return t(i)?{TAG:"Ok",_0:i}:{TAG:"Error",_0:N("invalid Linzumi "+r+" seed: "+e)}})}function lS(e,t,r,n){if(ja.existsSync(e))return Dg(e,r,n);let i=t();if(!r(i))return{TAG:"Error",_0:N("invalid generated Linzumi "+n+": "+i)};let o=pt.dirname(e),s=pt.basename(e),a=pt.join(o,"."+s+"."+process.pid.toString()+"."+fu.randomUUID()+".tmp"),l=c=>N(c.message);return Q(Q(Ae(zr(o),l),()=>Ae(Oo(a,i+`
111
- `,{encoding:"utf8",flag:"wx"}),l)),()=>{let c=Th(a,e),u;if(c.TAG==="Ok")u={TAG:"Ok",_0:i};else{let d=c._0;u=Sh(d,"EEXIST")?Dg(e,r,n):{TAG:"Error",_0:N(d.message)}}return zh(a),u})}function uS(){return"runner-"+fu.randomUUID()}function dS(e,t,r,n,i,o,s,a){let l=t!==void 0?tt(Ho(t),c=>{if(c!==Ir)return t}):{TAG:"Ok",_0:void 0};return Q(l,c=>Q(Mg(e,c),u=>{let d=s(u);return d!==void 0?{TAG:"Ok",_0:d}:Q(nS(e,c,r),h=>Q(lS(h,n,i,o),p=>Q(Mg(e,c),m=>{let f=s(m);return f!==void 0?{TAG:"Ok",_0:f}:tt(cS(a(m,p),e,c),()=>p)})))}))}function Lg(e,t,r){return dS(e,t,"runner-id",r!==void 0?r:uS,Ia,"runner id",i=>i.runnerId,(i,o)=>({version:i.version,machineId:i.machineId,runnerId:o,allowedCwds:i.allowedCwds}))}function Vg(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.error;if(typeof t=="string")return t}function Ug(e,t){if(e===void 0)return t!==void 0?"local runner device authorization failed (HTTP "+t.toString()+", no reason returned by the server)":"local runner device authorization failed (no reason returned by the server)";switch(e){case"access_denied":return"local runner device authorization was denied";case"approving_user_not_found":return"local runner device authorization failed: the approving Linzumi account could not be found";case"device_session_consumed":return"local runner device authorization was already used";case"device_session_expired":return"local runner device authorization expired";case"device_session_not_pending":return"local runner device authorization was already decided (approved or denied) on the server";case"invalid_device_code":return"local runner device authorization code was rejected";case"invalid_user_code":return"local runner device authorization code was not recognized by the server";case"rate_limited":return"local runner device authorization was rate limited by the server; wait a minute and retry";default:return"local runner device authorization failed (server said: "+e+")"}}function Ui(e,t){let r=e[t];if(r!==void 0&&typeof r=="string"&&r.trim()!=="")return r}async function Fg(e,t,r,n,i){let o=Br("/api/v2/local-codex-runner/device/start",e);if(o.TAG!=="Ok")return{TAG:"Error",_0:N(o._0)};let s={},a=(g,y)=>{if(y!==void 0){s[g]=y;return}};a("workspace",t),a("channel",r),a("onboarding",n),i!==void 0&&(a("runner_id",i.commanderId),a("machine_fingerprint",i.machineFingerprint),a("hostname",i.hostname));let l={};l["content-type"]="application/json";let c=await Jo(o._0.toString(),{method:"POST",headers:l,body:JSON.stringify(s)});if(c.TAG!=="Ok")return{TAG:"Error",_0:N(c._0.message)};let u=c._0,d=u.status,h=await Wo(u);if(h.TAG!=="Ok")return{TAG:"Error",_0:N(h._0.message)};let p=h._0;if(d>=200&&d<300){if(Array.isArray(p))return{TAG:"Error",_0:N("local runner device authorization response was incomplete")};if(p!==null)switch(typeof p){case"object":let g=Ui(p,"device_code"),y=Ui(p,"user_code"),v=Ui(p,"verification_uri");if(g===void 0)return{TAG:"Error",_0:N("local runner device authorization response was incomplete")};if(y===void 0)return{TAG:"Error",_0:N("local runner device authorization response was incomplete")};if(v===void 0)return{TAG:"Error",_0:N("local runner device authorization response was incomplete")};let b=p.expires_in,w;return w=typeof b=="number"?b:void 0,{TAG:"Ok",_0:{deviceCode:g,userCode:y,verificationUri:v,expiresInSeconds:w}}}}let f=Vg(p);return{TAG:"Error",_0:N(f!==void 0?"local runner device authorization failed to start (server said: "+f+")":"local runner device authorization failed to start (HTTP "+d.toString()+")")}}async function mS(e,t,r){let n=new AbortController,i=setTimeout(()=>{n.abort()},r+1e4|0),o={};o.device_code=t,o.wait_ms=r;let s={};s["content-type"]="application/json";let a=Br("/api/v2/local-codex-runner/device/token",e),l;if(l=a.TAG==="Ok"?await Jo(a._0.toString(),{method:"POST",headers:s,body:JSON.stringify(o),signal:ur(n.signal)}):{TAG:"Error",_0:{message:a._0}},l.TAG==="Ok"){let c=l._0,u=c.status,d=await Wo(c);if(clearTimeout(i),d.TAG!=="Ok")return n.signal.aborted?"Continue":{TAG:"Done",_0:{TAG:"Transient",reason:"non-JSON device/token response ("+d._0.message+")",httpStatus:u}};let h=d._0,p=u>=200&&u<300,m=Vg(h),f=0;if(u!==202||m===void 0)f=1;else{if(m==="authorization_pending")return"Continue";f=1}if(f===1){let g=0;if(p){if(Array.isArray(h))return{TAG:"Done",_0:{TAG:"Rejected",reason:"device token response did not include access_token",httpStatus:u}};if(h===null)g=2;else switch(typeof h){case"object":let y=Ui(h,"access_token");if(y===void 0)return{TAG:"Done",_0:{TAG:"Rejected",reason:"device token response did not include access_token",httpStatus:u}};let v=h.expires_in,b;return b=typeof v=="number"?v:void 0,{TAG:"Done",_0:{TAG:"Token",_0:{accessToken:y,expiresInSeconds:b,workspaceSlug:Ui(h,"workspace"),channelSlug:Ui(h,"channel")}}};default:g=2}}else g=2;if(g===2){let y=0;if(m!==void 0)switch(m){case"access_denied":return{TAG:"Done",_0:"Denied"};case"device_session_consumed":return{TAG:"Done",_0:"Consumed"};case"device_session_expired":return{TAG:"Done",_0:"CodeExpired"};default:y=3}else y=3;if(y===3)return u>=500||u===429?{TAG:"Done",_0:{TAG:"Transient",reason:m!==void 0?m:"HTTP "+u.toString(),httpStatus:u}}:{TAG:"Done",_0:{TAG:"Rejected",reason:m,httpStatus:u}}}}}else return clearTimeout(i),n.signal.aborted?"Continue":{TAG:"Done",_0:{TAG:"Transient",reason:l._0.message,httpStatus:void 0}}}async function Gg(e,t,r,n){let i=n!==void 0?n:()=>Date.now(),o=r!==void 0&&r>=0?r:600,s=i()+o*1e3,a=async()=>{if(i()>=s)return"CodeExpired";let l=Math.max(0,Math.min(3e4,s-i())),c=await mS(e,t,l);return typeof c!="object"?await a():c._0};return await a()}var hS=3600*1e3;function gS(e,t,r,n){return e<=3?"DecidePrompt":r!==void 0&&t-r<hS?n?"DecideRefreshLine":"DecideSilent":"DecideSummary"}function Bg(e){let t=Math.floor(e/6e4),r=Math.floor(t/60),n=t-r*60;return r>0?r.toString()+"h "+n.toString()+"m":n.toString()+"m"}function _S(e){switch(e.TAG){case"Prompt":return(e.cycle===1?"":`The previous code expired; here is a fresh one (no restart needed - this prompt stays alive).
108
+ `),p=h.path,g=`
109
+ - `+(p===""?"":"At "+p+": ")+m;c[g]||(c[g]=1,a=a+g)}}let u={code:"invalid_input",path:r,reason:a,expected:e,received:t,unionErrors:o};return i&&(u.input=n),u}function zu(e,t,r,n){return i=>{let o=t!==void 0?t:"",s=n!==void 0?n:!0,a=e!==void 0?e:i.e,u=i.prev,c=u!==void 0?u.s:i.s,l=o===""?i.path:i.path+o;return d=>Ng(a,c,l,d,s,void 0,r)}}function ut(e){let t=e.e.errorMessage,r;if(t!==void 0){let n=t.type;r=n!==void 0?n:t._}else r=void 0;return zu(void 0,void 0,r,void 0)(e)}function jS(e,t){let r=t!==void 0?t:e.e;return ts(e,zu(r,void 0,void 0,void 0)(e),e.v())}function NS(e,t){let r=e.vc,n=r.length;if(n===1){let s=r[0];return s.c(t)+"||"+ts(e,s.f(e),t)+";"}let i="",o=0;for(;o<n;){let s=r[o],a=s.f,u=s.c(t);for(o=o+1|0;o<n&&r[o].f===a;)u=u+"&&"+r[o].c(t),o=o+1|0;i=i+(u+"||"+ts(e,a(e),t)+";")}return i}function Mg(e){return e.t===!0?e.prev.t!==!0?e.cp==="":!1:!0}function Nr(e,t){let r=e,n="";for(;r!==void 0;){let i=r;r=i.prev;let o="";if(i.vc)if(t!==void 0&&Mg(i)){let a=r.v(),u=i.vc,c="";for(let l=0,d=u.length;l<d;++l){let h=u[l],m=h.c(a);h.f===ut?c=c?c+"&&"+m:m:i.e.noValidation!==!0&&(o=o+(m+"||"+ts(i,h.f(i),a)+";"))}c&&(t.contents?t.contents=c+"&&"+t.contents:t.contents=c)}else i.e.noValidation!==!0&&(o=NS(i,r.v()));i.hd!==""&&(o=o+("let "+i.hd+";")),i.fz=!0,o=i.cp+o,n=o+n}return n}function Zr(e,t,r,n){let i=n!==void 0?n:e.e;return{v:Ga,i:t,s:r,e:i,prev:e,f:0,d:e.d,cp:"",hd:"",t:!0,path:e.path,g:e.g}}function je(e,t,r,n){let i=t!==void 0?t:e.s,o=n!==void 0?n:e.e,s=e.v!==Mt,a={v:s?CS:Mt,i:e.i,s:i,e:o,prev:e,f:e.f,d:e.d,cp:"",hd:"",vc:r,t:e.t,path:e.path,g:e.g};if(s){let u=e.v.bind(e);e.v=()=>{let c=u();return a.i=c,a.v=Mt,c}}return a}function Ou(e,t){let r=e.vc;r!==void 0?r.push(t):e.vc=[t]}function rs(e,t){let r=t.e.inputRefiner,n;if(r!==void 0){let a=r(t);if(a.length!==0)if(t.prev!==void 0){for(let c=0,l=a.length;c<l;++c)Ou(t,a[c]);n=void 0}else n=a;else n=void 0}else n=void 0;let i=e.e.refiner,o;if(i!==void 0){let a=i(e);o=a.length!==0?a:void 0}else o=void 0;let s=n!==void 0?o!==void 0?je(e,void 0,n.concat(o),void 0):je(e,void 0,n,void 0):o!==void 0?je(e,void 0,o,void 0):e;return s.io=!0,s}function Dg(e,t,r){if(!t.vc)return;let i="["+ii(e.g,r)+"]";t.vc.forEach(o=>Ou(e,{c:s=>o.c(s+i),f:o.f})),t.vc=void 0}function Zg(e,t){let r=e.s.additionalItems,n;n=r!==void 0&&r!=="strip"&&r!=="strict"?r:ot;let i=e.e.additionalItems,o;return o=i!==void 0&&i!=="strip"&&i!=="strict"?i:ot,{p:e,v:RS,i:e.v()+"["+t+"]",s:n,e:o,f:e.f,cp:"",hd:"",path:"",g:e.g}}function ei(e,t,r){return Zr(e,ls(e,t),t,r)}function Lg(e,t){let r=Zr(e,t,e.s,void 0);return r.f=1,r}function kn(e,t,r){e.s.type===ti?e.s.items.push(r.s):(r.o||e.s.required.push(t),e.s.properties[t]=r.s),r.f&1&&r.v(),e.cp=e.cp+Nr(r,void 0),e.d[t]=r}function qg(e,t,r){return e.v()+"["+t+"]="+r.i}function en(e){let t=e.v!==Mt,r={b:e,v:t?PS:Mt,i:e.i,s:e.s,io:e.io,e:e.e,f:0,d:e.d,cp:"",hd:"",u:!1,t:!1,path:e.path,g:e.g};if(t){let n=e.v.bind(e);e.v=()=>{let i=n();return r.i=i,r.v=Mt,i}}return r}function MS(e,t){throw new ri({code:"invalid_operation",path:e.path,reason:t})}function Fg(e,t,r,n){if(e.path===""&&r===void 0)return Nr(e,void 0);{let i=u=>{let c=t.path,l=c===""?"":ro(c)+"+";return u+".path="+l+(r!==void 0?`'["'+`+r+`+'"]'+`:"")+u+".path"},o=Nr(e,void 0);if(o===""&&!(e.f&1))return o+(n!==void 0?n():"");let s=rr(e.g),a=i(s)+";throw "+s;return e.f&1&&(e.i=e.i+".catch("+s+"=>{"+a+"})"),"try{"+o+(n!==void 0?n():"")+"}catch("+s+"){"+a+"}"}}function Ug(e){return e}Ug.embedded=Ka;function gu(e){return e+"<=2147483647&&"+e+">=-2147483648&&"+e+"%1===0"}function ns(e){return t=>"typeof "+t+'==="'+e+'"'}function Qi(e){return"Number.isNaN("+e+")"}function Va(e){return"Array.isArray("+e+")"}function Gg(e){return ns(st)(e)+"&&"+e}function DS(e,t){return r=>r+" instanceof "+ni(e,t)}function ZS(e){let t=Ke[e.s.type];if(t&1){let i=[{c:ns(Sn),f:ut}],o=e.e.format,s=0;return o==="int32"?i.push({c:gu,f:ut}):s=1,s===1&&(e.g.o&2||i.push({c:a=>"!"+Qi(a),f:ut})),je(e,e.e,i,void 0)}if(!(t&2))return t&4?e.s.format!==e.e.format&&e.e.format==="int32"?je(e,e.e,[{c:gu,f:ut}],void 0):e:us(e,e.s,e.e);let r=rr(e.g),n=Zr(e,r,e.e,void 0);return n.v=Mt,n.cp="let "+r+"=+"+e.v()+";",n.vc=[{c:i=>{let o=e.e.format;return o!==void 0&&o==="int32"?gu(r):"!"+Qi(r)},f:ut}],n}function Vg(){return no(Sn,Sn,e=>{e.decoder=ZS})}function LS(e){return Zr(e,'""+'+e.i,Au(),void 0)}function qS(e){let t=Ke[e.s.type];if(t&1)return je(e,e.e,[{c:ns(Xi),f:ut}],void 0);if(!(t&3132&&Dr in e.s))return t&1036?LS(e):t&2?e:us(e,e.s,e.e);let r=""+e.s.const,n=At(Xi,!1);return n.const=r,Zr(e,'"'+r+'"',n,void 0)}function Au(){return no(Xi,Xi,e=>{e.decoder=qS})}function Bg(e,t){e[Ke[t]&768?as:t]=!0}var FS="JSON";function to(e){let t=e.e;if(t.noValidation&&!e.u)return ei(e,t,void 0);if(Dr in e.s)return e.s.const===t.const?e:ei(e,t,void 0);let r=Ke[t.type];if(!(Ke[e.s.type]&2&&r&3132))return r&2048?je(e,t,[{c:Qi,f:ut}],void 0):je(e,t,[{c:o=>o+"==="+ls(e,t),f:ut}],void 0);let n=At(Xi,!1);n.const=""+t.const;let i=ei(e,n,n);return i.vc=[{c:o=>o+'==="'+n.const+'"',f:ut}],ei(i,t,t)}function Xa(){return no(Mr,Mr,e=>{e.const=void 0,e.decoder=to})}function US(){return no(Yi,Yi,e=>{e.const=null,e.decoder=to})}function Jg(){return no(yu,yu,e=>{e.const=NaN,e.decoder=to})}function Pu(e){if(e===null)return US();let t=typeof e;if(t===Mr)return Xa();if(t===Sn&&Number.isNaN(e))return Jg();if(t===st){let n=At(Su,!0);return n.class=e.constructor,n.const=e,n.decoder=to,n}let r=At(t,!0);return r.const=e,r.decoder=to,r}function nr(e){let t=e,r,n=0;for(;!t.io||t.e.to;){let i=r;r=void 0;let o=t;if(n=n+1|0,n>50)throw new Error("Loop count exceeded 100");if(o.e.$defs&&(o.g.d?Object.assign(o.g.d,o.e.$defs):o.g.d=o.e.$defs),o.f&1){let s=o.v(),a=en(o),u=nr(a),c=Nr(u,void 0);t=a.i!==u.i||c!==""?Zr(o,s+".then("+s+"=>{"+c+"return "+u.i+"})",u.s,u.e):je(o,u.s,void 0,u.e),t.f=t.f|1,t.io=!0}else if(o.io){let s=o.e.to,u=o.e.parser;t=u!==void 0?u(o):je(t,void 0,void 0,s)}else{let s=o.s.encoder;s&&s!==i&&o.s!==o.e&&o.e.type!==as&&(t=s(o,o.e)),o!==t?r=s:(t=o.e.decoder(o),t.io||(t=rs(t,t)))}}return t}function En(e){for(;;){let t=e,r=t.to;if(r===void 0)return t;e=r}}function Yr(e){if(Ki in e)return e[Ki];let t,r=e;for(;r;){let i=eo(r),o=i.to,s=t;s!==void 0?i.to=s:delete i.to;let a=i.parser,u=i.serializer;u!==void 0?i.parser=u:delete i.parser,a!==void 0?i.serializer=a:delete i.serializer;let c=i.refiner,l=i.inputRefiner;l!==void 0?i.refiner=l:delete i.refiner,c!==void 0?i.inputRefiner=c:delete i.inputRefiner;let d=i.fromDefault,h=i.default;h!==void 0?i.fromDefault=h:delete i.fromDefault,d!==void 0?i.default=d:delete i.default;let m=i.items;m!==void 0&&(i.items=m.map(Yr));let p=i.properties;if(p!==void 0){let y={},v=Object.keys(p);for(let b=0,w=v.length;b<w;++b){let S=v[b];y[S]=Yr(p[S])}i.properties=y}typeof i.additionalItems===st&&(i.additionalItems=Yr(i.additionalItems));let f=i.anyOf;if(f!==void 0){let y={},v=[];for(let b=0,w=f.length;b<w;++b){let S=f[b],q=Yr(S);v.push(q),Bg(y,q.type)}i.has=y,i.anyOf=v}let g=i.$defs;if(g!==void 0){let y={};for(let v=0,b=Object.keys(g).length;v<b;++v){let w=Object.keys(g)[v];y[w]=Yr(g[w])}i.$defs=y}t=i,r=o}let n=t;return xn[Fa]=n,br(e,Ki,xn),xn[Fa]=e,br(n,Ki,xn),n}function Wg(e){try{return nr(e)}catch(t){let r=Qa(t),n=e.p;throw r.path=(n!==void 0?n.path:"")+(e.path+"[]"+r.path),r}}function GS(e,t,r,n){let i=IS(Dr in e?ot:e,t,r,n),o=nr(i),s=Nr(o,void 0),a=AS(o.f,1);t.isAsync=a;let u=o.t===!0;if(t.hasTransform=u,s===""&&(o===i||o.i===i.i)&&!(r&1))return Ug;let c=o.i;r&1&&!a&&!n&&(c="Promise.resolve("+c+")");let l="i=>{"+s+"return "+c+"}",d=i.g.e,h=new Function("e","s","return "+l)(d,xu);return h.embedded=i.g.e,h}function Ba(e,t){let r=arguments,n=0,i,o="",s=0,a;for(;i===void 0;){let c=r[n];if(c)if(typeof c===Sn){let l=c|es.f;i=l,o=o+"-"+l}else{let l=c.seq;l>s&&(s=l,a=c),o=o+l+"-",n=n+1|0}else{let l=es.f;i=l,o=o+"-"+l}}let u=a;if(u!==void 0){let c=o;if(c in u)return u[c];let l=r[n-1|0];for(let h=n-2|0;h>=0;--h){let m=l;l=$n(r[h],p=>{p.to=m})}let d=GS(l,l,i,0);return xn[Fa]=d,br(u,c,xn),d}throw new Error("[Sury] No schema provided for decoder.")}var oi="BS_PRIVATE_NESTED_SOME_NONE";function VS(e){let t=je(e,void 0,void 0,Cu());return t.cp=jS(e,void 0)+";",t}function Cu(){return no(vu,vu,e=>{e.decoder=VS})}function BS(e){let t=e.e.to;return Zr(e,"{"+oi+":"+En(e.e).properties[oi].const+"}",t,t)}function is(e,t){return{v:Ga,i:"",s:t.type===ti?{type:ti,decoder:Iu,additionalItems:"strict",items:[]}:{type:st,decoder:ds,additionalItems:"strict",required:[],properties:{}},e:e.e,prev:e,f:0,d:{},cp:"",hd:"",t:!0,path:e.path,g:e.g}}function Ru(e){return Nu(e,Xa())}function ds(e){let t=e.u,r=e.e,n=Ke[e.s.type],i;if(n&65){let l=n&64,d;if(l)d=e.s;else{let m=At(st,!1);m.properties=Cg,m.additionalItems=ot,d=m}let h=[];l||(h.push({c:Gg,f:ut}),r.additionalItems!=="strip"&&h.push({c:m=>"!"+Va(m),f:ut})),i=h.length!==0?je(e,d,h,void 0):je(e,d,void 0,void 0)}else i=us(e,e.s,r);let o=r.additionalItems,s;s=o==="strip"||o==="strict"?void 0:o;let a=i.s.additionalItems,u;u=a!=="strip"&&a!=="strict";let c;if(s!==void 0)if(s===ot)c=i;else if(u){let l=i.v(),d=rr(i.g),h=Zg(i,d),m=Wg(h),p=m.t,f=p?Zr(i,"{}",r,void 0):je(i,r,void 0,void 0),g=Fg(m,i,d,p?()=>qg(f,d,m):void 0);if((p||g!=="")&&(f.cp=f.cp+("for(let "+d+" in "+l+"){"+g+"}")),m.f&1){let y=rr(f.g),v=rr(f.g),b=rr(f.g),w=rr(f.g),S=f.v();c=Lg(f,"new Promise(("+y+","+v+")=>{let "+w+"=Object.keys("+S+").length;for(let "+d+" in "+S+"){"+S+"["+d+"].then("+b+"=>{"+S+"["+d+"]="+b+";if("+w+"--===1){"+y+"("+S+")}},"+v+")}})")}else c=f}else{let l=is(i,r),d=Object.keys(i.s.properties);for(let h=0,m=d.length;h<m;++h){let p=d[h],f=Ja(i,p);f.e=s,f.io=!1,f.u=t,kn(l,p,nr(f))}c=os(l)}else{let l=r.properties,d=Object.keys(l),h=d.length,m=is(i,r),p=r.additionalItems,f;f=p==="strip"||p==="strict"?p==="strip"?u||Object.keys(i.s.properties).length!==h:!1:!0;let g=i.s.additionalItems,y;y=g==="strip"||g==="strict"?!1:g.name===FS;for(let b=0;b<h;++b){let w=d[b],S=l[w],q=Ja(i,w);q.e=S,q.io=!1,q.u=t,y&&S.type===Tn&&S.has[Mr]&&(q.i="("+q.i+"??null)");let K=nr(q);t&&Dr in S&&Dg(i,K,w),kn(m,w,K),f||(f=K.t)}let v=!1;if(r.additionalItems==="strict"){let b=i.s.additionalItems,w;w=b!=="strip"&&b!=="strict",v=w}if(v){let b=rr(m.g);if(Ua(i,b),m.cp=m.cp+("for("+b+" in "+i.v()+"){if("),d.length!==0)for(let w=0,S=d.length;w<S;++w){let q=d[w];w!==0&&(m.cp=m.cp+"&&"),m.cp=m.cp+(b+"!=="+ii(i.g,q))}else m.cp=m.cp+"true";m.cp=m.cp+("){"+ts(i,w=>({code:"unrecognized_keys",path:m.path,reason:'Unrecognized key "'+w+'"',keys:[w]}),b)+"}}")}if(f)c=os(m);else{let b=je(i,void 0,void 0,void 0);b.cp=m.cp,b.d=m.d,c=b}}return rs(c,i)}function JS(){let e=Pu(0),t={};return t[oi]=e,{type:st,serializer:r=>{let n=r.e.to;return ei(r,n,n)},decoder:ds,additionalItems:"strip",required:[oi],properties:t}}function Iu(e){let t=e.u,r=e.e,n=Ke[e.s.type],i=r.items,o=i.length,s;if(n&129){let l=n&128,d=l?e.s:ju(ot),h=[];l||h.push({c:Va,f:ut});let m=d.additionalItems,p;if(p=m==="strip"||m==="strict"?d.items.length===o:!1,!p){let f=r.additionalItems;(f==="strip"||f==="strict")&&(f==="strip"?h.push({c:g=>g+".length>="+o,f:ut}):h.push({c:g=>g+".length==="+o,f:ut}))}s=h.length!==0?je(e,d,h,void 0):je(e,d,void 0,void 0)}else s=us(e,e.s,r);let a=r.additionalItems,u,c=0;if(a==="strip"||a==="strict")c=1;else if(a===ot)u=s;else{let l=s.v(),d=rr(s.g),h=Zg(s,d),m=Wg(h),p=m.t,f=p?Zr(s,"new Array("+l+".length)",r,void 0):je(s,r,void 0,void 0),g=Fg(m,s,d,p?()=>qg(f,d,m):void 0);(p||g!=="")&&(f.cp=f.cp+("for(let "+d+"="+o+";"+d+"<"+l+".length;++"+d+"){"+g+"}")),u=m.f&1?Lg(f,"Promise.all("+f.i+")"):f}if(c===1){let l=is(s,r),d=r.additionalItems,h;if(d==="strip"||d==="strict")if(d==="strip"){let m=s.s.additionalItems;h=m==="strip"||m==="strict"?s.s.items.length!==o:!0}else h=!1;else h=!0;for(let m=0;m<o;++m){let p=i[m],f=m.toString(),g=Ja(s,f);g.e=p,g.io=!1,g.u=t;let y=nr(g);t&&Dr in p&&Dg(s,y,f),kn(l,f,y),h||(h=y.t)}if(h)u=os(l);else{let m=je(s,void 0,void 0,void 0);m.cp=l.cp,m.d=l.d,u=m}}return rs(u,s)}function WS(e,t){let r=e.s.anyOf;return t.type===Tn&&Kg(t)===void 0&&Hg(t.anyOf,r)||!QS(r,t)?e:KS(e,t)}function HS(e){let t=e.e,r=t.anyOf,n=Ke[e.s.type],i=Kg(t);if(e.s===t&&i===void 0&&r.every(Za)||n&256&&Hg(r,e.s.anyOf)&&i===void 0||e.io&&e.e===e.s)return e;(n&256||e.s.encoder===void 0&&n&512)&&(e.s=ot);let o="";if(!(n&769)){let j=_u(e.s),$=!1,R=!1,N=r.length,I=0;for(;o===""&&I<N;){let V=r[I];_u(V)===j?o=j:V.type===Yi?$=!0:V.type===Mr&&(R=!0),I=I+1|0}o===""&&(n&16&&$?o=Yi:n&32&&R&&(o=Mr))}let s=o,a=e.i,u=j=>ni(e,function(){let $=arguments,R=Ng(t,ot,e.path,$[0],!0,$.length>1?Array.from($).slice(1):void 0,void 0);throw new ri(R)})+"("+e.v()+j+")",c=je(e,void 0,void 0,void 0),l=[],d={contents:""},h=(j,$)=>{let R=j[0],N=j[1],I="",V="",ye=!1,qe={contents:""},Ye="",zt={},vt=2,xe=j.length-1|0;for(;vt<=xe;){let Fe=en(N);Fe.u=!0,Fe.t=N.t,Fe.io=!1,Fe.e=j[vt];let Ue=vt===xe,_e=vt===2,hr=_e&&Ue,Bi=!hr,Ar=!1,Qr="",yn={contents:""};try{let Pe=nr(Fe);if(l.push(Pe.s),Qr=Nr(Pe,yn),Pe.t){c.t=!0,Pe.f&1&&(c.f=c.f|1);let Pr=R.v();Pe.i!==Pr&&(Qr=Qr+(Pr+"="+Pe.i))}}catch(Pe){let Pr=ni(Fe,Qa(Pe));Ye=Ye+","+Pr,$&&hr?(d.contents=Pr,Ar=!0):Ue?(Bi=!1,Qr=$?"throw "+Pr:u(Ye)):Ar=!0}let vn=yn.contents,Kn=Qr;if(!Ar&&vn)if(Kn){let Pe=zt[vn];Pe!==void 0?typeof Pe=="string"?zt[vn]=[Pe,Kn]:Pe.push(Kn):zt[vn]=Kn}else qe.contents=qe.contents?qe.contents+"||"+vn:vn;if(!Ar&&(!vn||Ue)){let Pe=Object.keys(zt);for(let Pr=0,rS=Pe.length;Pr<rS;++Pr){let lg=Pe[Pr];I=I+(ye?"else if":"if")+("("+lg+"){");let Ho=zt[lg];if(typeof Ho=="string")I=I+Ho+"}";else{let ou="";for(let Ea=0,nS=Ho.length;Ea<nS;++Ea){let iS=Ho[Ea],ug="e"+Ea;I=I+("try{"+iS+"}catch("+ug+"){"),ou=ou+","+ug}I=I+u(ou)+"}".repeat(Ho.length)+"}"}ye=!0}zt={}}if(!Ar&&!vn)if(Kn)if(qe.contents&&(I=I+(ye?"else if":"if")+("(!("+qe.contents+")){"),V="}"+V,qe.contents="",ye=!1),Ue&&($||!Bi||_e))I=I+((ye?"else{":"")+Kn),V=(ye?"}":"")+V;else{let Pe="e"+(vt-2|0);I=I+((ye?"else{":"")+"try{"+Kn+"}catch("+Pe+"){"),V=(ye?"}":"")+"}"+V,Ye=Ye+","+Pe,ye=!1}else qe.contents="",vt=xe,Bi=!1;if(Ue){if(qe.contents)I||Ye?I=I+(ye?"else if":"if")+("(!("+qe.contents+")){"+u(Ye)+"}"):Ou(N,{c:Pe=>"("+qe.contents+")",f:ut});else if(Bi){let Pe=u(Ye);I=I+(ye?"else{"+Pe+"}":Pe)}}vt=vt+1}return I+V},m="",p="",f="",g=!1,y=r.length-1|0,v={},b=[],w=t.refiner,S=t.inputRefiner,q={contents:void 0},K={contents:void 0},ce=(j,$,R)=>{if($===void 0)return j;let N=I=>{let V=R.contents;if(V!==void 0)return V;let ye=$(I);return R.contents=ye,ye};return j!==void 0?I=>{let V=j(I),ye=N(I);for(let qe=0,Ye=ye.length;qe<Ye;++qe)V.push(ye[qe]);return V}:N},C=j=>{let $=ce(j.refiner,w,q);$!==void 0&&(j.refiner=$);let R=ce(j.inputRefiner,S,K);if(R!==void 0){j.inputRefiner=R;return}},G;if(Dr in e.s){let j=[],$=[];for(let R=0;R<=y;++R){let N=r[R];Dr in N&&N.const===e.s.const?j.push(N):$.push(N)}G=j.concat($)}else G=r;for(let j=0;j<=y;++j){let $=i!==void 0?$n(G[j],V=>{C(V),V.to=i}):G[j],R=$.type,N=Ke[R],I=_u($);if((s===""||s===I)&&!(N&16&&"fromDefault"in t)){let V=v[I];if(V!==void 0)N&64&&oi in $.properties?V.splice(V.length-1|0,0,$):N&2096||V.push($);else{let ye=en(e),qe;if(N&37633)qe=ot;else{let xe=At($.type,!1);xe.encoder=$.encoder,N&8192?xe.class=$.class:N&64?(xe.properties=Cg,xe.additionalItems=ot):N&128?(xe.additionalItems=ot,xe.items=Ka):N&2096&&(xe.const=$.const),xe.decoder=Fe=>Ke[Fe.s.type]&1?je(Fe,Fe.e,[{c:Ue=>{let _e=Ke[$.type];if(_e&64)return Gg(Ue)+"&&!"+Va(Ue);if(_e&128)return Va(Ue);if(_e&8192)return DS(Fe,$.class)(Ue);if(!(_e&4))return _e&2048?Qi(Ue):_e&48?Ue+"==="+ls(Fe,$):_e&17418?ns($.type)(Ue):"";let hr=ns(Sn)(Ue);return Fe.g.o&2?hr:hr+"&&!"+Qi(Ue)},f:ut}],void 0):$.decoder(Fe),qe=xe}ye.e=qe;let Ye;try{Ye=nr(ye)}catch{ye.vc=void 0,Ye=ye}Og(N,v)?b.unshift(I):b.push(I),v[I]=[ye,Ye,$];let zt=!0,vt=Ye;for(;vt!==void 0&&zt;){let xe=vt;vt=xe.prev,zt=!(xe.vc&&Mg(xe))}if(zt){for(let xe=0,Fe=b.length;xe<Fe;++xe){let Ue=b[xe];if(!g){let _e=v[Ue],hr=_e[1],Bi=h(_e,!0),Ar=Nr(hr,void 0)+Bi,Qr=d.contents;if(Qr)if(d.contents="",Ar){let yn="e"+(j+xe|0);m=m+("try{"+Ar+"throw "+Qr+"}catch("+yn+"){"),p="}"+p,f=f+","+yn}else f=f+","+Qr;else if(Ar){let yn="e"+(j+xe|0);m=m+("try{"+Ar+"}catch("+yn+"){"),p="}"+p,f=f+","+yn}else g=!0}}v={},b=[]}}}}let H=v,fe=b;if(!g){let j=!1,$="";for(let I=0,V=fe.length;I<V;++I){let ye=H[fe[I]],qe=ye[1],Ye=ye[2],zt=h(ye,!1),vt={contents:""},xe=Nr(qe,vt)+zt,Fe=vt.contents;xe||Og(Ke[Ye.type],H)?(m=m+(j?"else if":"if")+("("+Fe+"){"+xe+"}"),j=!0):$=$?$+"||"+Fe:Fe}let R=u(f),N;$?N=(j?"else if":"if")+("(!("+$+")){"+R+"}"):N=j?"else{"+R+"}":p===""?R+";":R,m=m+N}c.cp=c.cp+m+p,e.i!==c.i&&(c.i=e.i);let ge=c.f&1?(c.i="Promise.resolve("+c.i+")",c.v=Ga,c):c.v===Mt&&e.cp===""&&c.cp===""&&a==="i"?(e.hd="",e.v=Ga,e.i=a,e):c;return ge.s=l.length?ss(l):Cu(),ge.e=i!==void 0?(ge.io=!0,En(i)):t,ge}function Hg(e,t){return t.every((r,n)=>{let i=e[n];return i!==void 0&&!(Ke[r.type]&9152)&&r.type===i.type&&r.const===i.const?r.to===void 0:!1})}function KS(e,t){return je(e,ot,void 0,$n(e.s,r=>{r.to=t}))}function QS(e,t){return!(Ke[En(t).type]&512)&&!(t.type===Tn&&t.anyOf.some(r=>Ke[r.type]&512))?!e.some(r=>r.to!==void 0||r.parser!==void 0?!0:Ke[r.type]&512):!1}function Kg(e){if(e.parser!==void 0)return;let r=e.to;if(r!==void 0)return r}function Ja(e,t){let r=e.d,n;if(r!==void 0)n=r;else{let l={};e.d=l,n=l}let i=n[t];if(i!==void 0)return en(i);let o=e.s.type===st?e.s.properties[t]:e.s.items[t],s;if(o!==void 0)s=o;else{let l=e.s.additionalItems;s=l==="strip"||l==="strict"?us(e,e.s,e.e):e.s.type===st&&l.type!==as&&!(Ke[l.type]&512)&&!OS(l)?Ru(l):l}let u="["+ii(e.g,t)+"]",c={p:e,v:bu,i:Dr in s?ls(e,s):e.v()+u,s,e:s,f:0,cp:"",hd:"",path:e.path+u,g:e.g};return n[t]=c,c}function os(e){let t=e.s.type===ti,r="",n="",i,o=Object.keys(e.d);for(let c=0,l=o.length;c<l;++c){let d=o[c],h=e.d[d];if(h.f&1&&(n=n+h.i+","),h.o){let m=i;i=p=>(m!==void 0?m(p):"")+("if("+h.v()+"!==void 0){"+p+"["+ii(e.g,d)+"]="+h.i+"}")}else r=r+(t?h.i:ii(e.g,d)+":"+h.i)+","}if(e.i=t?"["+r+"]":"{"+r+"}",n){let c=en(e);c.io=!0;let l=nr(c),d=Nr(l,void 0);return d===""&&n===l.i+","?e.i=l.i:e.i="Promise.all(["+n+"]).then((["+n+"])=>{"+d+"return "+l.i+"})",e.f=e.f|1,e.s=l.s,e.e=l.e,e.io=!0,e}let s=i;if(s===void 0)return e;let a=s(e.v()),u=je(e,void 0,void 0,void 0);return u.cp=u.cp+a,u}function ss(e){let t=e.length;if(t===1)return e[0];if(t!==0){let r={},n=new Set;for(let o=0,s=e.length;o<s;++o){let a=e[o];a.type===Tn&&a.to===void 0?(a.anyOf.forEach(u=>{n.add(u)}),Object.assign(r,a.has)):(n.add(a),Bg(r,a.type))}let i=At(Tn,!1);return i.anyOf=Array.from(n),i.decoder=HS,i.encoder=WS,i.has=r,i}throw new Error("[Sury] S.union requires at least one item")}function Og(e,t){return e&8320&&st in t?!0:e&2048?Sn in t:!1}function _u(e){return Ke[e.type]&8192?e.class.name:e.type}function Za(e){for(;;){let t=e,r=!1,n=!1,i=!1;if(t.to===void 0&&t.parser===void 0&&!(Ke[t.type]&512)){let s=t.anyOf;i=s!==void 0?s.every(Za):!0}if(i){let s=t.items;n=s!==void 0?s.every(Za):!0}if(n){let s=t.properties;r=s!==void 0?Object.values(s).every(Za):!0}if(!r)return!1;let o=t.additionalItems;if(o===void 0||o==="strip"||o==="strict")return!0;e=o}}function ju(e){let t=At(ti,e[Ki]===e);return t.additionalItems=e,t.items=Ka,t.decoder=Iu,t}function Nu(e,t){let r=t!==void 0?t:Xa(),n=En(e);switch(n.type){case"undefined":return ss([r,Ag(e)]);case"union":let o=n.has,s=n.anyOf;return $n(e,a=>{let u=wS(o),c=[];for(let l=0,d=s.length;l<d;++l){let h=s[l],m=En(h),p=m.type,f;if(p==="undefined")u[r.type]=!0,c.push(r),f=Ag(h);else{let g=m.properties;if(g!==void 0){let y=g[oi];f=y!==void 0?$n(h,v=>{let b={},w={...y};w.const=y.const+1,b[oi]=w,v.properties=b}):h}else f=h}c.push(f)}c.length===s.length&&(u[r.type]=!0,c.push(r)),a.anyOf=c,a.has=u});default:return ss([e,r])}}function Ag(e){return $n(e,t=>{t.to=JS(),t.parser=BS})}br(Eu,"~standard",{get:function(){let e=this;return{version:1,vendor:wu,validate:t=>{try{return{value:Ba(ot,e)(t)}}catch(r){let n=Qa(r);return{issues:[{message:n.reason,path:n.path===""?void 0:xS(n.path)}]}}}}}});function Qg(e,t){return Ba(ot,t)(e)}function XS(e,t){return $n(e,r=>{let n=t(r),i=r.refiner;i!==void 0?r.refiner=o=>{let s=i(o),a=n(o);for(let u=0,c=a.length;u<c;++u)s.push(a[u]);return s}:r.refiner=n})}function Xg(e,t,r,n){let i=r!==void 0?r:"Refinement failed",o=n!==void 0?SS(n):"";return XS(e,s=>(a=>{let u=ni(a,t);return[{c:c=>u+"("+c+")",f:zu(void 0,o,i,void 0)}]}))}function Yg(e,t){return $n(e,r=>{let n=r.anyOf;if(n!==void 0){let o=[],s=[];for(let h=0,m=n.length;h<m;++h){let p=n[h],f=En(p);f.type!=="undefined"&&(o.push(f),s.push(p))}let a=o.length,u;if(a!==1)if(a!==0)u=ss(o);else{let h="Can't set default for "+He(r);throw new Error("[Sury] "+h)}else u=o[0];let c=s.length!==1?ss(s):s[0];if(t.TAG==="Value"){let h=t._0;try{Ba(ot,u)(h)}catch(m){let p=Qa(m),f="Invalid default for "+He(r)+": "+p.message;throw new Error("[Sury] "+f)}try{r.default=Ba(Yr(c),void 0)(h)}catch{}}r.parser=h=>{let m=h.e.to,p=h.v(),f;return f=t.TAG==="Value"?ls(h,Pu(t._0)):ni(h,t._0)+"()",Zr(h,p+"===void 0?"+f+":"+p,m,m)};let l=eo(u),d=l.decoder;l.serializer=h=>{let m=Yr(c);return je(d(h),m,void 0,m)},l.decoder=jg,r.to=l;return}let i="Can't set default for "+He(r);throw new Error("[Sury] "+i)})}function YS(e){return e[ku]}function Wa(e,t,r){let n=eo(En(e));return n.from=t,r!==void 0&&(n.fromFlattened=r),new Proxy(n,{get:(i,o)=>{if(o===ku)return i;let s=i.items,a=i.properties,u=a!==void 0?a[o]:s!==void 0?s[o]:void 0;if(u===void 0){let c='Cannot read property "'+o+'" of '+He(i);throw new Error("[Sury] "+c)}return Wa(u,i.from.concat(o),i.fromFlattened)}})}function e_(e,t,r){let n=is(e,t);n.io=!0;let i=t.items;if(i!==void 0)for(let o=0,s=i.length;o<s;++o){let a=o.toString();kn(n,a,r(a,i[o]))}else{let o=t.properties;if(o!==void 0){let s=Object.keys(o);for(let a=0,u=s.length;a<u;++a){let c=s[a];kn(n,c,r(c,o[c]))}}else{let s="Don't know where the value is coming from: "+He(t);throw new Error("[Sury] "+s)}}return os(n)}function t_(e,t){let r=t.from,n=t.fromFlattened,i=n!==void 0?en(Pg(e.fv[n],t.from,0)):r!==void 0?en(Pg(e,r,0)):Dr in t?ei(e,t,void 0):e_(e,t,(o,s)=>t_(e,s));return i.prev=void 0,i.e=t,i}function r_(e,t){let r=t.e,n=r.from;if(n!==void 0){let s=r.fromFlattened,a;if(s!==void 0){e.flattened===void 0&&(e.flattened=[]);let u=e.flattened[s];if(u!==void 0)a=u;else{let c={};e.flattened[s]=c,a=c}}else a=e;for(let u=0,c=n.length;u<c;++u){let l=n[u],d=a.properties,h;if(d!==void 0)h=d;else{let f={};a.properties=f,h=f}let m=h[l],p;if(m!==void 0)p=m;else{let f={};h[l]=f,p=f}a=p}a.val=t;return}let i=t.d;if(i===void 0)return;let o=Object.keys(i);for(let s=0,a=o.length;s<a;++s)r_(e,i[o[s]])}function La(e,t,r,n){let i=0;if(t!==void 0){let o=t.val;if(o!==void 0){let s=en(o);return s.t=!0,s.s=r,s.e=r,nr(s)}i=1}else i=1;if(i===1){if(Dr in r){let d=ei(e,r,r);return d.prev=void 0,d.p=e,d.v=bu,d.io=!0,nr(d)}let o=t===void 0?En(r):r,s=is(e,o);s.e=o,s.io=!0,s.prev=void 0,s.p=e,s.v=bu;let a=o.flattened,u=o.items,c=0,l=0;if(u!==void 0&&(t!==void 0||typeof o.additionalItems!==st))for(let d=0,h=u.length;d<h;++d){let m=d.toString(),p;if(t!==void 0){let g=t.properties;p=g!==void 0?g[m]:void 0}else p=void 0;let f=ii(e.g,m);kn(s,m,La(e,p,u[d],n+("["+f+"]")))}else l=3;if(l===3){let d=o.properties;if(d!==void 0&&(t!==void 0||typeof o.additionalItems!==st)){if(a!==void 0&&t!==void 0){let m=t.flattened;m!==void 0&&m.forEach((p,f)=>{let y=La(e,p,Yr(a[f]),n).d,v=Object.keys(y);for(let b=0,w=v.length;b<w;++b){let S=v[b];kn(s,S,y[S])}})}let h=Object.keys(d);for(let m=0,p=h.length;m<p;++m){let f=h[m];if(!(f in s.d)){let g;if(t!==void 0){let v=t.properties;g=v!==void 0?v[f]:void 0}else g=void 0;let y=ii(e.g,f);kn(s,f,La(e,g,d[f],n+("["+y+"]")))}}}else c=2}if(c===2){let d=r.from,h=d!==void 0?n+d.map(p=>'["'+p+'"]').join(""):n,m=h===""?"":" at "+h;MS(e,"Missing input for "+He(r)+m)}return os(s)}}function Pg(e,t,r){for(;;){let n=r,i=e,o=t[n];if(o===void 0)return i;r=n+1|0,e=i.d[o]}}function Ha(e,t){if(typeof e!==st||e===null)return Pu(e);let r=t(e);if(r!==void 0)return r;if(Array.isArray(e)){for(let u=0,c=e.length;u<c;++u){let l=Ha(e[u],t);e[u]=l}let a=At(ti,!1);return a.items=e,a.additionalItems="strict",a.decoder=Iu,a}let n=e.constructor;if(n&&n!==Object){let a=At(Su,!0);return a.class=n,a.const=e,a.decoder=to,a}let i=Object.keys(e),o=i.length;for(let a=0;a<o;++a){let u=i[a],c=Ha(e[u],t);e[u]=c}let s=At(st,!1);return s.required=i,s.properties=e,s.additionalItems=es.a,s.decoder=ds,s}function eT(e){let t={};r_(t,e);let r=e.e.to,n=La(e,t,r,"");return n.t=!0,n.prev=e,n}function n_(e){return Ha(e,t=>{if(t["~standard"])return t})}function i_(e){let t=this,r="~"+e,n=t[r];if(n!==void 0)return ve(n);let i={},o=[],s=At(st,!1);s.required=o,s.properties=i,s.additionalItems=es.a,s.decoder=ds;let a=t.f(e,s)[ku],u=(m,p)=>{let f=ro(m);if(m in i)throw new Error("[Sury] "+("The field "+f+" defined twice"));return o.push(m),i[m]=p,Wa(p,a.from.concat(m),a.fromFlattened)},h={field:u,f:u,fieldOr:(m,p,f)=>{let g=Nu(p,void 0);return u(m,Yg(g,{TAG:"Value",_0:f}))},tag:(m,p)=>{u(m,n_(p))},nested:i_,flatten:m=>{if(m.type==="object"){let g=m.to,y=m.properties;if(g){let w="Unsupported nested flatten for transformed object schema "+He(m);throw new Error("[Sury] "+w)}let v=Object.keys(y),b={};for(let w=0,S=v.length;w<S;++w){let q=v[w];b[q]=u(q,y[q])}return b}let f="Can't flatten "+He(m)+" schema";throw new Error("[Sury] "+f)}};return t[r]=h,h}function tT(e){let t=eo(Ha(e,YS));return t.serializer=eT,t}function rT(e){let t=e.e.flattened;if(t!==void 0){let i=[];for(let o=0,s=t.length;o<s;++o){let a=t[o],u=a.to,c;if(u!==void 0){let l=en(e);l.e=a,l.io=!0,c=nr(l)}else{let l=e_(e,a,(d,h)=>Ja(e,d));l.e=a,l.prev=void 0,c=rs(l,l)}i.push(c),e.cp=e.cp+Nr(c,void 0)}e.fv=i}let r=e.e.to,n=t_(e,r);return n.t=!0,n.prev=e,rs(n,e)}function o_(e){let t,r={},n=l=>{if(l.type==="object"){let m=l.properties,p=Object.keys(m);for(let g=0,y=p.length;g<y;++g){let v=p[g],b=m[v],w=r[v];if(w!==void 0){if(w!==b)throw new Error("[Sury] "+('The field "'+v+'" defined twice with incompatible schemas'))}else r[v]=b}let f=t||(t=[]);return Wa(l,Ka,f.push(l)-1|0)}let h="The '"+He(l)+"' schema can't be flattened";throw new Error("[Sury] "+h)},i=(l,d)=>{if(l in r)throw new Error("[Sury] "+('The field "'+l+'" defined twice with incompatible schemas'));return r[l]=d,Wa(d,[l],void 0)},u=e({field:i,f:i,fieldOr:(l,d,h)=>{let m=Nu(d,void 0);return i(l,Yg(m,{TAG:"Value",_0:h}))},tag:(l,d)=>{i(l,n_(d))},nested:i_,flatten:n}),c=At(st,!1);return c.required=Object.keys(r),c.properties=r,c.additionalItems=es.a,c.decoder=ds,c.parser=rT,c.to=tT(u),t!==void 0&&(c.flattened=t),c}var zn=Au();var s_=Vg();var a_=Tu;var c_=ju;var fs=Ru;var tn=Xg;var l_=Qg;var Ya=o_;function iT(e){return{path:e.path,summary:e.message}}function F(e){return{path:"",summary:e}}function Mu(e,t){try{return{TAG:"Ok",_0:l_(e,t)}}catch(r){let n=X(r);if(n.RE_EXN_ID===a_)return{TAG:"Error",_0:iT(n._1)};throw n}}import*as ms from"node:fs";import*as h_ from"node:os";import*as ec from"node:path";var oT="--api-url must be ws://, wss://, http://, or https://";function Pt(e){let t=Wi(e);if(t===void 0)return{TAG:"Error",_0:"invalid URL: "+e};let r=ve(t),n=r.protocol,i;switch(n){case"http:":case"https:":i={TAG:"Ok",_0:void 0};break;case"ws:":r.protocol="http:",i={TAG:"Ok",_0:void 0};break;case"wss:":r.protocol="https:",i={TAG:"Ok",_0:void 0};break;default:i={TAG:"Error",_0:oT}}return tt(i,()=>{r.pathname="",r.search="",r.hash="";let o=r.toString();return o.endsWith("/")?o.slice(0,o.length-1|0):o})}var d_="wss://serve.linzumi.com";function ps(){return ec.join(h_.homedir(),".linzumi","auth.json")}var f_="Kandan auth cache must contain a JSON object",sT="Kandan auth cache local_codex_runner must be an object",aT="Kandan auth cache personal_agent_delegation must be an object";function m_(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.access_token,r=e.issued_at;if(t===void 0||typeof t!="string"||r===void 0||typeof r!="string")return;let n=e.expires_at,i;return i=typeof n=="string"?n:void 0,{accessToken:t,issuedAt:r,expiresAt:i}}function g_(e){let t;try{t=JSON.parse(e)}catch{t=void 0}if(t===void 0)return{TAG:"Error",_0:F(f_)};if(typeof t!="object"||t===null||Array.isArray(t))return{TAG:"Error",_0:F(f_)};let r=t.local_codex_runner,n=t.personal_agent_delegation,i=r!==void 0?typeof r=="object"&&r!==null&&!Array.isArray(r):!0,o=n!==void 0?typeof n=="object"&&n!==null&&!Array.isArray(n):!0;if(!i)return{TAG:"Error",_0:F(sT)};if(!o)return{TAG:"Error",_0:F(aT)};let s;return s=typeof r=="object"&&r!==null&&!Array.isArray(r)?Object.fromEntries(Ht(Object.entries(r),a=>{let u=a[0];return wt(m_(a[1]),c=>[u,c])})):void 0,{TAG:"Ok",_0:{serverTokens:s,personalAgentDelegation:it(n,m_)}}}function __(e){return ms.existsSync(e)?Y(ke(yr(e),t=>F(t.message)),t=>tt(g_(t),r=>r)):{TAG:"Ok",_0:void 0}}function y_(e,t){return e!==void 0?new Date(e).getTime()<=t:!1}function tc(e,t,r){return ms.existsSync(t)?Y(__(t),n=>tt(ke(Pt(e),F),i=>it(it(it(n,o=>o.serverTokens),o=>o[i]),o=>{if(!(o.accessToken.trim()===""||y_(o.expiresAt,r)))return{accessToken:o.accessToken,serverBaseUrl:i,issuedAt:o.issuedAt,expiresAt:o.expiresAt}}))):{TAG:"Ok",_0:void 0}}function cT(e){return"missing personal-agent delegation auth file: "+e}var lT="personal-agent delegation auth file is missing access_token",uT="personal-agent delegation auth file token is expired";function v_(e,t){return ms.existsSync(e)?Y(__(e),r=>{let n=it(r,i=>i.personalAgentDelegation);return n!==void 0&&n.accessToken.trim()!==""?y_(n.expiresAt,t)?{TAG:"Error",_0:F(uT)}:{TAG:"Ok",_0:n}:{TAG:"Error",_0:F(lT)}}):{TAG:"Error",_0:F(cT(e))}}function p_(e){let t={};t.access_token=e.accessToken,t.issued_at=e.issuedAt;let r=e.expiresAt;return r!==void 0&&(t.expires_at=r),t}function dT(e){let t={};t.version=1;let r=e.serverTokens;r!==void 0&&(t.local_codex_runner=Object.fromEntries(Object.entries(r).map(i=>[i[0],p_(i[1])])));let n=e.personalAgentDelegation;return n!==void 0&&(t.personal_agent_delegation=p_(n)),t}function Du(e,t,r,n,i){return Y(ke(Pt(e),F),o=>{let s=ms.existsSync(n)?Y(ke(yr(n),a=>F(a.message)),g_):{TAG:"Ok",_0:{serverTokens:void 0,personalAgentDelegation:void 0}};return Y(s,a=>{let u=i.toISOString(),c=wt(r,y=>new Date(i.getTime()+y*1e3).toISOString()),l={accessToken:t,issuedAt:u,expiresAt:c},d=a.serverTokens,h=d!==void 0?Object.fromEntries(Object.entries(d)):{};h[o]=l;let m=dT({serverTokens:h,personalAgentDelegation:a.personalAgentDelegation}),p=JSON.stringify(m,void 0,2)+`
110
+ `,f=n+".tmp."+process.pid.toString()+"."+vg(6),g=y=>F(y.message);return Y(ke(vr(ec.dirname(n)),g),()=>{let y=Y(Xo(f,p,{encoding:"utf8",mode:384}),()=>Pa(f,n));return y.TAG==="Ok"?{TAG:"Ok",_0:{accessToken:t,serverBaseUrl:o,issuedAt:u,expiresAt:c}}:(Qn(f),{TAG:"Error",_0:F(y._0.message)})})})})}function Lu(e){let t=Cr(e);return t!==void 0?lt(Rr(ve(t)),"unknown error"):"unknown error"}async function hs(e,t){try{return{TAG:"Ok",_0:await fetch(e,t)}}catch(r){let n=X(r);return{TAG:"Error",_0:{message:Lu(n)}}}}async function fT(e){try{return{TAG:"Ok",_0:await e.text()}}catch(t){let r=X(t);return{TAG:"Error",_0:{message:Lu(r)}}}}async function gs(e){let t=await fT(e);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};try{return{TAG:"Ok",_0:JSON.parse(t._0)}}catch(r){let n=X(r);return{TAG:"Error",_0:{message:Lu(n)}}}}function mT(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}async function io(e,t,r,n,i){let o=i!==void 0?i:[],s=ke(Pt(e),F);if(s.TAG!=="Ok")return{TAG:"Error",_0:s._0};let a=Xr("/api/v2/local-codex-runner/oauth/validate",s._0);if(a.TAG!=="Ok")return{TAG:"Error",_0:F(a._0)};let u=a._0,c=u.searchParams;r!==void 0&&c.set("workspace",r),n!==void 0&&c.set("channel",n),o.forEach(p=>{c.append("required_scope",p)});let l={};l.authorization="Bearer "+t;let d=await hs(u.toString(),{method:"GET",headers:l});if(d.TAG!=="Ok")return{TAG:"Error",_0:F(d._0.message)};let h=d._0,m=h.status;if(m>404||m<401){if(m===200){let p=await gs(h);return p.TAG!=="Ok"?{TAG:"Error",_0:F(p._0.message)}:it(mT(p._0),g=>g.ok)===!0?{TAG:"Ok",_0:"Usable"}:{TAG:"Ok",_0:"Rejected"}}}else{if(m<402)return{TAG:"Ok",_0:"Rejected"};switch(m){case 402:break;case 403:return{TAG:"Ok",_0:"Rejected"};case 404:return{TAG:"Ok",_0:"NotFound"}}}return{TAG:"Error",_0:F("local runner auth validation failed with HTTP "+m.toString())}}import*as q_ from"node:os";import*as ic from"node:fs";import*as Bu from"node:os";import*as xt from"node:path";import*as Ju from"node:crypto";function Fu(e){return isFinite(e)?Math.trunc(e)===e:!1}var pT=new RegExp("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$","i"),hT=new RegExp("^[a-zA-Z0-9_.-]+$");function Uu(e){return pT.test(e)}function nc(e){return hT.test(e)}var gT=tn(zn,e=>e.trim()!=="","allowedCwds entries must be non-empty strings",void 0);function S_(e){return{version:1,machineId:e.f("machineId",fs(tn(zn,Uu,"invalid machine id",void 0))),runnerId:e.f("runnerId",fs(tn(zn,nc,"invalid runner id",void 0))),allowedCwds:e.f("allowedCwds",c_(gT))}}var _T=Ya(S_),yT=Ya(e=>(e.tag("version",1),S_(e)));function Gu(e){let t=new Set;return Ht(e,r=>{let n=r.trim();if(!(n===""||t.has(n)))return t.add(n),n})}function T_(e){return{version:e.version,machineId:e.machineId,runnerId:e.runnerId,allowedCwds:Gu(e.allowedCwds)}}function Vu(e){return tt(Mu(e,yT),T_)}function $_(e){return tt(Mu(e,_T),T_)}var rc=fs(tn(zn,e=>e.trim()!=="","must be a non-empty string",void 0)),x_=fs(tn(s_,e=>Fu(e)?e>0:!1,"must be a positive integer",void 0));function vT(e){return!Number.isNaN(new Date(e).getTime())}var k_=tn(zn,vT,"must be a parseable date",void 0),fZ=Ya(e=>({email:e.f("email",tn(zn,t=>t.trim()!=="","must be a non-empty string",void 0)),serviceUrl:e.f("service_url",tn(zn,t=>t.trim()!=="","must be a non-empty string",void 0)),accessToken:e.f("access_token",rc),refreshToken:e.f("refresh_token",rc),expiresInSeconds:e.f("expires_in_seconds",x_),userId:e.f("user_id",x_),workspaceSlug:e.f("workspace_slug",rc),launchUrl:e.f("launch_url",rc),createdAt:e.f("created_at",k_),updatedAt:e.f("updated_at",k_)}));var Lr="prod";function E_(e){let t=e!==void 0?e:process.env,r=uu(t,"HOME");return r!==void 0&&r.trim()!==""?r:Bu.homedir()}function wT(e,t){let r=e!==void 0?e:process.env;return t==="~"?E_(r):t.startsWith("~/")?xt.resolve(E_(r),t.slice(2)):t}function A_(e){let t=uu(e,"LINZUMI_CONFIG_FILE");return t!==void 0&&t.trim()!==""?xt.resolve(wT(e,t)):xt.resolve(Bu.homedir(),".linzumi","config.json")}function _s(e){let t=Pt(e),r=Pt(d_);if(t.TAG!=="Ok")return{TAG:"Error",_0:F(t._0)};let n=t._0;return r.TAG==="Ok"?{TAG:"Ok",_0:n===r._0?Lr:n}:{TAG:"Error",_0:F(r._0)}}function xT(e){return tt(_s(e),t=>t===Lr?Lr:Buffer.from(t).toString("base64url"))}function kT(e,t,r){let n=xt.dirname(e),i=xt.basename(e);return t!==void 0?Y(_s(t),o=>o===Lr?{TAG:"Ok",_0:xt.join(n,i+"."+r)}:tt(xT(t),s=>xt.join(n,i+"."+s+"."+r))):{TAG:"Ok",_0:xt.join(n,i+"."+r)}}function P_(e){if(ic.existsSync(e))return Y(ke(yr(e),r=>F(r.message)),r=>{let n;try{n=JSON.parse(r)}catch{n=void 0}return typeof n=="object"&&n!==null&&!Array.isArray(n)?Vu(n).TAG==="Ok"?{TAG:"Ok",_0:n}:{TAG:"Error",_0:F("invalid Linzumi config: "+e)}:{TAG:"Error",_0:F("invalid Linzumi config: "+e)}});let t={};return t.version=1,t.allowedCwds=[],{TAG:"Ok",_0:t}}function ST(){let e={};return e.allowedCwds=[],e}function z_(e,t){return Y(P_(e),r=>{let n=t!==void 0?_s(t):{TAG:"Ok",_0:Lr};return Y(n,i=>{let o=i===Lr?r:lt(r[i],ST()),s=i===Lr?Vu(o):$_(o);return ke(s,a=>F("invalid Linzumi config section "+i+": "+e))})})}function TT(e,t){let r=i=>F(i.message),n=ic.existsSync(e)?ke(Aa(e,384),r):{TAG:"Ok",_0:void 0};return Y(Y(n,()=>ke(Xo(e,JSON.stringify(t,void 0,2)+`
111
+ `,{encoding:"utf8",mode:384}),r)),()=>ke(Aa(e,384),r))}function $T(e){let t={},r=e.machineId;r!==void 0&&(t.machineId=r);let n=e.runnerId;return n!==void 0&&(t.runnerId=n),t.allowedCwds=Gu(e.allowedCwds).map(i=>i),t}function ET(e){let t=e.version===1,r=e.machineId,n=r!==void 0?Uu(r):!0,i=e.runnerId,o=i!==void 0?nc(i):!0,s=e.allowedCwds.every(a=>a.trim()!=="");return t&&n&&o&&s?{TAG:"Ok",_0:void 0}:{TAG:"Error",_0:F("invalid Linzumi config")}}function zT(e,t,r){return Y(ET(e),()=>{let n=r!==void 0?_s(r):{TAG:"Ok",_0:Lr};return Y(n,i=>Y(P_(t),o=>{let s=Object.fromEntries(Object.entries(o)),a=$T(e);return i===Lr?(Object.entries(a).forEach(u=>{s[u[0]]=u[1]}),s.version=1):(s.version=1,s[i]=a),Y(ke(vr(xt.dirname(t)),u=>F(u.message)),()=>TT(t,s))}))})}function O_(e,t,r){return Y(ke(yr(e),n=>F(n.message)),n=>{let i=n.trim();return t(i)?{TAG:"Ok",_0:i}:{TAG:"Error",_0:F("invalid Linzumi "+r+" seed: "+e)}})}function OT(e,t,r,n){if(ic.existsSync(e))return O_(e,r,n);let i=t();if(!r(i))return{TAG:"Error",_0:F("invalid generated Linzumi "+n+": "+i)};let o=xt.dirname(e),s=xt.basename(e),a=xt.join(o,"."+s+"."+process.pid.toString()+"."+Ju.randomUUID()+".tmp"),u=c=>F(c.message);return Y(Y(ke(vr(o),u),()=>ke(Xo(a,i+`
112
+ `,{encoding:"utf8",flag:"wx"}),u)),()=>{let c=_g(a,e),l;if(c.TAG==="Ok")l={TAG:"Ok",_0:i};else{let d=c._0;l=hg(d,"EEXIST")?O_(e,r,n):{TAG:"Error",_0:F(d.message)}}return yg(a),l})}function AT(){return"runner-"+Ju.randomUUID()}function PT(e,t,r,n,i,o,s,a){let u=t!==void 0?tt(_s(t),c=>{if(c!==Lr)return t}):{TAG:"Ok",_0:void 0};return Y(u,c=>Y(z_(e,c),l=>{let d=s(l);return d!==void 0?{TAG:"Ok",_0:d}:Y(kT(e,c,r),h=>Y(OT(h,n,i,o),m=>Y(z_(e,c),p=>{let f=s(p);return f!==void 0?{TAG:"Ok",_0:f}:tt(zT(a(p,m),e,c),()=>m)})))}))}function C_(e,t,r){return PT(e,t,"runner-id",r!==void 0?r:AT,nc,"runner id",i=>i.runnerId,(i,o)=>({version:i.version,machineId:i.machineId,runnerId:o,allowedCwds:i.allowedCwds}))}function R_(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.error;if(typeof t=="string")return t}function I_(e,t){if(e===void 0)return t!==void 0?"local runner device authorization failed (HTTP "+t.toString()+", no reason returned by the server)":"local runner device authorization failed (no reason returned by the server)";switch(e){case"access_denied":return"local runner device authorization was denied";case"approving_user_not_found":return"local runner device authorization failed: the approving Linzumi account could not be found";case"device_session_consumed":return"local runner device authorization was already used";case"device_session_expired":return"local runner device authorization expired";case"device_session_not_pending":return"local runner device authorization was already decided (approved or denied) on the server";case"invalid_device_code":return"local runner device authorization code was rejected";case"invalid_user_code":return"local runner device authorization code was not recognized by the server";case"rate_limited":return"local runner device authorization was rate limited by the server; wait a minute and retry";default:return"local runner device authorization failed (server said: "+e+")"}}function oo(e,t){let r=e[t];if(r!==void 0&&typeof r=="string"&&r.trim()!=="")return r}async function j_(e,t,r,n,i){let o=Xr("/api/v2/local-codex-runner/device/start",e);if(o.TAG!=="Ok")return{TAG:"Error",_0:F(o._0)};let s={},a=(g,y)=>{if(y!==void 0){s[g]=y;return}};a("workspace",t),a("channel",r),a("onboarding",n),i!==void 0&&(a("runner_id",i.commanderId),a("machine_fingerprint",i.machineFingerprint),a("hostname",i.hostname));let u={};u["content-type"]="application/json";let c=await hs(o._0.toString(),{method:"POST",headers:u,body:JSON.stringify(s)});if(c.TAG!=="Ok")return{TAG:"Error",_0:F(c._0.message)};let l=c._0,d=l.status,h=await gs(l);if(h.TAG!=="Ok")return{TAG:"Error",_0:F(h._0.message)};let m=h._0;if(d>=200&&d<300){if(Array.isArray(m))return{TAG:"Error",_0:F("local runner device authorization response was incomplete")};if(m!==null)switch(typeof m){case"object":let g=oo(m,"device_code"),y=oo(m,"user_code"),v=oo(m,"verification_uri");if(g===void 0)return{TAG:"Error",_0:F("local runner device authorization response was incomplete")};if(y===void 0)return{TAG:"Error",_0:F("local runner device authorization response was incomplete")};if(v===void 0)return{TAG:"Error",_0:F("local runner device authorization response was incomplete")};let b=m.expires_in,w;return w=typeof b=="number"?b:void 0,{TAG:"Ok",_0:{deviceCode:g,userCode:y,verificationUri:v,expiresInSeconds:w}}}}let f=R_(m);return{TAG:"Error",_0:F(f!==void 0?"local runner device authorization failed to start (server said: "+f+")":"local runner device authorization failed to start (HTTP "+d.toString()+")")}}async function RT(e,t,r){let n=new AbortController,i=setTimeout(()=>{n.abort()},r+1e4|0),o={};o.device_code=t,o.wait_ms=r;let s={};s["content-type"]="application/json";let a=Xr("/api/v2/local-codex-runner/device/token",e),u;if(u=a.TAG==="Ok"?await hs(a._0.toString(),{method:"POST",headers:s,body:JSON.stringify(o),signal:gr(n.signal)}):{TAG:"Error",_0:{message:a._0}},u.TAG==="Ok"){let c=u._0,l=c.status,d=await gs(c);if(clearTimeout(i),d.TAG!=="Ok")return n.signal.aborted?"Continue":{TAG:"Done",_0:{TAG:"Transient",reason:"non-JSON device/token response ("+d._0.message+")",httpStatus:l}};let h=d._0,m=l>=200&&l<300,p=R_(h),f=0;if(l!==202||p===void 0)f=1;else{if(p==="authorization_pending")return"Continue";f=1}if(f===1){let g=0;if(m){if(Array.isArray(h))return{TAG:"Done",_0:{TAG:"Rejected",reason:"device token response did not include access_token",httpStatus:l}};if(h===null)g=2;else switch(typeof h){case"object":let y=oo(h,"access_token");if(y===void 0)return{TAG:"Done",_0:{TAG:"Rejected",reason:"device token response did not include access_token",httpStatus:l}};let v=h.expires_in,b;return b=typeof v=="number"?v:void 0,{TAG:"Done",_0:{TAG:"Token",_0:{accessToken:y,expiresInSeconds:b,workspaceSlug:oo(h,"workspace"),channelSlug:oo(h,"channel")}}};default:g=2}}else g=2;if(g===2){let y=0;if(p!==void 0)switch(p){case"access_denied":return{TAG:"Done",_0:"Denied"};case"device_session_consumed":return{TAG:"Done",_0:"Consumed"};case"device_session_expired":return{TAG:"Done",_0:"CodeExpired"};default:y=3}else y=3;if(y===3)return l>=500||l===429?{TAG:"Done",_0:{TAG:"Transient",reason:p!==void 0?p:"HTTP "+l.toString(),httpStatus:l}}:{TAG:"Done",_0:{TAG:"Rejected",reason:p,httpStatus:l}}}}}else return clearTimeout(i),n.signal.aborted?"Continue":{TAG:"Done",_0:{TAG:"Transient",reason:u._0.message,httpStatus:void 0}}}async function N_(e,t,r,n){let i=n!==void 0?n:()=>Date.now(),o=r!==void 0&&r>=0?r:600,s=i()+o*1e3,a=async()=>{if(i()>=s)return"CodeExpired";let u=Math.max(0,Math.min(3e4,s-i())),c=await RT(e,t,u);return typeof c!="object"?await a():c._0};return await a()}var jT=3600*1e3;function NT(e,t,r,n){return e<=3?"DecidePrompt":r!==void 0&&t-r<jT?n?"DecideRefreshLine":"DecideSilent":"DecideSummary"}function M_(e){let t=Math.floor(e/6e4),r=Math.floor(t/60),n=t-r*60;return r>0?r.toString()+"h "+n.toString()+"m":n.toString()+"m"}function MT(e){switch(e.TAG){case"Prompt":return(e.cycle===1?"":`The previous code expired; here is a fresh one (no restart needed - this prompt stays alive).
112
113
  `)+`Authorize this computer:
113
114
  Code: `+e.userCode+`
114
115
  Open: `+e.verificationUri+`
115
- `;case"Summary":return"Still waiting for authorization after "+Bg(e.waitedMs)+" "+("("+e.cycle.toString()+` codes issued so far).
116
+ `;case"Summary":return"Still waiting for authorization after "+M_(e.waitedMs)+" "+("("+e.cycle.toString()+` codes issued so far).
116
117
  `)+(`Authorize this computer:
117
118
  Code: `+e.userCode+`
118
119
  Open: `+e.verificationUri+`
119
- `);case"RefreshLine":return"\r\x1B[2KCode: "+e.userCode+" (waiting "+Bg(e.waitedMs)+") - open "+e.verificationUri;case"TransientFailure":return"Device authorization poll hit a transient failure ("+e.reason+`); retrying with the same code.
120
+ `);case"RefreshLine":return"\r\x1B[2KCode: "+e.userCode+" (waiting "+M_(e.waitedMs)+") - open "+e.verificationUri;case"TransientFailure":return"Device authorization poll hit a transient failure ("+e.reason+`); retrying with the same code.
120
121
  `;case"StartFailed":return"Could not mint a device authorization code ("+e.reason+"); retrying in "+Math.round(e.retryInMs/1e3).toString()+`s.
121
- `}}function yS(e){return new Promise((t,r)=>{setTimeout(()=>t(),e|0)})}function vS(e){return{startDeviceAuthorization:t=>Fg(t.httpBaseUrl,t.workspaceSlug,t.channelSlug,t.onboarding,t.identity),pollDeviceCodeForToken:t=>Gg(t.httpBaseUrl,t.deviceCode,t.expiresInSeconds,void 0),now:()=>Date.now(),sleep:yS,report:e,log:(t,r)=>{}}}var bS="local runner device authorization was denied - a signed-in user rejected this computer";async function Jg(e,t,r,n,i,o,s,a){let l=o!==void 0?o:y=>{Po(y)},c=a!==void 0?a:vS(y=>l(_S(y))),u=s!==void 0?s:kt(Oi(process.stderr.isTTY),!0),d=Ae($t(e),N);if(d.TAG!=="Ok")return{TAG:"Error",_0:d._0};let h=d._0,p=c.now(),m={cycle:0,lastLoudPromptAtMs:void 0,startFailures:0},f=async y=>{let v=await c.pollDeviceCodeForToken({httpBaseUrl:h,deviceCode:y.deviceCode,expiresInSeconds:y.expiresInSeconds});if(typeof v!="object"||v.TAG!=="Transient")return v;let b=v.httpStatus,w=v.reason;c.report({TAG:"TransientFailure",reason:w,waitedMs:c.now()-p});let S={};return S.cycle=m.cycle,S.reason=w,S.httpStatus=b!==void 0?b:null,c.log("device_wait.transient_poll_failure",S),await c.sleep(5e3),await f(y)},g=async()=>{let y=await c.startDeviceAuthorization({httpBaseUrl:h,workspaceSlug:t,channelSlug:r,onboarding:n,identity:i});if(y.TAG==="Ok"){let v=y._0;m.startFailures=0,m.cycle=m.cycle+1|0;let b=gS(m.cycle,c.now(),m.lastLoudPromptAtMs,u),w=0;switch(b){case"DecidePrompt":case"DecideSummary":w=1;break;case"DecideRefreshLine":c.report({TAG:"RefreshLine",cycle:m.cycle,userCode:v.userCode,verificationUri:v.verificationUri,waitedMs:c.now()-p});break;case"DecideSilent":break}if(w===1){m.lastLoudPromptAtMs=c.now();let F=c.now()-p,ce;ce=b==="DecidePrompt"?{TAG:"Prompt",cycle:m.cycle,userCode:v.userCode,verificationUri:v.verificationUri,waitedMs:F}:{TAG:"Summary",cycle:m.cycle,userCode:v.userCode,verificationUri:v.verificationUri,waitedMs:F},c.report(ce)}let S={};S.cycle=m.cycle,S.verificationUri=v.verificationUri,c.log("device_wait.code_issued",S);let Z=await f(v);if(typeof Z!="object")switch(Z){case"CodeExpired":let F={};return F.cycle=m.cycle,F.outcome="code_expired",c.log("device_wait.code_retired",F),await g();case"Denied":return{TAG:"Error",_0:N(bS)};case"Consumed":let ce={};return ce.cycle=m.cycle,ce.outcome="consumed",c.log("device_wait.code_retired",ce),await g()}else switch(Z.TAG){case"Token":let F={};return F.cycle=m.cycle,F.waitedMs=c.now()-p,c.log("device_wait.authorized",F),{TAG:"Ok",_0:Z._0};case"Rejected":let ce=Z.httpStatus,Je=Z.reason;c.report({TAG:"TransientFailure",reason:Ug(Je,ce),waitedMs:c.now()-p});let Ee={};return Ee.cycle=m.cycle,Ee.reason=Je!==void 0?Je:null,Ee.httpStatus=ce,c.log("device_wait.code_rejected",Ee),await g();case"Transient":return await g()}}else{let v=y._0;m.startFailures=m.startFailures+1|0;let b=Math.min(6e4,5e3*Math.pow(2,m.startFailures-1|0));c.report({TAG:"StartFailed",reason:v.summary,retryInMs:b});let w={};return w.reason=v.summary,w.retryInMs=b,w.attempt=m.startFailures,c.log("device_wait.start_failed",w),await c.sleep(b),await g()}};return await g()}var kS="linzumi-machine-fingerprint:v1:";var Wg={platform:void 0,execFile:void 0,readFile:void 0,username:void 0};function SS(e,t){return Oh(e,t,5e3,1024*1024)}var $S=new RegExp('"IOPlatformUUID"\\s*=\\s*"([0-9A-Fa-f-]{36})"'),TS=new RegExp("^[0-9a-f]{32}$"),zS=["/etc/machine-id","/var/lib/dbus/machine-id"];function ES(e){let t=e!==void 0?e:Wg,r=xt(t.platform,process.platform),n=xt(t.execFile,SS),i=xt(t.readFile,fr);switch(r){case"darwin":let o=n("ioreg",["-rd1","-c","IOPlatformExpertDevice"]);if(o.TAG!=="Ok")return;let s=$S.exec(o._0);if(s==null)return;let a=s.slice(1)[0];if(a===void 0)return;let l=de(a);return l!==void 0?l.toLowerCase():void 0;case"linux":return Mh(zS,void 0,(c,u)=>{if(c!==void 0)return c;let d=i(u);if(d.TAG!=="Ok")return;let h=d._0.trim().toLowerCase();if(TS.test(h))return h});default:return}}function Hg(e){return ft(ES(e!==void 0?e:Wg),r=>"mfp-"+la(kS+r).slice(0,32))}function OS(e,t){return Q(Ae($t(e),N),r=>{let n=Ci(r);return n===void 0?{TAG:"Error",_0:N("invalid URL: "+r)}:{TAG:"Ok",_0:"Workspace '"+(t!==void 0?t:"undefined")+"' was not found on "+de(n).host+". Sign in to the web app to create it, then re-run connect."}})}var PS="local runner browser OAuth is not available in this implementation yet; use --auth-mode device or supply --token";async function CS(e){let t=Zg(process.env),r=Lg(t,e.serviceUrl,void 0);if(r.TAG!=="Ok")return{TAG:"Error",_0:r._0};let n=r._0,i=Hg(void 0),o=Kg.hostname(),s={commanderId:n,machineFingerprint:i,hostname:o},a=await Jg(e.serviceUrl,e.workspaceSlug,e.channelSlug,e.onboarding,s,void 0,void 0,void 0);if(a.TAG!=="Ok")return{TAG:"Error",_0:a._0};let l=a._0,c=e.authFilePath,u=c!==void 0?c:Bo();return tt(nu(e.serviceUrl,l.accessToken,l.expiresInSeconds,u,new Date),d=>l.accessToken)}async function RS(e){let t=e.authMode;return typeof(t!==void 0?t:{TAG:"BrowserMode",callbackHost:e.callbackHost})!="object"?await CS(e):{TAG:"Error",_0:N(PS)}}function IS(){return{readCachedToken:(e,t)=>Ca(e,t,Date.now()),validateToken:(e,t,r,n,i)=>Vi(e,t,r,n,i),acquireAndCacheToken:RS}}async function jS(e,t,r){let n=await t.validateToken(e.serviceUrl,r,e.workspaceSlug,e.channelSlug,e.requiredScopes);if(n.TAG!=="Ok")return{TAG:"Ok",_0:void 0};switch(n._0){case"Usable":case"Rejected":return{TAG:"Ok",_0:void 0};case"NotFound":return Q(OS(e.serviceUrl,e.workspaceSlug),i=>({TAG:"Error",_0:N(i)}))}}async function Qg(e,t){let r=t!==void 0?t:IS(),n=e.explicitToken;if(n!==void 0)return{TAG:"Ok",_0:n};let i=e.authFilePath,o=i!==void 0?i:Bo(),s=r.readCachedToken(e.serviceUrl,o);if(s.TAG!=="Ok")return{TAG:"Error",_0:s._0};let a=s._0,l;if(a!==void 0){let m=await r.validateToken(e.serviceUrl,a.accessToken,e.workspaceSlug,e.channelSlug,e.requiredScopes);if(m.TAG==="Ok")switch(m._0){case"Usable":l={TAG:"Ok",_0:a.accessToken};break;case"Rejected":let f=e.reportRejectedCachedToken;f!==void 0&&f("UnusableRejected"),l={TAG:"Ok",_0:void 0};break;case"NotFound":let g=e.reportRejectedCachedToken;g!==void 0&&g("UnusableNotFound"),l={TAG:"Ok",_0:void 0};break}else l={TAG:"Error",_0:m._0}}else l={TAG:"Ok",_0:void 0};if(l.TAG!=="Ok")return{TAG:"Error",_0:l._0};let c=l._0;if(c!==void 0)return{TAG:"Ok",_0:c};let u=await r.acquireAndCacheToken(e);if(u.TAG!=="Ok")return{TAG:"Error",_0:u._0};let d=u._0;if(e.workspaceSlug===void 0)return{TAG:"Ok",_0:d};let p=await jS(e,r,d);return p.TAG==="Ok"?{TAG:"Ok",_0:d}:{TAG:"Error",_0:p._0}}function MS(){return{readCachedToken:(e,t)=>Ca(e,t,Date.now()),validateTokenOutcome:(e,t,r,n)=>Vi(e,t,r,n,void 0),resolveToken:e=>Qg(e,void 0)}}var DS="missing Linzumi MCP token; run linzumi auth or pass --token";function ZS(e){return"Linzumi MCP token was rejected by the server and re-mint failed: "+e}async function Xg(e,t,r,n,i,o){let s=o!==void 0?o:MS(),a=r!==void 0?r:Bo(),l=t!==void 0?{TAG:"Ok",_0:t}:tt(s.readCachedToken(e,a),h=>ft(h,p=>p.accessToken));if(l.TAG!=="Ok")return{TAG:"Error",_0:l._0};let c=l._0;if(c===void 0)return{TAG:"Error",_0:N(DS)};let u=await s.validateTokenOutcome(e,c,n,i);if(u.TAG!=="Ok")return{TAG:"Error",_0:u._0};switch(u._0){case"Usable":return{TAG:"Ok",_0:c};case"Rejected":case"NotFound":break}let d=await s.resolveToken({serviceUrl:e,explicitToken:void 0,workspaceSlug:n,channelSlug:i,requiredScopes:[],onboarding:void 0,authFilePath:r,callbackHost:void 0,authMode:void 0,reportRejectedCachedToken:void 0});return d.TAG==="Ok"?{TAG:"Ok",_0:d._0}:{TAG:"Error",_0:N(ZS(d._0.summary))}}var _={};zl(_,{BRAND:()=>f$,DIRTY:()=>Kn,EMPTY_PATH:()=>FS,INVALID:()=>q,NEVER:()=>H$,OK:()=>ht,ParseStatus:()=>nt,Schema:()=>W,ZodAny:()=>xn,ZodArray:()=>en,ZodBigInt:()=>Xn,ZodBoolean:()=>Yn,ZodBranded:()=>Qo,ZodCatch:()=>ui,ZodDate:()=>ei,ZodDefault:()=>li,ZodDiscriminatedUnion:()=>Da,ZodEffects:()=>er,ZodEnum:()=>ai,ZodError:()=>Pt,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>qa,ZodIntersection:()=>ii,ZodIssueCode:()=>$,ZodLazy:()=>oi,ZodLiteral:()=>si,ZodMap:()=>Hi,ZodNaN:()=>Qi,ZodNativeEnum:()=>ci,ZodNever:()=>pr,ZodNull:()=>ri,ZodNullable:()=>Mr,ZodNumber:()=>Qn,ZodObject:()=>Rt,ZodOptional:()=>Ct,ZodParsedType:()=>A,ZodPipeline:()=>Xo,ZodPromise:()=>kn,ZodReadonly:()=>di,ZodRecord:()=>Za,ZodSchema:()=>W,ZodSet:()=>Ki,ZodString:()=>wn,ZodSymbol:()=>Ji,ZodTransformer:()=>er,ZodTuple:()=>Nr,ZodType:()=>W,ZodUndefined:()=>ti,ZodUnion:()=>ni,ZodUnknown:()=>Yr,ZodVoid:()=>Wi,addIssueToContext:()=>z,any:()=>w$,array:()=>$$,bigint:()=>g$,boolean:()=>l_,coerce:()=>W$,custom:()=>s_,date:()=>_$,datetimeRegex:()=>i_,defaultErrorMap:()=>Qr,discriminatedUnion:()=>E$,effect:()=>q$,enum:()=>M$,function:()=>I$,getErrorMap:()=>Fi,getParsedType:()=>jr,instanceof:()=>p$,intersection:()=>A$,isAborted:()=>Na,isAsync:()=>Gi,isDirty:()=>Ma,isValid:()=>bn,late:()=>m$,lazy:()=>j$,literal:()=>N$,makeIssue:()=>Ko,map:()=>C$,nan:()=>h$,nativeEnum:()=>D$,never:()=>k$,null:()=>b$,nullable:()=>V$,number:()=>c_,object:()=>gu,objectUtil:()=>mu,oboolean:()=>J$,onumber:()=>B$,optional:()=>L$,ostring:()=>G$,pipeline:()=>F$,preprocess:()=>U$,promise:()=>Z$,quotelessJson:()=>LS,record:()=>P$,set:()=>R$,setErrorMap:()=>US,strictObject:()=>T$,string:()=>a_,symbol:()=>y$,transformer:()=>q$,tuple:()=>O$,undefined:()=>v$,union:()=>z$,unknown:()=>x$,util:()=>Y,void:()=>S$});var Y;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return e.objectValues(s)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},e.find=(i,o)=>{for(let s of i)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Y||(Y={}));var mu;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(mu||(mu={}));var A=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),jr=e=>{switch(typeof e){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(e)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(e)?A.array:e===null?A.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?A.promise:typeof Map<"u"&&e instanceof Map?A.map:typeof Set<"u"&&e instanceof Set?A.set:typeof Date<"u"&&e instanceof Date?A.date:A.object;default:return A.unknown}};var $=Y.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),LS=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Pt=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,l=0;for(;l<s.path.length;){let c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Y.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Pt.create=e=>new Pt(e);var VS=(e,t)=>{let r;switch(e.code){case $.invalid_type:e.received===A.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case $.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Y.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:r=`Unrecognized key(s) in object: ${Y.joinValues(e.keys,", ")}`;break;case $.invalid_union:r="Invalid input";break;case $.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Y.joinValues(e.options)}`;break;case $.invalid_enum_value:r=`Invalid enum value. Expected ${Y.joinValues(e.options)}, received '${e.received}'`;break;case $.invalid_arguments:r="Invalid function arguments";break;case $.invalid_return_type:r="Invalid function return type";break;case $.invalid_date:r="Invalid date";break;case $.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Y.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case $.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case $.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case $.custom:r="Invalid input";break;case $.invalid_intersection_types:r="Intersection results could not be merged";break;case $.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case $.not_finite:r="Number must be finite";break;default:r=t.defaultError,Y.assertNever(e)}return{message:r}},Qr=VS;var Yg=Qr;function US(e){Yg=e}function Fi(){return Yg}var Ko=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",l=n.filter(c=>!!c).slice().reverse();for(let c of l)a=c(s,{data:t,defaultError:a}).message;return{...i,path:o,message:a}},FS=[];function z(e,t){let r=Fi(),n=Ko({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Qr?void 0:Qr].filter(i=>!!i)});e.common.issues.push(n)}var nt=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return q;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return q;o.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:t.value,value:n}}},q=Object.freeze({status:"aborted"}),Kn=e=>({status:"dirty",value:e}),ht=e=>({status:"valid",value:e}),Na=e=>e.status==="aborted",Ma=e=>e.status==="dirty",bn=e=>e.status==="valid",Gi=e=>typeof Promise<"u"&&e instanceof Promise;var P;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(P||(P={}));var Yt=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},e_=(e,t)=>{if(bn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Pt(e.common.issues);return this._error=r,this._error}}};function G(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,a)=>{let{message:l}=e;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??r??a.defaultError}},description:i}}var W=class{get description(){return this._def.description}_getType(t){return jr(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:jr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new nt,ctx:{common:t.parent.common,data:t.data,parsedType:jr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(Gi(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:jr(t)},i=this._parseSync({data:t,path:n.path,parent:n});return e_(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:jr(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return bn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>bn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:jr(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(Gi(i)?i:Promise.resolve(i));return e_(n,o)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=t(i),a=()=>o.addIssue({code:$.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new er({schema:this,typeName:T.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Ct.create(this,this._def)}nullable(){return Mr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return en.create(this)}promise(){return kn.create(this,this._def)}or(t){return ni.create([this,t],this._def)}and(t){return ii.create(this,t,this._def)}transform(t){return new er({...G(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new li({...G(this._def),innerType:this,defaultValue:r,typeName:T.ZodDefault})}brand(){return new Qo({typeName:T.ZodBranded,type:this,...G(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new ui({...G(this._def),innerType:this,catchValue:r,typeName:T.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Xo.create(this,t)}readonly(){return di.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},GS=/^c[^\s-]{8,}$/i,BS=/^[0-9a-z]+$/,JS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,WS=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,HS=/^[a-z0-9_-]{21}$/i,KS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,QS=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,XS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,YS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",pu,e$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,t$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,r$=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,n$=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,i$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,o$=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,r_="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",s$=new RegExp(`^${r_}$`);function n_(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function a$(e){return new RegExp(`^${n_(e)}$`)}function i_(e){let t=`${r_}T${n_(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function c$(e,t){return!!((t==="v4"||!t)&&e$.test(e)||(t==="v6"||!t)&&r$.test(e))}function l$(e,t){if(!KS.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function u$(e,t){return!!((t==="v4"||!t)&&t$.test(e)||(t==="v6"||!t)&&n$.test(e))}var wn=class e extends W{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==A.string){let o=this._getOrReturnCtx(t);return z(o,{code:$.invalid_type,expected:A.string,received:o.parsedType}),q}let n=new nt,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),z(i,{code:$.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),z(i,{code:$.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=t.data.length>o.value,a=t.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(t,i),s?z(i,{code:$.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&z(i,{code:$.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")XS.test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"email",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")pu||(pu=new RegExp(YS,"u")),pu.test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"emoji",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")WS.test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"uuid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")HS.test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"nanoid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")GS.test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"cuid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")BS.test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"cuid2",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")JS.test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"ulid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),z(i,{validation:"url",code:$.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"regex",code:$.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),z(i,{code:$.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),z(i,{code:$.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),z(i,{code:$.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?i_(o).test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{code:$.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?s$.test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{code:$.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?a$(o).test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{code:$.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?QS.test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"duration",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?c$(t.data,o.version)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"ip",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?l$(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"jwt",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?u$(t.data,o.version)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"cidr",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?i$.test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"base64",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?o$.test(t.data)||(i=this._getOrReturnCtx(t,i),z(i,{validation:"base64url",code:$.invalid_string,message:o.message}),n.dirty()):Y.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:$.invalid_string,...P.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...P.errToObj(t)})}url(t){return this._addCheck({kind:"url",...P.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...P.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...P.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...P.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...P.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...P.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...P.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...P.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...P.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...P.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...P.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...P.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...P.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...P.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...P.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...P.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...P.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...P.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...P.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...P.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...P.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...P.errToObj(r)})}nonempty(t){return this.min(1,P.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};wn.create=e=>new wn({checks:[],typeName:T.ZodString,coerce:e?.coerce??!1,...G(e)});function d$(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return o%s/10**i}var Qn=class e extends W{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==A.number){let o=this._getOrReturnCtx(t);return z(o,{code:$.invalid_type,expected:A.number,received:o.parsedType}),q}let n,i=new nt;for(let o of this._def.checks)o.kind==="int"?Y.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),z(n,{code:$.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),z(n,{code:$.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),z(n,{code:$.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?d$(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),z(n,{code:$.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),z(n,{code:$.not_finite,message:o.message}),i.dirty()):Y.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,P.toString(r))}gt(t,r){return this.setLimit("min",t,!1,P.toString(r))}lte(t,r){return this.setLimit("max",t,!0,P.toString(r))}lt(t,r){return this.setLimit("max",t,!1,P.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:P.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:P.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:P.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:P.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Y.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};Qn.create=e=>new Qn({checks:[],typeName:T.ZodNumber,coerce:e?.coerce||!1,...G(e)});var Xn=class e extends W{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==A.bigint)return this._getInvalidInput(t);let n,i=new nt;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),z(n,{code:$.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),z(n,{code:$.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),z(n,{code:$.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Y.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return z(r,{code:$.invalid_type,expected:A.bigint,received:r.parsedType}),q}gte(t,r){return this.setLimit("min",t,!0,P.toString(r))}gt(t,r){return this.setLimit("min",t,!1,P.toString(r))}lte(t,r){return this.setLimit("max",t,!0,P.toString(r))}lt(t,r){return this.setLimit("max",t,!1,P.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:P.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:P.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Xn.create=e=>new Xn({checks:[],typeName:T.ZodBigInt,coerce:e?.coerce??!1,...G(e)});var Yn=class extends W{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==A.boolean){let n=this._getOrReturnCtx(t);return z(n,{code:$.invalid_type,expected:A.boolean,received:n.parsedType}),q}return ht(t.data)}};Yn.create=e=>new Yn({typeName:T.ZodBoolean,coerce:e?.coerce||!1,...G(e)});var ei=class e extends W{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==A.date){let o=this._getOrReturnCtx(t);return z(o,{code:$.invalid_type,expected:A.date,received:o.parsedType}),q}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return z(o,{code:$.invalid_date}),q}let n=new nt,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),z(i,{code:$.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),z(i,{code:$.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Y.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:P.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:P.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};ei.create=e=>new ei({checks:[],coerce:e?.coerce||!1,typeName:T.ZodDate,...G(e)});var Ji=class extends W{_parse(t){if(this._getType(t)!==A.symbol){let n=this._getOrReturnCtx(t);return z(n,{code:$.invalid_type,expected:A.symbol,received:n.parsedType}),q}return ht(t.data)}};Ji.create=e=>new Ji({typeName:T.ZodSymbol,...G(e)});var ti=class extends W{_parse(t){if(this._getType(t)!==A.undefined){let n=this._getOrReturnCtx(t);return z(n,{code:$.invalid_type,expected:A.undefined,received:n.parsedType}),q}return ht(t.data)}};ti.create=e=>new ti({typeName:T.ZodUndefined,...G(e)});var ri=class extends W{_parse(t){if(this._getType(t)!==A.null){let n=this._getOrReturnCtx(t);return z(n,{code:$.invalid_type,expected:A.null,received:n.parsedType}),q}return ht(t.data)}};ri.create=e=>new ri({typeName:T.ZodNull,...G(e)});var xn=class extends W{constructor(){super(...arguments),this._any=!0}_parse(t){return ht(t.data)}};xn.create=e=>new xn({typeName:T.ZodAny,...G(e)});var Yr=class extends W{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ht(t.data)}};Yr.create=e=>new Yr({typeName:T.ZodUnknown,...G(e)});var pr=class extends W{_parse(t){let r=this._getOrReturnCtx(t);return z(r,{code:$.invalid_type,expected:A.never,received:r.parsedType}),q}};pr.create=e=>new pr({typeName:T.ZodNever,...G(e)});var Wi=class extends W{_parse(t){if(this._getType(t)!==A.undefined){let n=this._getOrReturnCtx(t);return z(n,{code:$.invalid_type,expected:A.void,received:n.parsedType}),q}return ht(t.data)}};Wi.create=e=>new Wi({typeName:T.ZodVoid,...G(e)});var en=class e extends W{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==A.array)return z(r,{code:$.invalid_type,expected:A.array,received:r.parsedType}),q;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(z(r,{code:s?$.too_big:$.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(z(r,{code:$.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(z(r,{code:$.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new Yt(r,s,r.path,a)))).then(s=>nt.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Yt(r,s,r.path,a)));return nt.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:P.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:P.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:P.toString(r)}})}nonempty(t){return this.min(1,t)}};en.create=(e,t)=>new en({type:e,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...G(t)});function Bi(e){if(e instanceof Rt){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Ct.create(Bi(n))}return new Rt({...e._def,shape:()=>t})}else return e instanceof en?new en({...e._def,type:Bi(e.element)}):e instanceof Ct?Ct.create(Bi(e.unwrap())):e instanceof Mr?Mr.create(Bi(e.unwrap())):e instanceof Nr?Nr.create(e.items.map(t=>Bi(t))):e}var Rt=class e extends W{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Y.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==A.object){let c=this._getOrReturnCtx(t);return z(c,{code:$.invalid_type,expected:A.object,received:c.parsedType}),q}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof pr&&this._def.unknownKeys==="strip"))for(let c in i.data)s.includes(c)||a.push(c);let l=[];for(let c of s){let u=o[c],d=i.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Yt(i,d,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof pr){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(c==="strict")a.length>0&&(z(i,{code:$.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let d=i.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Yt(i,d,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,h=await u.value;c.push({key:d,value:h,alwaysSet:u.alwaysSet})}return c}).then(c=>nt.mergeObjectSync(n,c)):nt.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return P.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:P.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:T.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of Y.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of Y.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return Bi(this)}partial(t){let r={};for(let n of Y.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of Y.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Ct;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return o_(Y.objectKeys(this.shape))}};Rt.create=(e,t)=>new Rt({shape:()=>e,unknownKeys:"strip",catchall:pr.create(),typeName:T.ZodObject,...G(t)});Rt.strictCreate=(e,t)=>new Rt({shape:()=>e,unknownKeys:"strict",catchall:pr.create(),typeName:T.ZodObject,...G(t)});Rt.lazycreate=(e,t)=>new Rt({shape:e,unknownKeys:"strip",catchall:pr.create(),typeName:T.ZodObject,...G(t)});var ni=class extends W{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new Pt(a.ctx.common.issues));return z(r,{code:$.invalid_union,unionErrors:s}),q}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let l of n){let c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(l=>new Pt(l));return z(r,{code:$.invalid_union,unionErrors:a}),q}}get options(){return this._def.options}};ni.create=(e,t)=>new ni({options:e,typeName:T.ZodUnion,...G(t)});var Xr=e=>e instanceof oi?Xr(e.schema):e instanceof er?Xr(e.innerType()):e instanceof si?[e.value]:e instanceof ai?e.options:e instanceof ci?Y.objectValues(e.enum):e instanceof li?Xr(e._def.innerType):e instanceof ti?[void 0]:e instanceof ri?[null]:e instanceof Ct?[void 0,...Xr(e.unwrap())]:e instanceof Mr?[null,...Xr(e.unwrap())]:e instanceof Qo||e instanceof di?Xr(e.unwrap()):e instanceof ui?Xr(e._def.innerType):[],Da=class e extends W{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==A.object)return z(r,{code:$.invalid_type,expected:A.object,received:r.parsedType}),q;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(z(r,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let s=Xr(o.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,o)}}return new e({typeName:T.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...G(n)})}};function hu(e,t){let r=jr(e),n=jr(t);if(e===t)return{valid:!0,data:e};if(r===A.object&&n===A.object){let i=Y.objectKeys(t),o=Y.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let l=hu(e[a],t[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(r===A.array&&n===A.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let s=e[o],a=t[o],l=hu(s,a);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return r===A.date&&n===A.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var ii=class extends W{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(Na(o)||Na(s))return q;let a=hu(o.value,s.value);return a.valid?((Ma(o)||Ma(s))&&r.dirty(),{status:r.value,value:a.data}):(z(n,{code:$.invalid_intersection_types}),q)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ii.create=(e,t,r)=>new ii({left:e,right:t,typeName:T.ZodIntersection,...G(r)});var Nr=class e extends W{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==A.array)return z(n,{code:$.invalid_type,expected:A.array,received:n.parsedType}),q;if(n.data.length<this._def.items.length)return z(n,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),q;!this._def.rest&&n.data.length>this._def.items.length&&(z(n,{code:$.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Yt(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>nt.mergeArray(r,s)):nt.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Nr.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nr({items:e,typeName:T.ZodTuple,rest:null,...G(t)})};var Za=class e extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==A.object)return z(n,{code:$.invalid_type,expected:A.object,received:n.parsedType}),q;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Yt(n,a,n.path,a)),value:s._parse(new Yt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?nt.mergeObjectAsync(r,i):nt.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof W?new e({keyType:t,valueType:r,typeName:T.ZodRecord,...G(n)}):new e({keyType:wn.create(),valueType:t,typeName:T.ZodRecord,...G(r)})}},Hi=class extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==A.map)return z(n,{code:$.invalid_type,expected:A.map,received:n.parsedType}),q;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,l],c)=>({key:i._parse(new Yt(n,a,n.path,[c,"key"])),value:o._parse(new Yt(n,l,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of s){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return q;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let l of s){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return q;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}}}};Hi.create=(e,t,r)=>new Hi({valueType:t,keyType:e,typeName:T.ZodMap,...G(r)});var Ki=class e extends W{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==A.set)return z(n,{code:$.invalid_type,expected:A.set,received:n.parsedType}),q;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(z(n,{code:$.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(z(n,{code:$.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(l){let c=new Set;for(let u of l){if(u.status==="aborted")return q;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}let a=[...n.data.values()].map((l,c)=>o._parse(new Yt(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:P.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:P.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Ki.create=(e,t)=>new Ki({valueType:e,minSize:null,maxSize:null,typeName:T.ZodSet,...G(t)});var qa=class e extends W{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==A.function)return z(r,{code:$.invalid_type,expected:A.function,received:r.parsedType}),q;function n(a,l){return Ko({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fi(),Qr].filter(c=>!!c),issueData:{code:$.invalid_arguments,argumentsError:l}})}function i(a,l){return Ko({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fi(),Qr].filter(c=>!!c),issueData:{code:$.invalid_return_type,returnTypeError:l}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof kn){let a=this;return ht(async function(...l){let c=new Pt([]),u=await a._def.args.parseAsync(l,o).catch(p=>{throw c.addIssue(n(l,p)),c}),d=await Reflect.apply(s,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(p=>{throw c.addIssue(i(d,p)),c})})}else{let a=this;return ht(function(...l){let c=a._def.args.safeParse(l,o);if(!c.success)throw new Pt([n(l,c.error)]);let u=Reflect.apply(s,this,c.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new Pt([i(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Nr.create(t).rest(Yr.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||Nr.create([]).rest(Yr.create()),returns:r||Yr.create(),typeName:T.ZodFunction,...G(n)})}},oi=class extends W{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};oi.create=(e,t)=>new oi({getter:e,typeName:T.ZodLazy,...G(t)});var si=class extends W{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return z(r,{received:r.data,code:$.invalid_literal,expected:this._def.value}),q}return{status:"valid",value:t.data}}get value(){return this._def.value}};si.create=(e,t)=>new si({value:e,typeName:T.ZodLiteral,...G(t)});function o_(e,t){return new ai({values:e,typeName:T.ZodEnum,...G(t)})}var ai=class e extends W{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return z(r,{expected:Y.joinValues(n),received:r.parsedType,code:$.invalid_type}),q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return z(r,{received:r.data,code:$.invalid_enum_value,options:n}),q}return ht(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};ai.create=o_;var ci=class extends W{_parse(t){let r=Y.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==A.string&&n.parsedType!==A.number){let i=Y.objectValues(r);return z(n,{expected:Y.joinValues(i),received:n.parsedType,code:$.invalid_type}),q}if(this._cache||(this._cache=new Set(Y.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Y.objectValues(r);return z(n,{received:n.data,code:$.invalid_enum_value,options:i}),q}return ht(t.data)}get enum(){return this._def.values}};ci.create=(e,t)=>new ci({values:e,typeName:T.ZodNativeEnum,...G(t)});var kn=class extends W{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==A.promise&&r.common.async===!1)return z(r,{code:$.invalid_type,expected:A.promise,received:r.parsedType}),q;let n=r.parsedType===A.promise?r.data:Promise.resolve(r.data);return ht(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};kn.create=(e,t)=>new kn({type:e,typeName:T.ZodPromise,...G(t)});var er=class extends W{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===T.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s=>{z(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return q;let l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?q:l.status==="dirty"?Kn(l.value):r.value==="dirty"?Kn(l.value):l});{if(r.value==="aborted")return q;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?q:a.status==="dirty"?Kn(a.value):r.value==="dirty"?Kn(a.value):a}}if(i.type==="refinement"){let s=a=>{let l=i.refinement(a,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?q:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?q:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!bn(s))return q;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>bn(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):q);Y.assertNever(i)}};er.create=(e,t,r)=>new er({schema:e,typeName:T.ZodEffects,effect:t,...G(r)});er.createWithPreprocess=(e,t,r)=>new er({schema:t,effect:{type:"preprocess",transform:e},typeName:T.ZodEffects,...G(r)});var Ct=class extends W{_parse(t){return this._getType(t)===A.undefined?ht(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ct.create=(e,t)=>new Ct({innerType:e,typeName:T.ZodOptional,...G(t)});var Mr=class extends W{_parse(t){return this._getType(t)===A.null?ht(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Mr.create=(e,t)=>new Mr({innerType:e,typeName:T.ZodNullable,...G(t)});var li=class extends W{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===A.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};li.create=(e,t)=>new li({innerType:e,typeName:T.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...G(t)});var ui=class extends W{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Gi(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Pt(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Pt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ui.create=(e,t)=>new ui({innerType:e,typeName:T.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...G(t)});var Qi=class extends W{_parse(t){if(this._getType(t)!==A.nan){let n=this._getOrReturnCtx(t);return z(n,{code:$.invalid_type,expected:A.nan,received:n.parsedType}),q}return{status:"valid",value:t.data}}};Qi.create=e=>new Qi({typeName:T.ZodNaN,...G(e)});var f$=Symbol("zod_brand"),Qo=class extends W{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Xo=class e extends W{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?q:o.status==="dirty"?(r.dirty(),Kn(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?q:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:T.ZodPipeline})}},di=class extends W{_parse(t){let r=this._def.innerType._parse(t),n=i=>(bn(i)&&(i.value=Object.freeze(i.value)),i);return Gi(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};di.create=(e,t)=>new di({innerType:e,typeName:T.ZodReadonly,...G(t)});function t_(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function s_(e,t={},r){return e?xn.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=t_(t,n),l=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:l})}});if(!o){let s=t_(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):xn.create()}var m$={object:Rt.lazycreate},T;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(T||(T={}));var p$=(e,t={message:`Input not instance of ${e.name}`})=>s_(r=>r instanceof e,t),a_=wn.create,c_=Qn.create,h$=Qi.create,g$=Xn.create,l_=Yn.create,_$=ei.create,y$=Ji.create,v$=ti.create,b$=ri.create,w$=xn.create,x$=Yr.create,k$=pr.create,S$=Wi.create,$$=en.create,gu=Rt.create,T$=Rt.strictCreate,z$=ni.create,E$=Da.create,A$=ii.create,O$=Nr.create,P$=Za.create,C$=Hi.create,R$=Ki.create,I$=qa.create,j$=oi.create,N$=si.create,M$=ai.create,D$=ci.create,Z$=kn.create,q$=er.create,L$=Ct.create,V$=Mr.create,U$=er.createWithPreprocess,F$=Xo.create,G$=()=>a_().optional(),B$=()=>c_().optional(),J$=()=>l_().optional(),W$={string:(e=>wn.create({...e,coerce:!0})),number:(e=>Qn.create({...e,coerce:!0})),boolean:(e=>Yn.create({...e,coerce:!0})),bigint:(e=>Xn.create({...e,coerce:!0})),date:(e=>ei.create({...e,coerce:!0}))};var H$=q;import*as yu from"node:fs";import*as __ from"node:os";import*as It from"node:path";import*as Xi from"node:fs/promises";function d_(e,t){return"Kandan attachment path must resolve inside an allowed upload root ("+e+"): "+t}function f_(e){return"Kandan attachment upload path must not include hidden path segments: "+e}function _u(e){return"Kandan attachment upload requires a known media/document type or text content (binary content is not allowed): "+e}var m_="LINZUMI_THREAD_RUNNER_KANDAN_THREAD_ID";var p_="Kandan attachment path must not be empty";function it(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function Yo(e){if(Array.isArray(e))return e}function qe(e){if(e!==void 0&&typeof e=="string"&&e.trim()!=="")return e.trim()}function K$(e){if(e!==void 0&&typeof e=="number"&&Number.isInteger(e))return e}function vu(e){if(e!==void 0)return e}function gt(e){let t={};t.type="text",t.text=JSON.stringify(e,void 0,2);let r={};return r.content=[t],r.structuredContent=e,r}var Q$="failed: ([a-z0-9_]+)(?: detail=(.+))?$";async function bu(e){let t;try{t=await e}catch(r){let n=ee(r),i=fn(n),o=new RegExp(Q$).exec(i);if(o==null){let d={};return d.error=i,gt(d)}let s=o.slice(1),a=s[0],l;if(a!==void 0){let d=de(a);l=d!==void 0?d:i}else l=i;let c={};c.error=l;let u=s[1];if(u!==void 0){let d=de(u);d!==void 0&&(c.detail=d)}return gt(c)}return gt(t)}function y_(e){let t=$r(e);if(t===void 0)return Cl(e);let r=de(t),n=Tr(r);return n!==void 0&&n.includes("channel_required")?Rh(new Error(n+". Remediation: pass the channel slug in the `channel` parameter, or set target.thread_id to a Linzumi thread you can access (the server resolves the thread's channel). The files were NOT attached; retry with a channel or thread instead of leaving them on disk.",{cause:r})):Ih(r)}function tn(e){let t={};return Object.entries(e).forEach(r=>{t[r[0]]=r[1]}),t}function wu(e,t){if(qe(e.thread_id)!==void 0||t===void 0)return e;let n=()=>{let s=tn(e);return s.thread_id=t,s},i=e.message_seq;if(i!==void 0&&typeof i<"u")return n();let o=qe(e.kind);if(o===void 0)return e;switch(o){case"latest_assistant_message":case"message_seq":case"new_message":return n();default:return e}}function tr(e,t){if(qe(e.thread_id)!==void 0||t===void 0)return e;let n=tn(e);return n.thread_id=t,n}function La(e,t){let r=Ci(t);if(r!==void 0)return de(r).toString();let n=e.replace(new RegExp("^wss://"),"https://").replace(new RegExp("^ws://"),"http://"),i=Br(t,n);return i.TAG==="Ok"?i._0.toString():je(i._0)}function X$(e,t){let r=qe(t.inline_url),n=qe(t.carousel_url),i=tn(t);return r!==void 0&&(i.inline_url=La(e,r)),n!==void 0&&(i.carousel_url=La(e,n)),i}function Y$(e,t){if(typeof t!="object"||t===null||Array.isArray(t))return t;let r=qe(t.url),n=it(t.image_variants),i=tn(t);return r!==void 0&&(i.url=La(e,r)),n!==void 0&&(i.image_variants=X$(e,n)),i}function g_(e,t){let r=Yo(t.attachments);if(r===void 0)return t;let n=tn(t);return n.attachments=r.map(i=>Y$(e,i)),n}function xu(e,t){let r=it(t.message),n=it(t.target_message);if(r===void 0&&n===void 0)return t;let i=tn(t);return r!==void 0&&(i.message=g_(e,r)),n!==void 0&&(i.target_message=g_(e,n)),i}var eT=[".csv",".diff",".gif",".htm",".html",".jpeg",".jpg",".json",".jsonl",".log",".md",".mp4",".patch",".pdf",".png",".svg",".txt",".webm",".webp",".xml",".zip"];async function tT(e){let t=[{path:e,label:"runner cwd"}],r=ft(process.env.HOME,o=>o.trim()),n=It.resolve(r!==void 0&&r!==""?r:__.homedir(),"Downloads"),i;try{i=await Xi.realpath(n)}catch{return t}return t.some(o=>o.path===i)||t.push({path:i,label:"~/Downloads"}),t}function rT(e,t){let r=It.relative(e,t);return r===""?!0:r.startsWith("..")?!1:!It.isAbsolute(r)}async function nT(e,t){if(t==="")return je(p_);let r=It.isAbsolute(t)?It.resolve(t):It.resolve(e,t);return await Xi.realpath(r)}async function iT(e,t){if(!(await e.stat()).isFile())return je("Kandan attachment path is not a file: "+t);let n=It.extname(t).toLowerCase();if(eT.includes(n))return{classification:"KnownType",bytes:await e.readFile()};let i=Buffer.alloc(8192),s=(await e.read(i,0,8192,0)).bytesRead;if(i.subarray(0,s).includes(0))return je(_u(t));let a=await e.readFile();return a.subarray(0,8192).includes(0)?je(_u(t)):{classification:"TextContent",bytes:a}}async function oT(e,t){let r=e.find(i=>rT(i.path,t));if(r!==void 0){if(It.relative(r.path,t).split(new RegExp("[\\\\/]+","g")).find(u=>u!==void 0?u.startsWith("."):!1)!==void 0)return je(f_(t));let s=await Xi.open(t,yu.constants.O_RDONLY|yu.constants.O_NONBLOCK),a,l=0,c;try{c=await iT(s,t),l=1}catch(u){a={TAG:"Error",_0:ee(u)}}return l===1&&(a={TAG:"Ok",_0:c}),await s.close(),a.TAG==="Ok"?a._0:Cl(a._0)}let n=e.map(i=>i.label).join(", ");return je(d_(n,t))}function sT(e){let t=e.toLowerCase();return t.endsWith(".png")?"image/png":t.endsWith(".jpg")||t.endsWith(".jpeg")?"image/jpeg":t.endsWith(".gif")?"image/gif":t.endsWith(".webp")?"image/webp":t.endsWith(".csv")?"text/csv":t.endsWith(".json")?"application/json":t.endsWith(".md")||t.endsWith(".txt")||t.endsWith(".log")?"text/plain":"application/octet-stream"}function aT(e,t){if(e.toLowerCase().endsWith(".py"))return"text/x-python";let n=sT(e);return t==="KnownType"||n!=="application/octet-stream"?n:"text/plain"}async function v_(e,t){let r=await Xi.realpath(e),n=await tT(r),i=await nT(r,t),o=await oT(n,i);return{fileName:It.basename(i),contentType:aT(i,o.classification),sizeBytes:o.bytes.byteLength,bytes:o.bytes}}async function b_(e,t,r,n,i){let o={};return o["content-type"]=n,await pa.binary(La(e,t),{method:r,headers:o,body:jh(i)})}async function w_(e){let t=await Promise.all(e.files.map(m=>v_(e.cwd,m))),r=qe(e.target.thread_id),n={},i=e.workspace;i!==void 0&&(n.workspace=i);let o=e.channel;o!==void 0&&(n.channel=o),r!==void 0&&(n.thread_id=r),n.files=t.map(m=>{let f={};return f.file_name=m.fileName,f.content_type=m.contentType,f.size_bytes=m.sizeBytes,f});let s=await e.client.prepareMessageUploads(n),a=Yo(s.uploads),l=a!==void 0?a:[];l.length===t.length||je("Linzumi upload prepare response count mismatch"),await Promise.all(t.map(async(m,f)=>{let g=it(l[f]),y=qe(He(g,S=>S.upload_url)),v=qe(He(g,S=>S.upload_method)),b=v!==void 0?v:"PUT";if(y===void 0)return je("Linzumi upload prepare response missing upload_url");let w=await b_(e.serviceUrl,y,b,m.contentType,m.bytes);if(!w.ok)return je("Linzumi upload failed for "+m.fileName+": "+w.status.toString()+" "+w.statusText)}));let c=l.map(m=>{let f=qe(He(it(m),g=>g.file_id));return f!==void 0?f:je("Linzumi upload prepare response missing file_id")}),u={},d=e.workspace;d!==void 0&&(u.workspace=d);let h=e.channel;h!==void 0&&(u.channel=h),r!==void 0&&(u.thread_id=r),u.target=e.target;let p=e.body;return p!==void 0&&(u.body=p),u.uploaded_file_ids=c,await e.client.attachMessageFiles(u)}async function x_(e){let t=await v_(e.cwd,e.file),r={},n=e.workspace;n!==void 0&&(r.workspace=n),r.name=e.name,r.file_name=t.fileName,r.content_type=t.contentType,r.size_bytes=t.sizeBytes;let i=await e.client.prepareCustomEmoji(r),o=it(i.upload),s=qe(He(o,m=>m.upload_url)),a=qe(He(o,m=>m.upload_method)),l=a!==void 0?a:"PUT";if(s===void 0)return je("Linzumi custom emoji prepare response missing upload_url");let c=await b_(e.serviceUrl,s,l,t.contentType,t.bytes);if(c.ok){let m=await c.json();if(typeof m!="object"||m===null||Array.isArray(m))return je("Linzumi custom emoji upload returned non-object JSON");let f=it(m.custom_emoji);if(f===void 0)return je("Linzumi custom emoji upload response missing custom_emoji");let g={};g.ok=!0;let y=i.workspace;g.workspace=y!==void 0?y:void 0,g.emoji=f;let v=qe(m.asset_id);g.asset_id=v!==void 0?v:void 0;let b=K$(f.id);g.id=b!==void 0?b:void 0;let w=qe(f.name);g.name=w!==void 0?w:void 0;let S=qe(f.shortcode);g.shortcode=S!==void 0?S:void 0;let Z=qe(f.image_url);return g.image_url=Z!==void 0?Z:void 0,g}let u=c.status.toString()+" "+c.statusText,h=(await c.text()).trim(),p;if(h==="")p=u;else{let m=0,f;try{f=JSON.parse(h),m=1}catch{p=h}if(m===1)if(typeof f=="object"&&f!==null&&!Array.isArray(f)){let g=f.error;p=typeof g=="string"?g:h}else p=h}return je("Linzumi custom emoji upload failed: "+p)}import*as jt from"node:fs";import*as S_ from"node:os";import*as $_ from"node:net";import*as rr from"node:path";import*as T_ from"node:child_process";function $u(e,t){}function Tu(e){return e==="DesiredRunning"?"running":"stopped"}function z_(e){switch(e){case"Running":return"running";case"Unhealthy":return"unhealthy";case"Exited":return"exited";case"Stopped":return"stopped"}}function cT(){let e=ft(process.env.LINZUMI_DEV_SERVICES_DIR,t=>t.trim());return e!==void 0&&e!==""?e:rr.join(S_.homedir(),".linzumi","dev-services")}function lT(e){let t=e.replace(new RegExp("[^A-Za-z0-9._-]+","g"),"-").replace(new RegExp("^[-.]+|[-.]+$","g"),"").slice(0,80),r=la(e).slice(0,8),n=t===""?"runner":t;return rr.join(cT(),n+"."+r)}function Va(e){let t=e.trim().toLowerCase();if(new RegExp("^[a-z0-9][a-z0-9._-]{0,63}$").test(t)&&!t.includes(".."))return t}function zu(e,t){return rr.join(e,"services",t+".json")}function Eu(e,t){return rr.join(e,"exits",t+".json")}function E_(e,t){return rr.join(e,"logs",t+".log")}function es(e){if(typeof e=="string"&&e!=="")return e}function ts(e){if(e!==void 0&&typeof e=="number"&&isFinite(e))return e}function uT(e){return e!==void 0?Array.isArray(e)?Ft(e,t=>{if(typeof t=="number"&&Number.isInteger(t)&&t>0&&t<=65535)return t}):[]:[]}function dT(e){if(typeof e!="object"||e===null||Array.isArray(e)||!kt(e.version,1))return;let t=es(e.name),r=He(t,Va),n=es(e.command),i=es(e.cwd),o=e.desiredState,s;if(typeof o=="string")switch(o){case"running":s="DesiredRunning";break;case"stopped":s="DesiredStopped";break;default:s=void 0}else s=void 0;let a=ts(e.updatedAtMs),l=es(e.logPath),c=kt(r,t);if(r!==void 0&&c&&n!==void 0&&i!==void 0&&s!==void 0&&a!==void 0&&l!==void 0)return{name:r,command:n,cwd:i,ports:uT(e.ports),restartOnBranchChange:kt(e.restartOnBranchChange,!0),desiredState:s,pid:ts(e.pid),ownerPid:ts(e.ownerPid),startedAtMs:ts(e.startedAtMs),updatedAtMs:a,lastBranch:es(e.lastBranch),logPath:l}}function ku(e){return e!==void 0?e:null}function fT(e){return e!==void 0?e:null}function mT(e){let t={};return t.version=1,t.name=e.name,t.command=e.command,t.cwd=e.cwd,t.ports=e.ports.map(r=>r),t.restartOnBranchChange=e.restartOnBranchChange,t.desiredState=Tu(e.desiredState),t.pid=ku(e.pid),t.ownerPid=ku(e.ownerPid),t.startedAtMs=ku(e.startedAtMs),t.updatedAtMs=e.updatedAtMs,t.lastBranch=fT(e.lastBranch),t.logPath=e.logPath,t}function A_(e,t,r){let n=zu(e,t.name),i=Q(zr(rr.dirname(n)),()=>{let s=n+".tmp";return Q($h(s,JSON.stringify(mT(t))+`
122
- `),()=>ca(s,n))});if(i.TAG==="Ok")return;let o={};o.path=n,o.message=i._0.message,r("dev_services.record_write_failed",o)}function Au(e,t){let r=Va(t);if(r===void 0)return;let n=fr(zu(e,r));if(n.TAG!=="Ok")return;let i;try{i=JSON.parse(n._0)}catch{return}return dT(i)}function pT(e){let t=Ah(rr.join(e,"services"));return t.TAG==="Ok"?Ft(t._0,r=>{if(r.endsWith(".json"))return Au(e,r.slice(0,r.length-5|0))}).toSorted((r,n)=>r.name.localeCompare(n.name)):[]}function O_(e,t){let r=fr(Eu(e,t));if(r.TAG!=="Ok")return;let n;try{n=JSON.parse(r._0)}catch{return}if(typeof n!="object"||n===null||Array.isArray(n))return;let i=ts(n.atMs);if(i===void 0)return;let o=n.code,s;s=typeof o=="number"?o:void 0;let a=n.signal,l;return l=typeof a=="string"?a:void 0,{code:s,signal:l,atMs:i}}function hT(e){let t={};return t.command=e.command,t.args=e.args.map(r=>r),t.cwd=e.cwd,t.ownerPid=e.ownerPid,t.pollIntervalMs=e.pollIntervalMs,t.exitStatusPath=e.exitStatusPath,JSON.stringify(t)}function gT(e,t){return{command:e,args:["-e",`
122
+ `}}function DT(e){return new Promise((t,r)=>{setTimeout(()=>t(),e|0)})}function ZT(e){return{startDeviceAuthorization:t=>j_(t.httpBaseUrl,t.workspaceSlug,t.channelSlug,t.onboarding,t.identity),pollDeviceCodeForToken:t=>N_(t.httpBaseUrl,t.deviceCode,t.expiresInSeconds,void 0),now:()=>Date.now(),sleep:DT,report:e,log:(t,r)=>{}}}var LT="local runner device authorization was denied - a signed-in user rejected this computer";async function D_(e,t,r,n,i,o,s,a){let u=o!==void 0?o:y=>{Yo(y)},c=a!==void 0?a:ZT(y=>u(MT(y))),l=s!==void 0?s:Ot(Ji(process.stderr.isTTY),!0),d=ke(Pt(e),F);if(d.TAG!=="Ok")return{TAG:"Error",_0:d._0};let h=d._0,m=c.now(),p={cycle:0,lastLoudPromptAtMs:void 0,startFailures:0},f=async y=>{let v=await c.pollDeviceCodeForToken({httpBaseUrl:h,deviceCode:y.deviceCode,expiresInSeconds:y.expiresInSeconds});if(typeof v!="object"||v.TAG!=="Transient")return v;let b=v.httpStatus,w=v.reason;c.report({TAG:"TransientFailure",reason:w,waitedMs:c.now()-m});let S={};return S.cycle=p.cycle,S.reason=w,S.httpStatus=b!==void 0?b:null,c.log("device_wait.transient_poll_failure",S),await c.sleep(5e3),await f(y)},g=async()=>{let y=await c.startDeviceAuthorization({httpBaseUrl:h,workspaceSlug:t,channelSlug:r,onboarding:n,identity:i});if(y.TAG==="Ok"){let v=y._0;p.startFailures=0,p.cycle=p.cycle+1|0;let b=NT(p.cycle,c.now(),p.lastLoudPromptAtMs,l),w=0;switch(b){case"DecidePrompt":case"DecideSummary":w=1;break;case"DecideRefreshLine":c.report({TAG:"RefreshLine",cycle:p.cycle,userCode:v.userCode,verificationUri:v.verificationUri,waitedMs:c.now()-m});break;case"DecideSilent":break}if(w===1){p.lastLoudPromptAtMs=c.now();let K=c.now()-m,ce;ce=b==="DecidePrompt"?{TAG:"Prompt",cycle:p.cycle,userCode:v.userCode,verificationUri:v.verificationUri,waitedMs:K}:{TAG:"Summary",cycle:p.cycle,userCode:v.userCode,verificationUri:v.verificationUri,waitedMs:K},c.report(ce)}let S={};S.cycle=p.cycle,S.verificationUri=v.verificationUri,c.log("device_wait.code_issued",S);let q=await f(v);if(typeof q!="object")switch(q){case"CodeExpired":let K={};return K.cycle=p.cycle,K.outcome="code_expired",c.log("device_wait.code_retired",K),await g();case"Denied":return{TAG:"Error",_0:F(LT)};case"Consumed":let ce={};return ce.cycle=p.cycle,ce.outcome="consumed",c.log("device_wait.code_retired",ce),await g()}else switch(q.TAG){case"Token":let K={};return K.cycle=p.cycle,K.waitedMs=c.now()-m,c.log("device_wait.authorized",K),{TAG:"Ok",_0:q._0};case"Rejected":let ce=q.httpStatus,C=q.reason;c.report({TAG:"TransientFailure",reason:I_(C,ce),waitedMs:c.now()-m});let G={};return G.cycle=p.cycle,G.reason=C!==void 0?C:null,G.httpStatus=ce,c.log("device_wait.code_rejected",G),await g();case"Transient":return await g()}}else{let v=y._0;p.startFailures=p.startFailures+1|0;let b=Math.min(6e4,5e3*Math.pow(2,p.startFailures-1|0));c.report({TAG:"StartFailed",reason:v.summary,retryInMs:b});let w={};return w.reason=v.summary,w.retryInMs=b,w.attempt=p.startFailures,c.log("device_wait.start_failed",w),await c.sleep(b),await g()}};return await g()}var UT="linzumi-machine-fingerprint:v1:";var Z_={platform:void 0,execFile:void 0,readFile:void 0,username:void 0};function GT(e,t){return wg(e,t,5e3,1024*1024)}var VT=new RegExp('"IOPlatformUUID"\\s*=\\s*"([0-9A-Fa-f-]{36})"'),BT=new RegExp("^[0-9a-f]{32}$"),JT=["/etc/machine-id","/var/lib/dbus/machine-id"];function WT(e){let t=e!==void 0?e:Z_,r=lt(t.platform,process.platform),n=lt(t.execFile,GT),i=lt(t.readFile,yr);switch(r){case"darwin":let o=n("ioreg",["-rd1","-c","IOPlatformExpertDevice"]);if(o.TAG!=="Ok")return;let s=VT.exec(o._0);if(s==null)return;let a=s.slice(1)[0];if(a===void 0)return;let u=ve(a);return u!==void 0?u.toLowerCase():void 0;case"linux":return zg(JT,void 0,(c,l)=>{if(c!==void 0)return c;let d=i(l);if(d.TAG!=="Ok")return;let h=d._0.trim().toLowerCase();if(BT.test(h))return h});default:return}}function L_(e){return wt(WT(e!==void 0?e:Z_),r=>"mfp-"+Ca(UT+r).slice(0,32))}function KT(e,t){return Y(ke(Pt(e),F),r=>{let n=Wi(r);return n===void 0?{TAG:"Error",_0:F("invalid URL: "+r)}:{TAG:"Ok",_0:"Workspace '"+(t!==void 0?t:"undefined")+"' was not found on "+ve(n).host+". Sign in to the web app to create it, then re-run connect."}})}var QT="local runner browser OAuth is not available in this implementation yet; use --auth-mode device or supply --token";async function XT(e){let t=A_(process.env),r=C_(t,e.serviceUrl,void 0);if(r.TAG!=="Ok")return{TAG:"Error",_0:r._0};let n=r._0,i=L_(void 0),o=q_.hostname(),s={commanderId:n,machineFingerprint:i,hostname:o},a=await D_(e.serviceUrl,e.workspaceSlug,e.channelSlug,e.onboarding,s,void 0,void 0,void 0);if(a.TAG!=="Ok")return{TAG:"Error",_0:a._0};let u=a._0,c=e.authFilePath,l=c!==void 0?c:ps();return tt(Du(e.serviceUrl,u.accessToken,u.expiresInSeconds,l,new Date),d=>u.accessToken)}async function YT(e){let t=e.authMode;return typeof(t!==void 0?t:{TAG:"BrowserMode",callbackHost:e.callbackHost})!="object"?await XT(e):{TAG:"Error",_0:F(QT)}}function e$(){return{readCachedToken:(e,t)=>tc(e,t,Date.now()),validateToken:(e,t,r,n,i)=>io(e,t,r,n,i),acquireAndCacheToken:YT}}async function t$(e,t,r){let n=await t.validateToken(e.serviceUrl,r,e.workspaceSlug,e.channelSlug,e.requiredScopes);if(n.TAG!=="Ok")return{TAG:"Ok",_0:void 0};switch(n._0){case"Usable":case"Rejected":return{TAG:"Ok",_0:void 0};case"NotFound":return Y(KT(e.serviceUrl,e.workspaceSlug),i=>({TAG:"Error",_0:F(i)}))}}async function F_(e,t){let r=t!==void 0?t:e$(),n=e.explicitToken;if(n!==void 0)return{TAG:"Ok",_0:n};let i=e.authFilePath,o=i!==void 0?i:ps(),s=r.readCachedToken(e.serviceUrl,o);if(s.TAG!=="Ok")return{TAG:"Error",_0:s._0};let a=s._0,u;if(a!==void 0){let p=await r.validateToken(e.serviceUrl,a.accessToken,e.workspaceSlug,e.channelSlug,e.requiredScopes);if(p.TAG==="Ok")switch(p._0){case"Usable":u={TAG:"Ok",_0:a.accessToken};break;case"Rejected":let f=e.reportRejectedCachedToken;f!==void 0&&f("UnusableRejected"),u={TAG:"Ok",_0:void 0};break;case"NotFound":let g=e.reportRejectedCachedToken;g!==void 0&&g("UnusableNotFound"),u={TAG:"Ok",_0:void 0};break}else u={TAG:"Error",_0:p._0}}else u={TAG:"Ok",_0:void 0};if(u.TAG!=="Ok")return{TAG:"Error",_0:u._0};let c=u._0;if(c!==void 0)return{TAG:"Ok",_0:c};let l=await r.acquireAndCacheToken(e);if(l.TAG!=="Ok")return{TAG:"Error",_0:l._0};let d=l._0;if(e.workspaceSlug===void 0)return{TAG:"Ok",_0:d};let m=await t$(e,r,d);return m.TAG==="Ok"?{TAG:"Ok",_0:d}:{TAG:"Error",_0:m._0}}function n$(){return{readCachedToken:(e,t)=>tc(e,t,Date.now()),validateTokenOutcome:(e,t,r,n)=>io(e,t,r,n,void 0),resolveToken:e=>F_(e,void 0)}}var i$="missing Linzumi MCP token; run linzumi auth or pass --token";function o$(e){return"Linzumi MCP token was rejected by the server and re-mint failed: "+e}async function U_(e,t,r,n,i,o){let s=o!==void 0?o:n$(),a=r!==void 0?r:ps(),u=t!==void 0?{TAG:"Ok",_0:t}:tt(s.readCachedToken(e,a),h=>wt(h,m=>m.accessToken));if(u.TAG!=="Ok")return{TAG:"Error",_0:u._0};let c=u._0;if(c===void 0)return{TAG:"Error",_0:F(i$)};let l=await s.validateTokenOutcome(e,c,n,i);if(l.TAG!=="Ok")return{TAG:"Error",_0:l._0};switch(l._0){case"Usable":return{TAG:"Ok",_0:c};case"Rejected":case"NotFound":break}let d=await s.resolveToken({serviceUrl:e,explicitToken:void 0,workspaceSlug:n,channelSlug:i,requiredScopes:[],onboarding:void 0,authFilePath:r,callbackHost:void 0,authMode:void 0,reportRejectedCachedToken:void 0});return d.TAG==="Ok"?{TAG:"Ok",_0:d._0}:{TAG:"Error",_0:F(o$(d._0.summary))}}var _={};au(_,{BRAND:()=>C$,DIRTY:()=>ai,EMPTY_PATH:()=>u$,INVALID:()=>B,NEVER:()=>hE,OK:()=>kt,ParseStatus:()=>dt,Schema:()=>re,ZodAny:()=>Pn,ZodArray:()=>an,ZodBigInt:()=>li,ZodBoolean:()=>ui,ZodBranded:()=>vs,ZodCatch:()=>wi,ZodDate:()=>di,ZodDefault:()=>bi,ZodDiscriminatedUnion:()=>ac,ZodEffects:()=>or,ZodEnum:()=>yi,ZodError:()=>Dt,ZodFirstPartyTypeKind:()=>E,ZodFunction:()=>lc,ZodIntersection:()=>hi,ZodIssueCode:()=>T,ZodLazy:()=>gi,ZodLiteral:()=>_i,ZodMap:()=>fo,ZodNaN:()=>po,ZodNativeEnum:()=>vi,ZodNever:()=>wr,ZodNull:()=>mi,ZodNullable:()=>Ur,ZodNumber:()=>ci,ZodObject:()=>Lt,ZodOptional:()=>Zt,ZodParsedType:()=>A,ZodPipeline:()=>bs,ZodPromise:()=>Cn,ZodReadonly:()=>xi,ZodRecord:()=>cc,ZodSchema:()=>re,ZodSet:()=>mo,ZodString:()=>An,ZodSymbol:()=>lo,ZodTransformer:()=>or,ZodTuple:()=>Fr,ZodType:()=>re,ZodUndefined:()=>fi,ZodUnion:()=>pi,ZodUnknown:()=>sn,ZodVoid:()=>uo,addIssueToContext:()=>O,any:()=>q$,array:()=>V$,bigint:()=>N$,boolean:()=>ey,coerce:()=>pE,custom:()=>Q_,date:()=>M$,datetimeRegex:()=>H_,defaultErrorMap:()=>nn,discriminatedUnion:()=>W$,effect:()=>sE,enum:()=>nE,function:()=>eE,getErrorMap:()=>so,getParsedType:()=>qr,instanceof:()=>I$,intersection:()=>H$,isAborted:()=>oc,isAsync:()=>ao,isDirty:()=>sc,isValid:()=>On,late:()=>R$,lazy:()=>tE,literal:()=>rE,makeIssue:()=>ys,map:()=>X$,nan:()=>j$,nativeEnum:()=>iE,never:()=>U$,null:()=>L$,nullable:()=>cE,number:()=>Y_,object:()=>Qu,objectUtil:()=>Wu,oboolean:()=>mE,onumber:()=>fE,optional:()=>aE,ostring:()=>dE,pipeline:()=>uE,preprocess:()=>lE,promise:()=>oE,quotelessJson:()=>a$,record:()=>Q$,set:()=>Y$,setErrorMap:()=>l$,strictObject:()=>B$,string:()=>X_,symbol:()=>D$,transformer:()=>sE,tuple:()=>K$,undefined:()=>Z$,union:()=>J$,unknown:()=>F$,util:()=>se,void:()=>G$});var se;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return e.objectValues(s)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},e.find=(i,o)=>{for(let s of i)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(se||(se={}));var Wu;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Wu||(Wu={}));var A=se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),qr=e=>{switch(typeof e){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(e)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(e)?A.array:e===null?A.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?A.promise:typeof Map<"u"&&e instanceof Map?A.map:typeof Set<"u"&&e instanceof Set?A.set:typeof Date<"u"&&e instanceof Date?A.date:A.object;default:return A.unknown}};var T=se.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),a$=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Dt=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,u=0;for(;u<s.path.length;){let c=s.path[u];u===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(s))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,se.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Dt.create=e=>new Dt(e);var c$=(e,t)=>{let r;switch(e.code){case T.invalid_type:e.received===A.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case T.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,se.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:r=`Unrecognized key(s) in object: ${se.joinValues(e.keys,", ")}`;break;case T.invalid_union:r="Invalid input";break;case T.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${se.joinValues(e.options)}`;break;case T.invalid_enum_value:r=`Invalid enum value. Expected ${se.joinValues(e.options)}, received '${e.received}'`;break;case T.invalid_arguments:r="Invalid function arguments";break;case T.invalid_return_type:r="Invalid function return type";break;case T.invalid_date:r="Invalid date";break;case T.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:se.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case T.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case T.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case T.custom:r="Invalid input";break;case T.invalid_intersection_types:r="Intersection results could not be merged";break;case T.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case T.not_finite:r="Number must be finite";break;default:r=t.defaultError,se.assertNever(e)}return{message:r}},nn=c$;var G_=nn;function l$(e){G_=e}function so(){return G_}var ys=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)a=c(s,{data:t,defaultError:a}).message;return{...i,path:o,message:a}},u$=[];function O(e,t){let r=so(),n=ys({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===nn?void 0:nn].filter(i=>!!i)});e.common.issues.push(n)}var dt=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return B;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return B;o.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:t.value,value:n}}},B=Object.freeze({status:"aborted"}),ai=e=>({status:"dirty",value:e}),kt=e=>({status:"valid",value:e}),oc=e=>e.status==="aborted",sc=e=>e.status==="dirty",On=e=>e.status==="valid",ao=e=>typeof Promise<"u"&&e instanceof Promise;var M;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(M||(M={}));var ir=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},V_=(e,t)=>{if(On(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Dt(e.common.issues);return this._error=r,this._error}}};function ee(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,a)=>{let{message:u}=e;return s.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:u??r??a.defaultError}},description:i}}var re=class{get description(){return this._def.description}_getType(t){return qr(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:qr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new dt,ctx:{common:t.parent.common,data:t.data,parsedType:qr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(ao(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:qr(t)},i=this._parseSync({data:t,path:n.path,parent:n});return V_(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:qr(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return On(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>On(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:qr(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(ao(i)?i:Promise.resolve(i));return V_(n,o)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=t(i),a=()=>o.addIssue({code:T.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new or({schema:this,typeName:E.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Zt.create(this,this._def)}nullable(){return Ur.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return an.create(this)}promise(){return Cn.create(this,this._def)}or(t){return pi.create([this,t],this._def)}and(t){return hi.create(this,t,this._def)}transform(t){return new or({...ee(this._def),schema:this,typeName:E.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new bi({...ee(this._def),innerType:this,defaultValue:r,typeName:E.ZodDefault})}brand(){return new vs({typeName:E.ZodBranded,type:this,...ee(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new wi({...ee(this._def),innerType:this,catchValue:r,typeName:E.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return bs.create(this,t)}readonly(){return xi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},d$=/^c[^\s-]{8,}$/i,f$=/^[0-9a-z]+$/,m$=/^[0-9A-HJKMNP-TV-Z]{26}$/i,p$=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,h$=/^[a-z0-9_-]{21}$/i,g$=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,_$=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,y$=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,v$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Hu,b$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,w$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,x$=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,k$=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,S$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,T$=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,J_="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",$$=new RegExp(`^${J_}$`);function W_(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function E$(e){return new RegExp(`^${W_(e)}$`)}function H_(e){let t=`${J_}T${W_(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function z$(e,t){return!!((t==="v4"||!t)&&b$.test(e)||(t==="v6"||!t)&&x$.test(e))}function O$(e,t){if(!g$.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function A$(e,t){return!!((t==="v4"||!t)&&w$.test(e)||(t==="v6"||!t)&&k$.test(e))}var An=class e extends re{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==A.string){let o=this._getOrReturnCtx(t);return O(o,{code:T.invalid_type,expected:A.string,received:o.parsedType}),B}let n=new dt,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),O(i,{code:T.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),O(i,{code:T.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=t.data.length>o.value,a=t.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(t,i),s?O(i,{code:T.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&O(i,{code:T.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")y$.test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"email",code:T.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Hu||(Hu=new RegExp(v$,"u")),Hu.test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"emoji",code:T.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")p$.test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"uuid",code:T.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")h$.test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"nanoid",code:T.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")d$.test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"cuid",code:T.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")f$.test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"cuid2",code:T.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")m$.test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"ulid",code:T.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),O(i,{validation:"url",code:T.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"regex",code:T.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),O(i,{code:T.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),O(i,{code:T.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),O(i,{code:T.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?H_(o).test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{code:T.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?$$.test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{code:T.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?E$(o).test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{code:T.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?_$.test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"duration",code:T.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?z$(t.data,o.version)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"ip",code:T.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?O$(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"jwt",code:T.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?A$(t.data,o.version)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"cidr",code:T.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?S$.test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"base64",code:T.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?T$.test(t.data)||(i=this._getOrReturnCtx(t,i),O(i,{validation:"base64url",code:T.invalid_string,message:o.message}),n.dirty()):se.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:T.invalid_string,...M.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...M.errToObj(t)})}url(t){return this._addCheck({kind:"url",...M.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...M.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...M.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...M.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...M.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...M.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...M.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...M.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...M.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...M.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...M.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...M.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...M.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...M.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...M.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...M.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...M.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...M.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...M.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...M.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...M.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...M.errToObj(r)})}nonempty(t){return this.min(1,M.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};An.create=e=>new An({checks:[],typeName:E.ZodString,coerce:e?.coerce??!1,...ee(e)});function P$(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return o%s/10**i}var ci=class e extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==A.number){let o=this._getOrReturnCtx(t);return O(o,{code:T.invalid_type,expected:A.number,received:o.parsedType}),B}let n,i=new dt;for(let o of this._def.checks)o.kind==="int"?se.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),O(n,{code:T.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),O(n,{code:T.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),O(n,{code:T.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?P$(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),O(n,{code:T.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),O(n,{code:T.not_finite,message:o.message}),i.dirty()):se.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,M.toString(r))}gt(t,r){return this.setLimit("min",t,!1,M.toString(r))}lte(t,r){return this.setLimit("max",t,!0,M.toString(r))}lt(t,r){return this.setLimit("max",t,!1,M.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:M.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:M.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:M.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:M.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:M.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:M.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:M.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:M.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:M.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:M.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&se.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};ci.create=e=>new ci({checks:[],typeName:E.ZodNumber,coerce:e?.coerce||!1,...ee(e)});var li=class e extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==A.bigint)return this._getInvalidInput(t);let n,i=new dt;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),O(n,{code:T.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),O(n,{code:T.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),O(n,{code:T.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):se.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return O(r,{code:T.invalid_type,expected:A.bigint,received:r.parsedType}),B}gte(t,r){return this.setLimit("min",t,!0,M.toString(r))}gt(t,r){return this.setLimit("min",t,!1,M.toString(r))}lte(t,r){return this.setLimit("max",t,!0,M.toString(r))}lt(t,r){return this.setLimit("max",t,!1,M.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:M.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:M.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:M.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:M.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:M.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:M.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};li.create=e=>new li({checks:[],typeName:E.ZodBigInt,coerce:e?.coerce??!1,...ee(e)});var ui=class extends re{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==A.boolean){let n=this._getOrReturnCtx(t);return O(n,{code:T.invalid_type,expected:A.boolean,received:n.parsedType}),B}return kt(t.data)}};ui.create=e=>new ui({typeName:E.ZodBoolean,coerce:e?.coerce||!1,...ee(e)});var di=class e extends re{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==A.date){let o=this._getOrReturnCtx(t);return O(o,{code:T.invalid_type,expected:A.date,received:o.parsedType}),B}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return O(o,{code:T.invalid_date}),B}let n=new dt,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),O(i,{code:T.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),O(i,{code:T.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):se.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:M.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:M.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};di.create=e=>new di({checks:[],coerce:e?.coerce||!1,typeName:E.ZodDate,...ee(e)});var lo=class extends re{_parse(t){if(this._getType(t)!==A.symbol){let n=this._getOrReturnCtx(t);return O(n,{code:T.invalid_type,expected:A.symbol,received:n.parsedType}),B}return kt(t.data)}};lo.create=e=>new lo({typeName:E.ZodSymbol,...ee(e)});var fi=class extends re{_parse(t){if(this._getType(t)!==A.undefined){let n=this._getOrReturnCtx(t);return O(n,{code:T.invalid_type,expected:A.undefined,received:n.parsedType}),B}return kt(t.data)}};fi.create=e=>new fi({typeName:E.ZodUndefined,...ee(e)});var mi=class extends re{_parse(t){if(this._getType(t)!==A.null){let n=this._getOrReturnCtx(t);return O(n,{code:T.invalid_type,expected:A.null,received:n.parsedType}),B}return kt(t.data)}};mi.create=e=>new mi({typeName:E.ZodNull,...ee(e)});var Pn=class extends re{constructor(){super(...arguments),this._any=!0}_parse(t){return kt(t.data)}};Pn.create=e=>new Pn({typeName:E.ZodAny,...ee(e)});var sn=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(t){return kt(t.data)}};sn.create=e=>new sn({typeName:E.ZodUnknown,...ee(e)});var wr=class extends re{_parse(t){let r=this._getOrReturnCtx(t);return O(r,{code:T.invalid_type,expected:A.never,received:r.parsedType}),B}};wr.create=e=>new wr({typeName:E.ZodNever,...ee(e)});var uo=class extends re{_parse(t){if(this._getType(t)!==A.undefined){let n=this._getOrReturnCtx(t);return O(n,{code:T.invalid_type,expected:A.void,received:n.parsedType}),B}return kt(t.data)}};uo.create=e=>new uo({typeName:E.ZodVoid,...ee(e)});var an=class e extends re{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==A.array)return O(r,{code:T.invalid_type,expected:A.array,received:r.parsedType}),B;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(O(r,{code:s?T.too_big:T.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(O(r,{code:T.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(O(r,{code:T.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new ir(r,s,r.path,a)))).then(s=>dt.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new ir(r,s,r.path,a)));return dt.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:M.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:M.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:M.toString(r)}})}nonempty(t){return this.min(1,t)}};an.create=(e,t)=>new an({type:e,minLength:null,maxLength:null,exactLength:null,typeName:E.ZodArray,...ee(t)});function co(e){if(e instanceof Lt){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Zt.create(co(n))}return new Lt({...e._def,shape:()=>t})}else return e instanceof an?new an({...e._def,type:co(e.element)}):e instanceof Zt?Zt.create(co(e.unwrap())):e instanceof Ur?Ur.create(co(e.unwrap())):e instanceof Fr?Fr.create(e.items.map(t=>co(t))):e}var Lt=class e extends re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=se.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==A.object){let c=this._getOrReturnCtx(t);return O(c,{code:T.invalid_type,expected:A.object,received:c.parsedType}),B}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof wr&&this._def.unknownKeys==="strip"))for(let c in i.data)s.includes(c)||a.push(c);let u=[];for(let c of s){let l=o[c],d=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new ir(i,d,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof wr){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of a)u.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(c==="strict")a.length>0&&(O(i,{code:T.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of a){let d=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new ir(i,d,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let l of u){let d=await l.key,h=await l.value;c.push({key:d,value:h,alwaysSet:l.alwaysSet})}return c}).then(c=>dt.mergeObjectSync(n,c)):dt.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(t){return M.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:M.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:E.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of se.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of se.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return co(this)}partial(t){let r={};for(let n of se.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of se.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Zt;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return K_(se.objectKeys(this.shape))}};Lt.create=(e,t)=>new Lt({shape:()=>e,unknownKeys:"strip",catchall:wr.create(),typeName:E.ZodObject,...ee(t)});Lt.strictCreate=(e,t)=>new Lt({shape:()=>e,unknownKeys:"strict",catchall:wr.create(),typeName:E.ZodObject,...ee(t)});Lt.lazycreate=(e,t)=>new Lt({shape:e,unknownKeys:"strip",catchall:wr.create(),typeName:E.ZodObject,...ee(t)});var pi=class extends re{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new Dt(a.ctx.common.issues));return O(r,{code:T.invalid_union,unionErrors:s}),B}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let u of n){let c={...r,common:{...r.common,issues:[]},parent:null},l=u._parseSync({data:r.data,path:r.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(u=>new Dt(u));return O(r,{code:T.invalid_union,unionErrors:a}),B}}get options(){return this._def.options}};pi.create=(e,t)=>new pi({options:e,typeName:E.ZodUnion,...ee(t)});var on=e=>e instanceof gi?on(e.schema):e instanceof or?on(e.innerType()):e instanceof _i?[e.value]:e instanceof yi?e.options:e instanceof vi?se.objectValues(e.enum):e instanceof bi?on(e._def.innerType):e instanceof fi?[void 0]:e instanceof mi?[null]:e instanceof Zt?[void 0,...on(e.unwrap())]:e instanceof Ur?[null,...on(e.unwrap())]:e instanceof vs||e instanceof xi?on(e.unwrap()):e instanceof wi?on(e._def.innerType):[],ac=class e extends re{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==A.object)return O(r,{code:T.invalid_type,expected:A.object,received:r.parsedType}),B;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(O(r,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),B)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let s=on(o.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,o)}}return new e({typeName:E.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...ee(n)})}};function Ku(e,t){let r=qr(e),n=qr(t);if(e===t)return{valid:!0,data:e};if(r===A.object&&n===A.object){let i=se.objectKeys(t),o=se.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let u=Ku(e[a],t[a]);if(!u.valid)return{valid:!1};s[a]=u.data}return{valid:!0,data:s}}else if(r===A.array&&n===A.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let s=e[o],a=t[o],u=Ku(s,a);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===A.date&&n===A.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var hi=class extends re{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(oc(o)||oc(s))return B;let a=Ku(o.value,s.value);return a.valid?((sc(o)||sc(s))&&r.dirty(),{status:r.value,value:a.data}):(O(n,{code:T.invalid_intersection_types}),B)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};hi.create=(e,t,r)=>new hi({left:e,right:t,typeName:E.ZodIntersection,...ee(r)});var Fr=class e extends re{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==A.array)return O(n,{code:T.invalid_type,expected:A.array,received:n.parsedType}),B;if(n.data.length<this._def.items.length)return O(n,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),B;!this._def.rest&&n.data.length>this._def.items.length&&(O(n,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new ir(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>dt.mergeArray(r,s)):dt.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Fr.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Fr({items:e,typeName:E.ZodTuple,rest:null,...ee(t)})};var cc=class e extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==A.object)return O(n,{code:T.invalid_type,expected:A.object,received:n.parsedType}),B;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new ir(n,a,n.path,a)),value:s._parse(new ir(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?dt.mergeObjectAsync(r,i):dt.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof re?new e({keyType:t,valueType:r,typeName:E.ZodRecord,...ee(n)}):new e({keyType:An.create(),valueType:t,typeName:E.ZodRecord,...ee(r)})}},fo=class extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==A.map)return O(n,{code:T.invalid_type,expected:A.map,received:n.parsedType}),B;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,u],c)=>({key:i._parse(new ir(n,a,n.path,[c,"key"])),value:o._parse(new ir(n,u,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of s){let c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return B;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let u of s){let c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return B;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}}}};fo.create=(e,t,r)=>new fo({valueType:t,keyType:e,typeName:E.ZodMap,...ee(r)});var mo=class e extends re{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==A.set)return O(n,{code:T.invalid_type,expected:A.set,received:n.parsedType}),B;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(O(n,{code:T.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(O(n,{code:T.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(u){let c=new Set;for(let l of u){if(l.status==="aborted")return B;l.status==="dirty"&&r.dirty(),c.add(l.value)}return{status:r.value,value:c}}let a=[...n.data.values()].map((u,c)=>o._parse(new ir(n,u,n.path,c)));return n.common.async?Promise.all(a).then(u=>s(u)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:M.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:M.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};mo.create=(e,t)=>new mo({valueType:e,minSize:null,maxSize:null,typeName:E.ZodSet,...ee(t)});var lc=class e extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==A.function)return O(r,{code:T.invalid_type,expected:A.function,received:r.parsedType}),B;function n(a,u){return ys({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,so(),nn].filter(c=>!!c),issueData:{code:T.invalid_arguments,argumentsError:u}})}function i(a,u){return ys({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,so(),nn].filter(c=>!!c),issueData:{code:T.invalid_return_type,returnTypeError:u}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof Cn){let a=this;return kt(async function(...u){let c=new Dt([]),l=await a._def.args.parseAsync(u,o).catch(m=>{throw c.addIssue(n(u,m)),c}),d=await Reflect.apply(s,this,l);return await a._def.returns._def.type.parseAsync(d,o).catch(m=>{throw c.addIssue(i(d,m)),c})})}else{let a=this;return kt(function(...u){let c=a._def.args.safeParse(u,o);if(!c.success)throw new Dt([n(u,c.error)]);let l=Reflect.apply(s,this,c.data),d=a._def.returns.safeParse(l,o);if(!d.success)throw new Dt([i(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Fr.create(t).rest(sn.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||Fr.create([]).rest(sn.create()),returns:r||sn.create(),typeName:E.ZodFunction,...ee(n)})}},gi=class extends re{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};gi.create=(e,t)=>new gi({getter:e,typeName:E.ZodLazy,...ee(t)});var _i=class extends re{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return O(r,{received:r.data,code:T.invalid_literal,expected:this._def.value}),B}return{status:"valid",value:t.data}}get value(){return this._def.value}};_i.create=(e,t)=>new _i({value:e,typeName:E.ZodLiteral,...ee(t)});function K_(e,t){return new yi({values:e,typeName:E.ZodEnum,...ee(t)})}var yi=class e extends re{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return O(r,{expected:se.joinValues(n),received:r.parsedType,code:T.invalid_type}),B}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return O(r,{received:r.data,code:T.invalid_enum_value,options:n}),B}return kt(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};yi.create=K_;var vi=class extends re{_parse(t){let r=se.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==A.string&&n.parsedType!==A.number){let i=se.objectValues(r);return O(n,{expected:se.joinValues(i),received:n.parsedType,code:T.invalid_type}),B}if(this._cache||(this._cache=new Set(se.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=se.objectValues(r);return O(n,{received:n.data,code:T.invalid_enum_value,options:i}),B}return kt(t.data)}get enum(){return this._def.values}};vi.create=(e,t)=>new vi({values:e,typeName:E.ZodNativeEnum,...ee(t)});var Cn=class extends re{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==A.promise&&r.common.async===!1)return O(r,{code:T.invalid_type,expected:A.promise,received:r.parsedType}),B;let n=r.parsedType===A.promise?r.data:Promise.resolve(r.data);return kt(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Cn.create=(e,t)=>new Cn({type:e,typeName:E.ZodPromise,...ee(t)});var or=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===E.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s=>{O(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return B;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?B:u.status==="dirty"?ai(u.value):r.value==="dirty"?ai(u.value):u});{if(r.value==="aborted")return B;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?B:a.status==="dirty"?ai(a.value):r.value==="dirty"?ai(a.value):a}}if(i.type==="refinement"){let s=a=>{let u=i.refinement(a,o);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?B:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?B:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!On(s))return B;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>On(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):B);se.assertNever(i)}};or.create=(e,t,r)=>new or({schema:e,typeName:E.ZodEffects,effect:t,...ee(r)});or.createWithPreprocess=(e,t,r)=>new or({schema:t,effect:{type:"preprocess",transform:e},typeName:E.ZodEffects,...ee(r)});var Zt=class extends re{_parse(t){return this._getType(t)===A.undefined?kt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Zt.create=(e,t)=>new Zt({innerType:e,typeName:E.ZodOptional,...ee(t)});var Ur=class extends re{_parse(t){return this._getType(t)===A.null?kt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ur.create=(e,t)=>new Ur({innerType:e,typeName:E.ZodNullable,...ee(t)});var bi=class extends re{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===A.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};bi.create=(e,t)=>new bi({innerType:e,typeName:E.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ee(t)});var wi=class extends re{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ao(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Dt(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Dt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};wi.create=(e,t)=>new wi({innerType:e,typeName:E.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ee(t)});var po=class extends re{_parse(t){if(this._getType(t)!==A.nan){let n=this._getOrReturnCtx(t);return O(n,{code:T.invalid_type,expected:A.nan,received:n.parsedType}),B}return{status:"valid",value:t.data}}};po.create=e=>new po({typeName:E.ZodNaN,...ee(e)});var C$=Symbol("zod_brand"),vs=class extends re{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},bs=class e extends re{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?B:o.status==="dirty"?(r.dirty(),ai(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?B:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:E.ZodPipeline})}},xi=class extends re{_parse(t){let r=this._def.innerType._parse(t),n=i=>(On(i)&&(i.value=Object.freeze(i.value)),i);return ao(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};xi.create=(e,t)=>new xi({innerType:e,typeName:E.ZodReadonly,...ee(t)});function B_(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function Q_(e,t={},r){return e?Pn.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=B_(t,n),u=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:u})}});if(!o){let s=B_(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):Pn.create()}var R$={object:Lt.lazycreate},E;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(E||(E={}));var I$=(e,t={message:`Input not instance of ${e.name}`})=>Q_(r=>r instanceof e,t),X_=An.create,Y_=ci.create,j$=po.create,N$=li.create,ey=ui.create,M$=di.create,D$=lo.create,Z$=fi.create,L$=mi.create,q$=Pn.create,F$=sn.create,U$=wr.create,G$=uo.create,V$=an.create,Qu=Lt.create,B$=Lt.strictCreate,J$=pi.create,W$=ac.create,H$=hi.create,K$=Fr.create,Q$=cc.create,X$=fo.create,Y$=mo.create,eE=lc.create,tE=gi.create,rE=_i.create,nE=yi.create,iE=vi.create,oE=Cn.create,sE=or.create,aE=Zt.create,cE=Ur.create,lE=or.createWithPreprocess,uE=bs.create,dE=()=>X_().optional(),fE=()=>Y_().optional(),mE=()=>ey().optional(),pE={string:(e=>An.create({...e,coerce:!0})),number:(e=>ci.create({...e,coerce:!0})),boolean:(e=>ui.create({...e,coerce:!0})),bigint:(e=>li.create({...e,coerce:!0})),date:(e=>di.create({...e,coerce:!0}))};var hE=B;import*as Yu from"node:fs";import*as cy from"node:os";import*as qt from"node:path";import*as ho from"node:fs/promises";function ry(e,t){return"Kandan attachment path must resolve inside an allowed upload root ("+e+"): "+t}function ny(e){return"Kandan attachment upload path must not include hidden path segments: "+e}function Xu(e){return"Kandan attachment upload requires a known media/document type or text content (binary content is not allowed): "+e}var iy="LINZUMI_THREAD_RUNNER_KANDAN_THREAD_ID";var oy="Kandan attachment path must not be empty";function ft(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function ws(e){if(Array.isArray(e))return e}function Qe(e){if(e!==void 0&&typeof e=="string"&&e.trim()!=="")return e.trim()}function gE(e){if(e!==void 0&&typeof e=="number"&&Number.isInteger(e))return e}function ed(e){if(e!==void 0)return e}function St(e){let t={};t.type="text",t.text=JSON.stringify(e,void 0,2);let r={};return r.content=[t],r.structuredContent=e,r}var _E="failed: ([a-z0-9_]+)(?: detail=(.+))?$";async function td(e){let t;try{t=await e}catch(r){let n=X(r),i=wn(n),o=new RegExp(_E).exec(i);if(o==null){let d={};return d.error=i,St(d)}let s=o.slice(1),a=s[0],u;if(a!==void 0){let d=ve(a);u=d!==void 0?d:i}else u=i;let c={};c.error=u;let l=s[1];if(l!==void 0){let d=ve(l);d!==void 0&&(c.detail=d)}return St(c)}return St(t)}function ly(e){let t=Cr(e);if(t===void 0)return mu(e);let r=ve(t),n=Rr(r);return n!==void 0&&n.includes("channel_required")?Sg(new Error(n+". Remediation: pass the channel slug in the `channel` parameter, or set target.thread_id to a Linzumi thread you can access (the server resolves the thread's channel). The files were NOT attached; retry with a channel or thread instead of leaving them on disk.",{cause:r})):Tg(r)}function cn(e){let t={};return Object.entries(e).forEach(r=>{t[r[0]]=r[1]}),t}function rd(e,t){if(Qe(e.thread_id)!==void 0||t===void 0)return e;let n=()=>{let s=cn(e);return s.thread_id=t,s},i=e.message_seq;if(i!==void 0&&typeof i<"u")return n();let o=Qe(e.kind);if(o===void 0)return e;switch(o){case"latest_assistant_message":case"message_seq":case"new_message":return n();default:return e}}function sr(e,t){if(Qe(e.thread_id)!==void 0||t===void 0)return e;let n=cn(e);return n.thread_id=t,n}function uc(e,t){let r=Wi(t);if(r!==void 0)return ve(r).toString();let n=e.replace(new RegExp("^wss://"),"https://").replace(new RegExp("^ws://"),"http://"),i=Xr(t,n);return i.TAG==="Ok"?i._0.toString():Ve(i._0)}function yE(e,t){let r=Qe(t.inline_url),n=Qe(t.carousel_url),i=cn(t);return r!==void 0&&(i.inline_url=uc(e,r)),n!==void 0&&(i.carousel_url=uc(e,n)),i}function vE(e,t){if(typeof t!="object"||t===null||Array.isArray(t))return t;let r=Qe(t.url),n=ft(t.image_variants),i=cn(t);return r!==void 0&&(i.url=uc(e,r)),n!==void 0&&(i.image_variants=yE(e,n)),i}function ay(e,t){let r=ws(t.attachments);if(r===void 0)return t;let n=cn(t);return n.attachments=r.map(i=>vE(e,i)),n}function nd(e,t){let r=ft(t.message),n=ft(t.target_message);if(r===void 0&&n===void 0)return t;let i=cn(t);return r!==void 0&&(i.message=ay(e,r)),n!==void 0&&(i.target_message=ay(e,n)),i}var bE=[".csv",".diff",".gif",".htm",".html",".jpeg",".jpg",".json",".jsonl",".log",".md",".mp4",".patch",".pdf",".png",".svg",".txt",".webm",".webp",".xml",".zip"];async function wE(e){let t=[{path:e,label:"runner cwd"}],r=wt(process.env.HOME,o=>o.trim()),n=qt.resolve(r!==void 0&&r!==""?r:cy.homedir(),"Downloads"),i;try{i=await ho.realpath(n)}catch{return t}return t.some(o=>o.path===i)||t.push({path:i,label:"~/Downloads"}),t}function xE(e,t){let r=qt.relative(e,t);return r===""?!0:r.startsWith("..")?!1:!qt.isAbsolute(r)}async function kE(e,t){if(t==="")return Ve(oy);let r=qt.isAbsolute(t)?qt.resolve(t):qt.resolve(e,t);return await ho.realpath(r)}async function SE(e,t){if(!(await e.stat()).isFile())return Ve("Kandan attachment path is not a file: "+t);let n=qt.extname(t).toLowerCase();if(bE.includes(n))return{classification:"KnownType",bytes:await e.readFile()};let i=Buffer.alloc(8192),s=(await e.read(i,0,8192,0)).bytesRead;if(i.subarray(0,s).includes(0))return Ve(Xu(t));let a=await e.readFile();return a.subarray(0,8192).includes(0)?Ve(Xu(t)):{classification:"TextContent",bytes:a}}async function TE(e,t){let r=e.find(i=>xE(i.path,t));if(r!==void 0){if(qt.relative(r.path,t).split(new RegExp("[\\\\/]+","g")).find(l=>l!==void 0?l.startsWith("."):!1)!==void 0)return Ve(ny(t));let s=await ho.open(t,Yu.constants.O_RDONLY|Yu.constants.O_NONBLOCK),a,u=0,c;try{c=await SE(s,t),u=1}catch(l){a={TAG:"Error",_0:X(l)}}return u===1&&(a={TAG:"Ok",_0:c}),await s.close(),a.TAG==="Ok"?a._0:mu(a._0)}let n=e.map(i=>i.label).join(", ");return Ve(ry(n,t))}function $E(e){let t=e.toLowerCase();return t.endsWith(".png")?"image/png":t.endsWith(".jpg")||t.endsWith(".jpeg")?"image/jpeg":t.endsWith(".gif")?"image/gif":t.endsWith(".webp")?"image/webp":t.endsWith(".csv")?"text/csv":t.endsWith(".json")?"application/json":t.endsWith(".md")||t.endsWith(".txt")||t.endsWith(".log")?"text/plain":"application/octet-stream"}function EE(e,t){if(e.toLowerCase().endsWith(".py"))return"text/x-python";let n=$E(e);return t==="KnownType"||n!=="application/octet-stream"?n:"text/plain"}async function uy(e,t){let r=await ho.realpath(e),n=await wE(r),i=await kE(r,t),o=await TE(n,i);return{fileName:qt.basename(i),contentType:EE(i,o.classification),sizeBytes:o.bytes.byteLength,bytes:o.bytes}}async function dy(e,t,r,n,i){let o={};return o["content-type"]=n,await Ma.binary(uc(e,t),{method:r,headers:o,body:$g(i)})}async function fy(e){let t=await Promise.all(e.files.map(p=>uy(e.cwd,p))),r=Qe(e.target.thread_id),n={},i=e.workspace;i!==void 0&&(n.workspace=i);let o=e.channel;o!==void 0&&(n.channel=o),r!==void 0&&(n.thread_id=r),n.files=t.map(p=>{let f={};return f.file_name=p.fileName,f.content_type=p.contentType,f.size_bytes=p.sizeBytes,f});let s=await e.client.prepareMessageUploads(n),a=ws(s.uploads),u=a!==void 0?a:[];u.length===t.length||Ve("Linzumi upload prepare response count mismatch"),await Promise.all(t.map(async(p,f)=>{let g=ft(u[f]),y=Qe(it(g,S=>S.upload_url)),v=Qe(it(g,S=>S.upload_method)),b=v!==void 0?v:"PUT";if(y===void 0)return Ve("Linzumi upload prepare response missing upload_url");let w=await dy(e.serviceUrl,y,b,p.contentType,p.bytes);if(!w.ok)return Ve("Linzumi upload failed for "+p.fileName+": "+w.status.toString()+" "+w.statusText)}));let c=u.map(p=>{let f=Qe(it(ft(p),g=>g.file_id));return f!==void 0?f:Ve("Linzumi upload prepare response missing file_id")}),l={},d=e.workspace;d!==void 0&&(l.workspace=d);let h=e.channel;h!==void 0&&(l.channel=h),r!==void 0&&(l.thread_id=r),l.target=e.target;let m=e.body;return m!==void 0&&(l.body=m),l.uploaded_file_ids=c,await e.client.attachMessageFiles(l)}async function my(e){let t=await uy(e.cwd,e.file),r={},n=e.workspace;n!==void 0&&(r.workspace=n),r.name=e.name,r.file_name=t.fileName,r.content_type=t.contentType,r.size_bytes=t.sizeBytes;let i=await e.client.prepareCustomEmoji(r),o=ft(i.upload),s=Qe(it(o,p=>p.upload_url)),a=Qe(it(o,p=>p.upload_method)),u=a!==void 0?a:"PUT";if(s===void 0)return Ve("Linzumi custom emoji prepare response missing upload_url");let c=await dy(e.serviceUrl,s,u,t.contentType,t.bytes);if(c.ok){let p=await c.json();if(typeof p!="object"||p===null||Array.isArray(p))return Ve("Linzumi custom emoji upload returned non-object JSON");let f=ft(p.custom_emoji);if(f===void 0)return Ve("Linzumi custom emoji upload response missing custom_emoji");let g={};g.ok=!0;let y=i.workspace;g.workspace=y!==void 0?y:void 0,g.emoji=f;let v=Qe(p.asset_id);g.asset_id=v!==void 0?v:void 0;let b=gE(f.id);g.id=b!==void 0?b:void 0;let w=Qe(f.name);g.name=w!==void 0?w:void 0;let S=Qe(f.shortcode);g.shortcode=S!==void 0?S:void 0;let q=Qe(f.image_url);return g.image_url=q!==void 0?q:void 0,g}let l=c.status.toString()+" "+c.statusText,h=(await c.text()).trim(),m;if(h==="")m=l;else{let p=0,f;try{f=JSON.parse(h),p=1}catch{m=h}if(p===1)if(typeof f=="object"&&f!==null&&!Array.isArray(f)){let g=f.error;m=typeof g=="string"?g:h}else m=h}return Ve("Linzumi custom emoji upload failed: "+m)}import*as Ct from"node:fs";import*as Vy from"node:os";import*as By from"node:net";import*as Kt from"node:path";var Jy=cu(Gy(),1);import*as Wy from"node:child_process";function wc(e,t){}function vd(e){return e==="DesiredRunning"?"running":"stopped"}function Hy(e){switch(e){case"Running":return"running";case"Unhealthy":return"unhealthy";case"Exited":return"exited";case"Failed":return"failed";case"Stopped":return"stopped"}}function tz(){let e=wt(process.env.LINZUMI_DEV_SERVICES_DIR,t=>t.trim());return e!==void 0&&e!==""?e:Kt.join(Vy.homedir(),".linzumi","dev-services")}function rz(e){let t=e.replace(new RegExp("[^A-Za-z0-9._-]+","g"),"-").replace(new RegExp("^[-.]+|[-.]+$","g"),"").slice(0,80),r=Ca(e).slice(0,8),n=t===""?"runner":t;return Kt.join(tz(),n+"."+r)}function xc(e){let t=e.trim().toLowerCase();if(new RegExp("^[a-z0-9][a-z0-9._-]{0,63}$").test(t)&&!t.includes(".."))return t}function Ss(e,t){return Kt.join(e,"services",t+".json")}function bd(e,t){return Kt.join(e,"exits",t+".json")}function Ky(e,t){return Kt.join(e,"logs",t+".log")}function zi(e){if(typeof e=="string"&&e!=="")return e}function un(e){if(e!==void 0&&typeof e=="number"&&isFinite(e))return e}function nz(e){return e!==void 0?Array.isArray(e)?Ht(e,t=>{if(typeof t=="number"&&Number.isInteger(t)&&t>0&&t<=65535)return t}):[]:[]}function iz(e,t,r){if(r!==void 0&&r!==null){if(typeof r=="object"&&!Array.isArray(r)){let n=zi(r.reason),i=un(r.atMs);if(n!==void 0&&i!==void 0)return{reason:n,atMs:i};let o=[];n!==void 0||o.push("reason"),i!==void 0||o.push("atMs");let s=o.join(", ");return console.warn("[dev_services.failure_record_malformed] name="+e+" invalid_fields="+o.join(",")),{reason:'dev-service "'+e+'" has a malformed persisted failure record: invalid '+s,atMs:t}}return console.warn("[dev_services.failure_record_malformed] name="+e+" invalid_fields=reason,atMs"),{reason:'dev-service "'+e+'" has a malformed persisted failure record: invalid reason, atMs',atMs:t}}}function oz(e){if(typeof e!="object"||e===null||Array.isArray(e)||!Ot(e.version,1))return;let t=zi(e.name),r=it(t,xc),n=zi(e.command),i=zi(e.cwd),o=e.desiredState,s;if(typeof o=="string")switch(o){case"running":s="DesiredRunning";break;case"stopped":s="DesiredStopped";break;default:s=void 0}else s=void 0;let a=un(e.updatedAtMs),u=zi(e.logPath),c=Ot(r,t);if(r!==void 0&&c&&n!==void 0&&i!==void 0&&s!==void 0&&a!==void 0&&u!==void 0)return{watchdogVersion:un(e.watchdogVersion),name:r,command:n,cwd:i,ports:nz(e.ports),restartOnBranchChange:Ot(e.restartOnBranchChange,!0),desiredState:s,pid:un(e.pid),ownerPid:un(e.ownerPid),startedAtMs:un(e.startedAtMs),updatedAtMs:a,lastBranch:zi(e.lastBranch),logPath:u,automaticRestartAttempts:lt(un(e.automaticRestartAttempts),0),automaticRestartWindowStartedAtMs:un(e.automaticRestartWindowStartedAtMs),automaticRestartCause:zi(e.automaticRestartCause),failure:iz(r,a,e.failure)}}function Ei(e){return e!==void 0?ve(e):null}function sz(e){let t=e.failure,r=t!==void 0?{reason:t.reason,atMs:t.atMs}:null,n={version:1,watchdogVersion:Ei(e.watchdogVersion),name:e.name,command:e.command,cwd:e.cwd,ports:e.ports,restartOnBranchChange:e.restartOnBranchChange,desiredState:vd(e.desiredState),pid:Ei(e.pid),ownerPid:Ei(e.ownerPid),startedAtMs:Ei(e.startedAtMs),updatedAtMs:e.updatedAtMs,lastBranch:Ei(e.lastBranch),logPath:e.logPath,automaticRestartAttempts:e.automaticRestartAttempts,automaticRestartWindowStartedAtMs:Ei(e.automaticRestartWindowStartedAtMs),automaticRestartCause:Ei(e.automaticRestartCause),failure:r},i=JSON.stringify(n);if(i!==void 0)return i+`
123
+ `;throw{RE_EXN_ID:"Failure",_1:"dev-service record could not be encoded",Error:new Error}}function az(e,t,r){let n=Ss(e,t.name),i=Y(Y(ke(vr(Kt.dirname(n)),a=>a.message),()=>{try{return{TAG:"Ok",_0:sz(t)}}catch(a){let u=X(a);return{TAG:"Error",_0:"record encoding failed: "+Ge(u).message}}}),a=>{let u=n+".tmp";return Y(ke(gg(u,a),c=>c.message),()=>ke(Pa(u,n),c=>c.message))});if(i.TAG==="Ok")return{TAG:"Ok",_0:void 0};let o=i._0,s={};return s.path=n,s.message=o,r("dev_services.record_write_failed",s),{TAG:"Error",_0:"could not persist dev-service state at "+n+": "+o}}function gd(e,t,r){let n=Ss(e,t.name),i=n+".lock",o=Y(vr(Kt.dirname(n)),()=>{let u;try{let c=Ct.statSync(i),l=c.isFile(),d=c.isDirectory(),h=Date.now()-c.mtimeMs>=5e3;u=l?h?tt(Qn(i),()=>{let m={};m.name=t.name,m.path=i,r("dev_services.legacy_record_lock_recovered",m)}):{TAG:"Ok",_0:void 0}:d&&h?{TAG:"Ok",_0:Date.now()-c.mtimeMs}:{TAG:"Ok",_0:void 0}}catch(c){let l=X(c),d=Ge(l);u=d.code==="ENOENT"?{TAG:"Ok",_0:void 0}:{TAG:"Error",_0:d}}return Y(u,c=>{try{let l=Jy.lockSync(n,{lockfilePath:i,realpath:!1,retries:0,stale:5e3,update:1e3,onCompromised:d=>{let h=Ge(d),m={};throw m.name=t.name,m.path=i,m.message=h.message,r("dev_services.record_lock_compromised",m),d}});if(c!==void 0){let d={};d.name=t.name,d.path=i,d.age_ms=c,r("dev_services.record_lease_recovered",d)}return{TAG:"Ok",_0:l}}catch(l){let d=X(l);return{TAG:"Error",_0:Ge(d)}}})});if(o.TAG==="Ok"){let u=az(e,t,r),c;try{o._0(),c={TAG:"Ok",_0:void 0}}catch(h){let m=X(h);c={TAG:"Error",_0:Ge(m)}}if(u.TAG!=="Ok")return{TAG:"PersistUnwritten",_0:u._0};if(c.TAG==="Ok")return"PersistOk";let l=c._0,d={};return d.name=t.name,d.path=i,d.message=l.message,r("dev_services.record_unlock_failed",d),{TAG:"PersistCommittedUnlockFailed",_0:"could not unlock dev-service state at "+i+": "+l.message}}let s=o._0,a={};return a.name=t.name,a.path=i,a.message=s.message,r("dev_services.record_lock_failed",a),{TAG:"PersistUnwritten",_0:"could not lock dev-service state at "+i+": "+s.message}}function wd(e,t){let r=xc(t);if(r===void 0)return;let n=yr(Ss(e,r));if(n.TAG!=="Ok")return;let i;try{i=JSON.parse(n._0)}catch{return}return oz(i)}function cz(e){let t=bg(Kt.join(e,"services"));return t.TAG==="Ok"?Ht(t._0,r=>{if(r.endsWith(".json"))return wd(e,r.slice(0,r.length-5|0))}).toSorted((r,n)=>r.name.localeCompare(n.name)):[]}function Qy(e,t){let r=yr(bd(e,t));if(r.TAG!=="Ok")return;let n;try{n=JSON.parse(r._0)}catch{return}if(typeof n!="object"||n===null||Array.isArray(n))return;let i=un(n.atMs);if(i===void 0)return;let o=n.code,s;s=typeof o=="number"?o:void 0;let a=n.signal,u;return u=typeof a=="string"?a:void 0,{code:s,signal:u,atMs:i}}function lz(e){let t={};return t.command=e.command,t.args=e.args.map(r=>r),t.cwd=e.cwd,t.pollIntervalMs=e.pollIntervalMs,t.recordPath=e.recordPath,t.exitStatusPath=e.exitStatusPath,JSON.stringify(t)}function uz(e,t){return{command:e,args:["-e",`
123
124
  const { spawn } = require('node:child_process');
124
125
  const fs = require('node:fs');
125
126
  const config = JSON.parse(process.argv[process.argv.length - 1]);
126
127
  const child = spawn(config.command, config.args, { cwd: config.cwd, stdio: 'inherit' });
127
128
  let done = false;
129
+ function cleanupFailed(branch, error) {
130
+ const message = error && error.message ? error.message : String(error);
131
+ process.stderr.write('dev-service watchdog cleanup failed: branch=' + branch + ' reason=' + message + '\\n');
132
+ }
128
133
  function shutdown(signal) {
129
134
  if (done) return;
130
135
  done = true;
131
136
  try { process.kill(-process.pid, signal); }
132
- catch (_e) { try { child.kill(signal); } catch (_e2) {} }
137
+ catch (groupError) {
138
+ cleanupFailed('shutdown_group', groupError);
139
+ try { child.kill(signal); } catch (childError) { cleanupFailed('shutdown_child', childError); }
140
+ }
133
141
  }
134
142
  process.on('SIGINT', () => shutdown('SIGINT'));
135
143
  process.on('SIGTERM', () => shutdown('SIGTERM'));
@@ -141,44 +149,67 @@ child.on('exit', (code, signal) => {
141
149
  // never let bookkeeping block teardown.
142
150
  try {
143
151
  fs.writeFileSync(config.exitStatusPath, JSON.stringify({ code: code, signal: signal, atMs: Date.now() }) + '\\n', 'utf8');
144
- } catch (_e) {}
152
+ } catch (error) { cleanupFailed('record_child_exit', error); }
145
153
  process.removeAllListeners('SIGINT');
146
154
  process.removeAllListeners('SIGTERM');
147
155
  process.removeAllListeners('SIGHUP');
148
156
  // Sweep any grandchildren left in the group (a dev server that forked
149
157
  // workers must not leak them past its own death), then follow the child.
150
- try { process.kill(-process.pid, 'SIGKILL'); } catch (_e) {}
151
- if (signal) { try { process.kill(process.pid, signal); } catch (_e) {} }
158
+ try { process.kill(-process.pid, 'SIGKILL'); } catch (error) { cleanupFailed('sweep_child_group', error); }
159
+ if (signal) {
160
+ try { process.kill(process.pid, signal); }
161
+ catch (error) { cleanupFailed('mirror_child_signal', error); }
162
+ }
152
163
  process.exit(signal ? 1 : code == null ? 0 : code);
153
164
  });
154
165
  child.on('error', (err) => {
155
166
  try {
156
167
  fs.writeFileSync(config.exitStatusPath, JSON.stringify({ code: 127, signal: null, atMs: Date.now() }) + '\\n', 'utf8');
157
- } catch (_e) {}
168
+ } catch (error) { cleanupFailed('record_spawn_failure', error); }
158
169
  process.stderr.write('dev-service spawn failed: ' + (err && err.message) + '\\n');
159
170
  process.exit(1);
160
171
  });
172
+ function currentOwnerPid() {
173
+ try {
174
+ const record = JSON.parse(fs.readFileSync(config.recordPath, 'utf8'));
175
+ if (typeof record.ownerPid !== 'number') {
176
+ throw new Error('dev-service owner record has no numeric ownerPid');
177
+ }
178
+ return record.ownerPid;
179
+ } catch (error) {
180
+ const message = error && error.message ? error.message : String(error);
181
+ process.stderr.write('dev-service owner record failed: ' + message + '\\n');
182
+ try {
183
+ fs.writeFileSync(config.exitStatusPath, JSON.stringify({ code: 126, signal: null, atMs: Date.now() }) + '\\n', 'utf8');
184
+ } catch (recordError) { cleanupFailed('record_owner_failure', recordError); }
185
+ try { child.kill('SIGKILL'); } catch (childError) { cleanupFailed('owner_failure_child', childError); }
186
+ try { process.kill(-process.pid, 'SIGKILL'); } catch (groupError) { cleanupFailed('owner_failure_group', groupError); }
187
+ process.exit(126);
188
+ }
189
+ }
161
190
  const watchdog = setInterval(() => {
162
- // Inlined devServiceOwnerAlive (keep in sync): the owning runner's death
163
- // takes the whole service group down - managed services die with the
164
- // runner BY DESIGN (desired state + reconcile provide the durability).
191
+ // Inlined devServiceOwnerAlive (keep in sync): the CURRENT owning runner's
192
+ // death takes the whole service group down. The durable record is reread so
193
+ // a replacement runner can transfer the live group before its predecessor
194
+ // exits.
165
195
  // EPERM = alive-but-unsignalable; anything else thrown by kill(pid, 0)
166
196
  // means the runner is gone.
167
- if (config.ownerPid > 0) {
197
+ const ownerPid = currentOwnerPid();
198
+ if (ownerPid > 0) {
168
199
  let alive = true;
169
- try { process.kill(config.ownerPid, 0); }
200
+ try { process.kill(ownerPid, 0); }
170
201
  catch (e) { alive = e && e.code === 'EPERM'; }
171
202
  if (!alive) {
172
- try { child.kill('SIGKILL'); } catch (_e) {}
173
- try { process.kill(-process.pid, 'SIGKILL'); } catch (_e) {}
203
+ try { child.kill('SIGKILL'); } catch (childError) { cleanupFailed('owner_dead_child', childError); }
204
+ try { process.kill(-process.pid, 'SIGKILL'); } catch (groupError) { cleanupFailed('owner_dead_group', groupError); }
174
205
  process.exit(0);
175
206
  }
176
207
  }
177
208
  }, config.pollIntervalMs);
178
- `.trim(),hT(t)]}}function Su(e){if(e===void 0||e<=1)return!1;try{return process.kill(-e,0),!0}catch(t){let r=ee(t);return kt(mt(r).code,"EPERM")}}function Ou(e,t){let r=t.pid;if(r===void 0||r<=1)return!1;let n=O_(e,t.name),i=t.startedAtMs;return n!==void 0&&i!==void 0&&n.atMs>=i?!1:Su(t.pid)}function Pu(e){return new Promise((t,r)=>{let n=$_.createConnection({port:e,host:"127.0.0.1"}),i=o=>{n.removeAllListeners(),n.destroy(),t(o)};n.setTimeout(750),n.once("connect",()=>i(!0)),n.once("timeout",()=>i(!1)),n.once("error",()=>i(!1))})}async function _T(e,t){let r=Ou(e,t),n=[];for(let s=0,a=t.ports.length;s<a;++s){let l=t.ports[s];if(l!==void 0){let c=r?await Pu(l|0):!1;n.push({port:l,listening:c})}}let i=t.desiredState,o;return o=i==="DesiredRunning"?r?n.every(s=>s.listening)?"Running":"Unhealthy":"Exited":"Stopped",{record:t,liveness:o,portProbes:n,lastExit:O_(e,t.name)}}async function Cu(e){let t=[],r=pT(e);for(let n=0,i=r.length;n<i;++n){let o=r[n];o!==void 0&&t.push(await _T(e,o))}return t}function yT(e){let t=ft(e.SHELL,r=>r.trim());return t!==void 0&&t!==""?t:"/bin/sh"}async function P_(e,t,r){if(e===void 0||e<=1||Ol(-e|0,"SIGTERM").TAG!=="Ok")return;let i=Date.now()+3e3,o=Su(e);for(;o&&Date.now()<i;)await ha(100),o=Su(e);if(!o||Ol(-e|0,"SIGKILL").TAG!=="Ok")return;let a={};return a.name=r,a.pgid=e,t("dev_services.stop_escalated",a)}async function C_(e){let t=e.log,r=t!==void 0?t:$u,n=Va(e.definition.name);if(n===void 0)return{TAG:"Error",_0:"invalid service name: use 1-64 lowercase letters, digits, ., _ or -"};let i=e.definition.command.trim();if(i==="")return{TAG:"Error",_0:"service command must not be empty"};let o;try{o={TAG:"Ok",_0:jt.statSync(e.definition.cwd).isDirectory()}}catch{o={TAG:"Error",_0:"cwd does not exist: "+e.definition.cwd}}if(o.TAG!=="Ok")return{TAG:"Error",_0:o._0};if(!o._0)return{TAG:"Error",_0:"cwd is not a directory: "+e.definition.cwd};let s=Au(e.scopeDir,n);s!==void 0&&Ou(e.scopeDir,s)&&await P_(s.pid,r,n);let a=e.nowMs,l=a!==void 0?a:Date.now(),c=E_(e.scopeDir,n),u=Eu(e.scopeDir,n),d=Q(Q(Q(zr(rr.dirname(c)),()=>zr(rr.join(e.scopeDir,"services"))),()=>zr(rr.dirname(u))),()=>{try{return{TAG:"Ok",_0:jt.openSync(c,"a")}}catch(R){let D=ee(R);return{TAG:"Error",_0:mt(D)}}});if(d.TAG!=="Ok")return{TAG:"Error",_0:"cannot open service log: "+d._0.message};let h=d._0;Pi(u);let p=e.shellPathOverride,m=p!==void 0?p:yT(process.env),f=e.nodeExecPath,g=e.watchdogPollIntervalMs,y=gT(f!==void 0?f:process.execPath,{command:m,args:["-lc",i],cwd:e.definition.cwd,ownerPid:e.ownerPid,pollIntervalMs:g!==void 0?g:500,exitStatusPath:u});try{jt.writeFileSync(h,`
179
- --- linzumi dev-service "`+n+'" starting at '+new Date(l).toISOString()+" (owner pid "+e.ownerPid.toString()+`) ---
209
+ `.trim(),lz(t)]}}function _d(e){if(e===void 0||e<=1)return!1;try{return process.kill(-e,0),!0}catch(t){let r=X(t);return Ot(Ge(r).code,"EPERM")}}function xd(e,t){let r=t.pid;if(r===void 0||r<=1)return!1;let n=Qy(e,t.name),i=t.startedAtMs;return n!==void 0&&i!==void 0&&n.atMs>=i?!1:_d(t.pid)}function kd(e){return new Promise((t,r)=>{let n=By.createConnection({port:e,host:"127.0.0.1"}),i=o=>{n.removeAllListeners(),n.destroy(),t(o)};n.setTimeout(750),n.once("connect",()=>i(!0)),n.once("timeout",()=>i(!1)),n.once("error",()=>i(!1))})}async function dz(e,t){let r=xd(e,t),n=[];for(let s=0,a=t.ports.length;s<a;++s){let u=t.ports[s];if(u!==void 0){let c=r?await kd(u|0):!1;n.push({port:u,listening:c})}}let i=t.desiredState,o;if(i==="DesiredRunning"){let s=t.failure;o=r?n.every(a=>a.listening)?"Running":"Unhealthy":s!==void 0?"Failed":"Exited"}else o="Stopped";return{record:t,liveness:o,portProbes:n,lastExit:Qy(e,t.name),failure:t.failure}}async function Sd(e){let t=[],r=cz(e);for(let n=0,i=r.length;n<i;++n){let o=r[n];o!==void 0&&t.push(await dz(e,o))}return t}function fz(e){let t=wt(e.SHELL,r=>r.trim());return t!==void 0&&t!==""?t:"/bin/sh"}async function yd(e,t,r,n){let i=n!==void 0?n:3e3;if(e===void 0||e<=1||du(-e|0,"SIGTERM").TAG!=="Ok")return;let s=Date.now()+i,a=_d(e);for(;a&&Date.now()<s;)await Da(100),a=_d(e);if(!a||du(-e|0,"SIGKILL").TAG!=="Ok")return;let c={};return c.name=r,c.pgid=e,t("dev_services.stop_escalated",c)}async function Xy(e){let t=e.log,r=t!==void 0?t:wc,n=xc(e.definition.name);if(n===void 0)return{TAG:"Error",_0:"invalid service name: use 1-64 lowercase letters, digits, ., _ or -"};let i=e.definition.command.trim();if(i==="")return{TAG:"Error",_0:"service command must not be empty"};let o;try{o={TAG:"Ok",_0:Ct.statSync(e.definition.cwd).isDirectory()}}catch{o={TAG:"Error",_0:"cwd does not exist: "+e.definition.cwd}}if(o.TAG!=="Ok")return{TAG:"Error",_0:o._0};if(!o._0)return{TAG:"Error",_0:"cwd is not a directory: "+e.definition.cwd};let s=wd(e.scopeDir,n);s!==void 0&&xd(e.scopeDir,s)&&await yd(s.pid,r,n,void 0);let a=e.nowMs,u=a!==void 0?a:Date.now(),c=Ky(e.scopeDir,n),l=bd(e.scopeDir,n),d=Y(Y(Y(vr(Kt.dirname(c)),()=>vr(Kt.join(e.scopeDir,"services"))),()=>vr(Kt.dirname(l))),()=>{try{return{TAG:"Ok",_0:Ct.openSync(c,"a")}}catch($){let R=X($);return{TAG:"Error",_0:Ge(R)}}});if(d.TAG!=="Ok")return{TAG:"Error",_0:"cannot open service log: "+d._0.message};let h=d._0,m=Qn(l);if(m.TAG!=="Ok"){let $={};$.name=n,$.path=l,$.message=m._0.message,r("dev_services.exit_marker_remove_failed",$)}let p=e.shellPathOverride,f=p!==void 0?p:fz(process.env),g=e.nodeExecPath,y=e.watchdogPollIntervalMs,v=uz(g!==void 0?g:process.execPath,{command:f,args:["-lc",i],cwd:e.definition.cwd,pollIntervalMs:y!==void 0?y:500,recordPath:Ss(e.scopeDir,n),exitStatusPath:l});try{Ct.writeFileSync(h,`
210
+ --- linzumi dev-service "`+n+'" starting at '+new Date(u).toISOString()+" (owner pid "+e.ownerPid.toString()+`) ---
180
211
  $ `+i+`
181
- `)}catch{}let v={};Object.entries(process.env).forEach(R=>{v[R[0]]=R[1]}),v.ELECTRON_RUN_AS_NODE="1";let b;try{let R=T_.spawn(y.command,y.args,{cwd:e.definition.cwd,detached:!0,stdio:["ignore",Number(h),Number(h)],env:v});R.unref(),b={TAG:"Ok",_0:Oi(R.pid)}}catch(R){let D=ee(R);b={TAG:"Error",_0:"spawn failed: "+mt(D).message}}try{jt.closeSync(h)}catch{}if(b.TAG!=="Ok")return{TAG:"Error",_0:b._0};let w=b._0;if(w===void 0)return{TAG:"Error",_0:"spawn failed: no pid"};let S=[];e.definition.ports.forEach(R=>{if(!S.includes(R)){S.push(R);return}});let Z=e.definition.cwd,F=S.toSorted((R,D)=>R-D),ce=e.definition.restartOnBranchChange,Je=w,Ee=e.ownerPid,ut={name:n,command:i,cwd:Z,ports:F,restartOnBranchChange:ce,desiredState:"DesiredRunning",pid:Je,ownerPid:Ee,startedAtMs:l,updatedAtMs:l,lastBranch:void 0,logPath:c};A_(e.scopeDir,ut,r);let Ye={};return Ye.name=n,Ye.pid=w,Ye.owner_pid=e.ownerPid,Ye.cwd=e.definition.cwd,Ye.ports=F.map(R=>R),r("dev_services.started",Ye),{TAG:"Ok",_0:ut}}async function Ru(e,t,r){let n=r!==void 0?r:$u,i=Au(e,t);if(i===void 0)return{TAG:"Error",_0:"unknown service: "+t};Ou(e,i)&&await P_(i.pid,n,i.name);let o=i.name,s=i.command,a=i.cwd,l=i.ports,c=i.restartOnBranchChange,u=i.startedAtMs,d=Date.now(),h=i.lastBranch,p=i.logPath,m={name:o,command:s,cwd:a,ports:l,restartOnBranchChange:c,desiredState:"DesiredStopped",pid:void 0,ownerPid:void 0,startedAtMs:u,updatedAtMs:d,lastBranch:h,logPath:p};A_(e,m,n);let f={};return f.name=i.name,n("dev_services.stopped",f),{TAG:"Ok",_0:m}}async function R_(e,t){let r=await Ru(e,t,$u);if(r.TAG!=="Ok")return{TAG:"Error",_0:r._0};let n=r._0;return Pi(zu(e,n.name)),Pi(Eu(e,n.name)),{TAG:"Ok",_0:n}}function I_(e,t,r){let n=Va(t);if(n===void 0)return;let i=E_(e,n),o;try{o=jt.openSync(i,"r")}catch{return}let s;try{let a=jt.fstatSync(o).size,l=Math.min(a,r),c=Buffer.alloc(l|0);jt.readSync(o,c,0,l|0,a-l),s=c.toString("utf8")}catch{s=void 0}try{jt.closeSync(o)}catch{}return s}function j_(e){let t=ft(e.LINZUMI_DEV_SERVICES_SCOPE,i=>i.trim()),r=e.LINZUMI_DEV_SERVICES_OWNER_PID,n=Number.parseInt(r!==void 0?r:"",10);if(t!==void 0&&t!==""&&Number.isInteger(n)&&n>0)return{scopeDir:lT(t),ownerPid:n}}var M_=`<linzumi_markdown_media_guidance>
212
+ `)}catch($){let R=X($),N={};N.name=n,N.message=Ge(R).message,r("dev_services.start_banner_write_failed",N)}let b=[];e.definition.ports.forEach($=>{if(!b.includes($)){b.push($);return}});let w=1,S=e.definition.cwd,q=b.toSorted(($,R)=>$-R),K=e.definition.restartOnBranchChange,ce=e.ownerPid,C=u,G={reason:'dev service "'+n+'" start did not complete',atMs:u},H={watchdogVersion:w,name:n,command:i,cwd:S,ports:q,restartOnBranchChange:K,desiredState:"DesiredStopped",pid:void 0,ownerPid:ce,startedAtMs:C,updatedAtMs:u,lastBranch:void 0,logPath:c,automaticRestartAttempts:0,automaticRestartWindowStartedAtMs:void 0,automaticRestartCause:void 0,failure:G},fe=()=>{try{return Ct.closeSync(h),{TAG:"Ok",_0:void 0}}catch($){let R=X($);return{TAG:"Error",_0:Ge(R).message}}},ge=gd(e.scopeDir,H,r);if(typeof ge!="object"){let $={};Object.entries(process.env).forEach(_e=>{$[_e[0]]=_e[1]}),$.ELECTRON_RUN_AS_NODE="1";let R;try{let _e=Wy.spawn(v.command,v.args,{cwd:e.definition.cwd,detached:!0,stdio:["ignore",Number(h),Number(h)],env:$});_e.unref(),R={TAG:"Ok",_0:Ji(_e.pid)}}catch(_e){let hr=X(_e);R={TAG:"Error",_0:"spawn failed: "+Ge(hr).message}}let N=fe();if(N.TAG!=="Ok"){let _e={};_e.name=n,_e.message=N._0,r("dev_services.log_close_failed",_e)}if(R.TAG!=="Ok")return{TAG:"Error",_0:R._0};let I=R._0;if(I===void 0)return{TAG:"Error",_0:"spawn failed: no pid"};let V=w,ye=S,qe=q,Ye=K,zt=I,Fe={watchdogVersion:V,name:n,command:i,cwd:ye,ports:qe,restartOnBranchChange:Ye,desiredState:"DesiredRunning",pid:zt,ownerPid:ce,startedAtMs:C,updatedAtMs:u,lastBranch:void 0,logPath:c,automaticRestartAttempts:0,automaticRestartWindowStartedAtMs:void 0,automaticRestartCause:void 0,failure:void 0},Ue=gd(e.scopeDir,Fe,r);if(typeof Ue!="object"){let _e={};return _e.name=n,_e.pid=I,_e.owner_pid=e.ownerPid,_e.cwd=e.definition.cwd,_e.ports=qe.map(hr=>hr),r("dev_services.started",_e),{TAG:"Ok",_0:Fe}}return Ue.TAG!=="PersistUnwritten"?{TAG:"Error",_0:Ue._0}:(await yd(zt,r,n,0),{TAG:"Error",_0:Ue._0})}else ge.TAG;let j=fe();if(j.TAG!=="Ok"){let $={};$.name=n,$.message=j._0,r("dev_services.log_close_failed",$)}return{TAG:"Error",_0:ge._0}}async function Td(e,t,r){let n=r!==void 0?r:wc,i=wd(e,t);if(i===void 0)return{TAG:"Error",_0:"unknown service: "+t};xd(e,i)&&await yd(i.pid,n,i.name,void 0);let o=i.watchdogVersion,s=i.name,a=i.command,u=i.cwd,c=i.ports,l=i.restartOnBranchChange,d=i.startedAtMs,h=Date.now(),m=i.lastBranch,p=i.logPath,f=i.automaticRestartAttempts,g=i.automaticRestartWindowStartedAtMs,y=i.automaticRestartCause,v={watchdogVersion:o,name:s,command:a,cwd:u,ports:c,restartOnBranchChange:l,desiredState:"DesiredStopped",pid:void 0,ownerPid:void 0,startedAtMs:d,updatedAtMs:h,lastBranch:m,logPath:p,automaticRestartAttempts:f,automaticRestartWindowStartedAtMs:g,automaticRestartCause:y,failure:void 0},b=gd(e,v,n);if(typeof b=="object")return{TAG:"Error",_0:b._0};let w={};return w.name=i.name,n("dev_services.stopped",w),{TAG:"Ok",_0:v}}async function Yy(e,t,r){let n=await Td(e,t,r);if(n.TAG!=="Ok")return{TAG:"Error",_0:n._0};let i=n._0,o=Y(Qn(Ss(e,i.name)),()=>Qn(bd(e,i.name)));if(o.TAG==="Ok")return{TAG:"Ok",_0:i};let s=o._0,a={};return a.name=i.name,a.message=s.message,r("dev_services.remove_failed",a),{TAG:"Error",_0:'could not remove dev service "'+i.name+'": '+s.message}}function ev(e,t,r){let n=xc(t);if(n===void 0)return;let i=Ky(e,n),o;try{o=Ct.openSync(i,"r")}catch{return}let s;try{let a=Ct.fstatSync(o).size,u=Math.min(a,r),c=Buffer.alloc(u|0);Ct.readSync(o,c,0,u|0,a-u),s=c.toString("utf8")}catch{s=void 0}try{Ct.closeSync(o)}catch{}return s}function tv(e){let t=wt(e.LINZUMI_DEV_SERVICES_SCOPE,i=>i.trim()),r=e.LINZUMI_DEV_SERVICES_OWNER_PID,n=Number.parseInt(r!==void 0?r:"",10);if(t!==void 0&&t!==""&&Number.isInteger(n)&&n>0)return{scopeDir:rz(t),ownerPid:n}}var nv=`<linzumi_markdown_media_guidance>
182
213
  Some Linzumi users have opted into rich Markdown media rendering. When you are
183
214
  writing a visible Linzumi message, channel message, or thread reply, you may use
184
215
  these Markdown-compatible media directives:
@@ -281,14 +312,14 @@ Why bad: External image hosts are intentionally not auto-rendered; attach the im
281
312
  Use media directives only after upload/attach returns a Linzumi download URL.
282
313
  Keep "src" required, all other fields optional, and never exceed 10 embeds in one message.
283
314
  </media_reminder>
284
- </linzumi_markdown_media_guidance>`;function Iu(e){return e==="Voice"?"voice":"text"}function bT(e){switch(e){case"All":return"all";case"Coding":return"coding";case"OnboardingDiscovery":return"onboarding-discovery"}}function ju(e){return JSON.stringify(e)}function D_(e){let t=[],r=e.argsPrefix;r!==void 0&&r.forEach(y=>{t.push(y)}),t.push("mcp"),t.push("server"),t.push("--api-url"),t.push(e.serviceUrl);let n=e.authFilePath;n!==void 0&&(t.push("--auth-file"),t.push(n));let i=e.delegationAuthFilePath;i!==void 0&&(t.push("--delegation-auth-file"),t.push(i));let o=e.ownerUsername;o!==void 0&&(t.push("--owner-username"),t.push(o));let s=e.cwd;s!==void 0&&(t.push("--cwd"),t.push(s));let a=e.threadId;a!==void 0&&(t.push("--thread-id"),t.push(a)),t.push("--mode");let l=e.operatingMode;t.push(l!==void 0?Iu(l):"text");let c=e.toolScope;if(c!==void 0){let y=0;switch(c){case"All":break;case"Coding":case"OnboardingDiscovery":y=1;break}y===1&&(t.push("--tool-scope"),t.push(bT(c)))}let u=e.agentSession;u!==void 0&&u&&t.push("--agent-session");let d=e.askUserQuestionTool;d!==void 0&&d&&t.push("--ask-user-question-tool");let h=e.multiAgentJobs;h!==void 0&&h&&t.push("--multi-agent-jobs");let p={},m=e.accessToken;m!==void 0&&(p.LINZUMI_MCP_ACCESS_TOKEN=m);let f=e.devServices;f!==void 0&&(p.LINZUMI_DEV_SERVICES_SCOPE=f.scope,p.LINZUMI_DEV_SERVICES_OWNER_PID=f.ownerPid.toString()),p.ELECTRON_RUN_AS_NODE="1";let g=e.command;return{name:"linzumi",command:g!==void 0?g:"linzumi",args:t,env:p}}function wT(e){return"["+e.map(ju).join(", ")+"]"}function xT(e){return"{ "+Object.entries(e).map(r=>r[0]+" = "+ju(r[1])).join(", ")+" }"}function Z_(e){let t={};t.command=e.command,t.args=e.args.map(o=>o);let r={};t.env=(Object.entries(e.env).forEach(o=>{r[o[0]]=o[1]}),r);let n={};n[e.name]=t;let i={};return i.mcpServers=n,JSON.stringify(i,void 0,2)+`
285
- `}function q_(e){let t=Object.entries(e.env).length===0?"":"env = "+xT(e.env)+`
315
+ </linzumi_markdown_media_guidance>`;function $d(e){return e==="Voice"?"voice":"text"}function pz(e){switch(e){case"All":return"all";case"Coding":return"coding";case"OnboardingDiscovery":return"onboarding-discovery"}}function Ed(e){return JSON.stringify(e)}function iv(e){let t=[],r=e.argsPrefix;r!==void 0&&r.forEach(y=>{t.push(y)}),t.push("mcp"),t.push("server"),t.push("--api-url"),t.push(e.serviceUrl);let n=e.authFilePath;n!==void 0&&(t.push("--auth-file"),t.push(n));let i=e.delegationAuthFilePath;i!==void 0&&(t.push("--delegation-auth-file"),t.push(i));let o=e.ownerUsername;o!==void 0&&(t.push("--owner-username"),t.push(o));let s=e.cwd;s!==void 0&&(t.push("--cwd"),t.push(s));let a=e.threadId;a!==void 0&&(t.push("--thread-id"),t.push(a)),t.push("--mode");let u=e.operatingMode;t.push(u!==void 0?$d(u):"text");let c=e.toolScope;if(c!==void 0){let y=0;switch(c){case"All":break;case"Coding":case"OnboardingDiscovery":y=1;break}y===1&&(t.push("--tool-scope"),t.push(pz(c)))}let l=e.agentSession;l!==void 0&&l&&t.push("--agent-session");let d=e.askUserQuestionTool;d!==void 0&&d&&t.push("--ask-user-question-tool");let h=e.multiAgentJobs;h!==void 0&&h&&t.push("--multi-agent-jobs");let m={},p=e.accessToken;p!==void 0&&(m.LINZUMI_MCP_ACCESS_TOKEN=p);let f=e.devServices;f!==void 0&&(m.LINZUMI_DEV_SERVICES_SCOPE=f.scope,m.LINZUMI_DEV_SERVICES_OWNER_PID=f.ownerPid.toString()),m.ELECTRON_RUN_AS_NODE="1";let g=e.command;return{name:"linzumi",command:g!==void 0?g:"linzumi",args:t,env:m}}function hz(e){return"["+e.map(Ed).join(", ")+"]"}function gz(e){return"{ "+Object.entries(e).map(r=>r[0]+" = "+Ed(r[1])).join(", ")+" }"}function ov(e){let t={};t.command=e.command,t.args=e.args.map(o=>o);let r={};t.env=(Object.entries(e.env).forEach(o=>{r[o[0]]=o[1]}),r);let n={};n[e.name]=t;let i={};return i.mcpServers=n,JSON.stringify(i,void 0,2)+`
316
+ `}function sv(e){let t=Object.entries(e.env).length===0?"":"env = "+gz(e.env)+`
286
317
  `;return"[mcp_servers."+e.name+`]
287
- command = `+ju(e.command)+`
288
- args = `+wT(e.args)+`
289
- `+t}var L_="Other",V_="linzumi_ask_user_question",kT="plan_mode_native_interview_tool",ST="no_active_turn";function rs(e){return JSON.stringify(e)}function $T(e){let t=e.trim().toLowerCase();switch(t){case"other":case"something else":case"something else...":return!0;default:return t.includes("other")?!0:t.includes("something else")}}function TT(e){let t=it(e),r=Yo(t!==void 0?t.questions:void 0);if(r===void 0)return{TAG:"Invalid",_0:"questions: expected an array"};let n=r.length;if(n===0)return{TAG:"Invalid",_0:"questions: min 1, got 0"};if(n>4)return{TAG:"Invalid",_0:"questions: max 4, got "+n.toString()};let i={contents:void 0},o=[],s=new Set;r.forEach((l,c)=>{if(i.contents!==void 0)return;let d=c.toString(),h=it(l);if(h===void 0){i.contents="questions["+d+"]: expected an object";return}let p=qe(h.question);if(p===void 0){i.contents="questions["+d+"].question: must be a non-empty string";return}if(s.has(p)){i.contents="questions: duplicate question text "+rs(p);return}let m=qe(h.header);if(m===void 0){i.contents="questions["+d+"].header: must be a non-empty string";return}if(m.length>12){i.contents="questions["+d+"].header: max 12 chars, got "+m.length.toString();return}let f=h.multiSelect;if(f!==void 0){let F=0;if(typeof f!="boolean"&&(F=2),F===2){i.contents="questions["+d+"].multiSelect: must be a boolean";return}}let g=Yo(h.options);if(g===void 0){i.contents="questions["+d+"].options: expected an array";return}let y=g.length;if(y<2){i.contents="questions["+d+"].options: min 2, got "+y.toString();return}if(y>4){i.contents="questions["+d+"].options: max 4, got "+y.toString();return}let v=[],b=new Set;if(g.forEach((F,ce)=>{if(i.contents!==void 0)return;let Ee=ce.toString(),bt=it(F),ut=bt!==void 0?qe(bt.label):void 0;if(bt!==void 0&&ut!==void 0){let Ye=bt.description,R=0;if(Ye!==void 0){let D=0;if(typeof Ye=="string"?R=2:D=3,D===3){i.contents="questions["+d+"].options["+Ee+"].description: must be a string";return}}else R=2;if(R===2){if($T(ut)){i.contents="questions["+d+"].options["+Ee+"].label: "+rs(ut)+" is reserved for the built-in Other option";return}if(b.has(ut)){i.contents="questions["+d+"].options: duplicate label "+rs(ut);return}b.add(ut);let D=bt.description,ve;ve=typeof D=="string"?D:"",v.push({label:ut,description:ve});return}}i.contents="questions["+d+"].options["+Ee+"].label: must be a non-empty string"}),i.contents!==void 0)return;s.add(p);let S=h.multiSelect,Z;Z=S===!0,o.push({question:p,header:m,options:v,multiSelect:Z})});let a=i.contents;return a!==void 0?{TAG:"Invalid",_0:a}:{TAG:"Parsed",_0:{questions:o}}}function zT(e){let t={};e.questions.forEach(a=>{let l={};l.type="string",l.description=a.header,t[a.question]=l});let r={};r.type="object",r.properties=t,r.required=e.questions.map(a=>a.question);let n=e.questions.map(a=>{let l={};return l.question=a.question,l.header=a.header,l.multiSelect=a.multiSelect,l.options=a.options.map(c=>{let u={};return u.label=c.label,u.description=c.description,u}),l}),i={};i.version=1,i.questions=n;let o={};o[V_]=i;let s={};return s.message="Linzumi interview: the user is being asked in the Linzumi thread.",s.requestedSchema=r,s._meta=o,s}function ET(e,t){let r=it(t);if(r===void 0)return{TAG:"AnswersInvalid",_0:"the runner accepted the interview but returned no answers; it may predate linzumi_ask_user_question support"};let n={contents:void 0},i={};e.questions.forEach(s=>{if(n.contents!==void 0)return;let l=r[s.question];if(typeof l=="string"){let c=0,u;try{u=JSON.parse(l),c=2}catch{n.contents="the runner returned an undecodable answer for question "+rs(s.question);return}if(c===2){i[s.question]=u;return}}n.contents="the runner returned no answer for question "+rs(s.question)});let o=n.contents;return o!==void 0?{TAG:"AnswersInvalid",_0:o}:{TAG:"Answers",_0:i}}function AT(e){let t=it(e);if(t===void 0)return;let r=it(t[V_]);return qe(r!==void 0?r.reason:void 0)}function rn(e){let t={};t.type="text",t.text=e;let r={};return r.content=[t],r.isError=!0,r}function OT(e){if(e===void 0)return"undefined";if(e===null)return"null";switch(typeof e){case"string":return e;case"number":return e.toString();default:return JSON.stringify(e)}}async function U_(e,t){let r=TT(t);if(r.TAG!=="Parsed")return rn(r._0);let n=r._0,i=0,o;try{o=await e(zT(n),2147483647),i=1}catch(s){let a=ee(s);return rn("the interview could not be delivered to the user: "+fn(a))}if(i===1){let s=it(o),a=s!==void 0?s:{},l=a.action,c=0;if(typeof l=="string")switch(l){case"accept":let u=ET(n,a.content);if(u.TAG!=="Answers")return rn(u._0);let d={};return d.answers=u._0,gt(d);case"cancel":return rn("the user dismissed the question without answering");case"decline":let h=AT(a._meta);return rn(h!==void 0?h===kT?"linzumi_ask_user_question is unavailable during a Plan-mode turn: use the native request_user_input interview tool instead":h===ST?"the interview was declined: no active turn is bound to this session":"the interview request was declined by the runner":"the interview request was declined by the runner");default:c=2}else c=2;if(c===2)return rn("the interview returned an unknown action: "+OT(l))}}var F_="linzumi_ask_user_question",Mu=4,Du=12,Zu=2,qu=4;function CT(e){switch(e){case"All":return!0;case"Coding":case"OnboardingDiscovery":return!1}}function RT(e){return e==="Voice"}function IT(e){return e.trim().replace(new RegExp("^:+"),"").replace(new RegExp(":+$"),"").toLowerCase()}function G_(){return _.string().min(1).refine(e=>IT(e).length<=64,{message:"Custom emoji shortcode name must be at most 64 characters after trimming surrounding colons."})}function be(){return _.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")}function Gt(){return _.string().optional().describe("Channel slug. Omit to use the authenticated token scope.")}function Bt(e){if(typeof e=="string")return e}function B_(e,t,r){let n=it(e[t]);return n!==void 0?n:je(r+" "+t+" must be an object")}function jT(e){return e!==void 0?Array.isArray(e)?Ft(e,t=>{if(typeof t=="string")return t}):[]:[]}function NT(e){return e!==void 0?Array.isArray(e)?Ft(e,t=>{if(typeof t=="number")return t}):[]:[]}function J_(e){if(typeof e=="number")return e}function W_(e){let t={};t.name=e.record.name,t.command=e.record.command,t.cwd=e.record.cwd,t.ports=e.record.ports.map(o=>o),t.restart_on_branch_change=e.record.restartOnBranchChange,t.desired_state=Tu(e.record.desiredState),t.liveness=z_(e.liveness),t.port_health=e.portProbes.map(o=>{let s={};return s.port=o.port,s.listening=o.listening,s});let r=e.record.startedAtMs;t.started_at_ms=r!==void 0?r:null;let n=e.lastExit,i;if(n!==void 0){let o={},s=n.code;o.code=s!==void 0?s:null;let a=n.signal;o.signal=a!==void 0?a:null,o.at_ms=n.atMs,i=o}else i=null;return t.last_exit=i,t.log_path=e.record.logPath,t}function MT(e,t,r){e.registerTool("linzumi_dev_service_start","Start a long-running local dev server (npm run dev, storybook, docker compose up, ...) as a MANAGED SERVICE owned by the Linzumi runner. Use this instead of running dev servers in your own shell: a managed service survives the end of your turn and branch switches, is auto-restarted if it crashes, and its declared ports are health-probed and surfaced in the product. Calling start for an existing name declaratively RESTARTS it (e.g. after a checkout). Declare EVERY port the app serves from (primary plus HMR/asset/bundle sibling ports).",Object.fromEntries([["name",_.string().regex(new RegExp("^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")).describe("Stable service name (slug), e.g. 'web' or 'storybook'. Reusing a name restarts that service.")],["command",_.string().min(1).describe("Shell command that runs the server in the foreground (never daemonize/screen/nohup it yourself), e.g. 'npm run dev'. Runs via the user's login shell.")],["cwd",_.string().optional().describe("Working directory for the service. Defaults to the session cwd.")],["ports",_.array(_.number().int().min(1).max(65535)).max(16).default([]).describe("Every TCP port this service listens on (primary AND related ports such as the Vite/HMR bundle port). Used for health probes and product visibility.")],["restart_on_branch_change",_.boolean().optional().describe("Restart the service automatically when the git branch of its cwd changes (for servers that go stale across checkouts).")],["wait_for_ports_ms",_.number().int().min(0).max(6e4).optional().describe("How long to wait for the declared ports to accept connections before returning (default 15000).")]]),async n=>{let i=Bt(n.name),o=i!==void 0?i:"",s=Bt(n.command),a=s!==void 0?s:"",l=Bt(n.cwd),c=await C_({scopeDir:r.scopeDir,definition:{name:o,command:a,cwd:l!==void 0?l:t,ports:NT(n.ports),restartOnBranchChange:kt(n.restart_on_branch_change,!0)},ownerPid:r.ownerPid});if(c.TAG==="Ok"){let d=c._0,h=J_(n.wait_for_ports_ms),p=Date.now()+(h!==void 0?h:15e3),m=d.ports.length===0;for(;!m&&Date.now()<p;)m=(await Promise.all(d.ports.map(w=>Pu(w|0)))).every(w=>w),m||await ha(250);let g=(await Cu(r.scopeDir)).find(b=>b.record.name===d.name),y={};y.ok=!0;let v;if(g!==void 0)v=W_(g);else{let b={};b.name=d.name,v=b}return y.service=v,g!==void 0&&g.liveness!=="Running"&&(y.hint="The service is not (fully) serving its declared ports yet. Check linzumi_dev_service_logs before assuming it works."),gt(y)}let u={};return u.ok=!1,u.error=c._0,gt(u)}),e.registerTool("linzumi_dev_service_stop","Stop a managed dev service (SIGTERM, then SIGKILL after a grace period). The registration is kept so linzumi_dev_service_start can bring it back.",Object.fromEntries([["name",_.string().min(1).describe("Service name to stop.")]]),async n=>{let i=Bt(n.name),o=i!==void 0?i:"",s=await Ru(r.scopeDir,o,void 0),a={};return s.TAG==="Ok"?(a.ok=!0,a.name=s._0.name,a.desired_state="stopped"):(a.ok=!1,a.error=s._0),gt(a)}),e.registerTool("linzumi_dev_service_status","List every managed dev service with liveness (running / unhealthy / exited / stopped), per-port health probes, and last exit. Live state - always check this before concluding a dev server is up or down.",{},async n=>{let i=await Cu(r.scopeDir),o={};return o.services=i.map(s=>W_(s)),gt(o)}),e.registerTool("linzumi_dev_service_logs","Read the tail of a managed dev service's combined stdout/stderr log.",Object.fromEntries([["name",_.string().min(1).describe("Service name.")],["max_bytes",_.number().int().min(256).max(65536).optional().describe("Tail size in bytes (default 16384).")]]),async n=>{let i=Bt(n.name),o=i!==void 0?i:"",s=J_(n.max_bytes),a=I_(r.scopeDir,o,s!==void 0?s:16384),l={};return a!==void 0?(l.ok=!0,l.name=o,l.log_tail=a):(l.ok=!1,l.error="no log for service: "+o),gt(l)}),e.registerTool("linzumi_dev_service_remove","Stop a managed dev service AND delete its registration (it will not be resurrected on runner restart). Use stop instead when the user may want it back.",Object.fromEntries([["name",_.string().min(1).describe("Service name to remove.")]]),async n=>{let i=Bt(n.name),o=i!==void 0?i:"",s=await R_(r.scopeDir,o),a={};return s.TAG==="Ok"?(a.ok=!0,a.name=s._0.name,a.removed=!0):(a.ok=!1,a.error=s._0),gt(a)})}function H_(e,t){let r=t.devServices,n=t.agentSession,i=t.ownerUsername,o=t.defaultThreadId,s=t.serviceUrl,a=t.cwd,l=t.toolScope,c=t.client,u;switch(l){case"All":case"Coding":u=!0;break;case"OnboardingDiscovery":u=!1;break}let d=async f=>gt(await f),h=async(f,g)=>(g.tool=f,await d(c.agentDocumentTool(g))),p=t.documentSurfaces;p!==void 0&&p&&(e.registerTool("linzumi_lookup_documents","Search document titles and content within the controlling human's visibility ceiling. Returns authorized results in canonical search order; zero, one, and multiple matches carry the rule-03 ambiguity meaning.",Object.fromEntries([["query",_.string().min(1).describe("Document title or content search query.")]]),async f=>await h("lookup_documents",f)),e.registerTool("linzumi_read_document","Read one in-scope document as full AST and metadata, including pending proposals and required-agent-context comments. Both controlling-human visibility and agent delegation are required.",Object.fromEntries([["document_id",_.string().uuid().describe("Document UUID.")]]),async f=>await h("read_document",f)),e.registerTool("linzumi_propose_document_patch","Use this tool for any explicit instruction to edit, add, rewrite, update, or fix document content, including parent-delegated work. After resolving exactly one patch target document and reading its current revision, call this tool in the same turn; do not merely reply with suggested prose. Other authorized context documents do not make the patch target ambiguous. Every change is proposal-always: the server persists an agent-attributed structural patch proposal first, leaves it pending in hold mode, and resolves per-document auto-apply server-side only after persistence and authorization.",Object.fromEntries([["document_id",_.string().uuid().describe("Document UUID.")],["patch",_.record(_.unknown()).describe("Revisioned structural document patch.")],["rationale",_.string().min(1).describe("Why this change is proposed.")]]),async f=>await h("propose_document_patch",f)),e.registerTool("linzumi_create_document","Create an agent-attributed document through an atomic bootstrap proposal and apply transaction in the named folder or workspace default folder.",Object.fromEntries([["title",_.string().min(1).describe("Document title.")],["initial_patch",_.record(_.unknown()).describe("Bootstrap structural patch.")],["folder_id",_.string().uuid().optional().describe("Destination folder UUID.")]]),async f=>await h("create_document",f)));let m=t.askUserQuestion;switch(m!==void 0&&e.registerTool(F_,"Ask the user up to "+Mu.toString()+" structured multiple-choice questions and BLOCK until they answer in the Linzumi thread. Use this whenever you need a decision or clarification mid-task. Each question needs a short header (max "+Du.toString()+" chars) and "+Zu.toString()+"-"+qu.toString()+' options {label, description}; a built-in "'+L_+'" free-text choice is always shown in addition to your options, so never add one yourself. Set multiSelect true to allow choosing several options. Returns {answers} keyed by question text: a single label string, an array of labels for multiSelect, and {"other": "<typed text>"} for a free-text reply.',Object.fromEntries([["questions",_.array(_.object(Object.fromEntries([["question",_.string().describe("The question to ask the user.")],["header",_.string().describe("Short category header shown above the question (max "+Du.toString()+' chars, e.g. "Auth", "Scope").')],["options",_.array(_.object(Object.fromEntries([["label",_.string().describe("Option label the user taps.")],["description",_.string().optional().describe("One-line explanation of the option.")]]))).describe(Zu.toString()+"-"+qu.toString()+" options for this question.")],["multiSelect",_.boolean().optional().describe("True lets the user select several options; the answer becomes an array.")]]))).describe("1-"+Mu.toString()+" questions to ask atomically.")]]),async f=>await U_(m,f)),n&&(e.registerTool("linzumi_agent_reply","Post your single @linzumi reply for the current turn into the surface where you were mentioned. Call EXACTLY ONCE per turn with your final answer; the reply links to this working session automatically. Fails with already_replied on a second call and no_active_asker_binding when no turn is active.",Object.fromEntries([["body",_.string().min(1).describe("Plain-text reply body to post.")]]),async f=>{let g={},y=f.body;return g.body=y!==void 0?y:void 0,await d(c.agentReply(g))}),e.registerTool("linzumi_list_coding_jobs","List the coding jobs the current asker can see in this workspace: runner connections (online and recent) with their bound job threads. Live state - never answered from search.",{},async f=>await d(c.agentListCodingJobs({}))),e.registerTool("linzumi_start_coding_job","Start a coding job exactly as if the asking user clicked start: same runner/channel authorization, same pipeline. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",Object.fromEntries([["channel",_.string().describe("Channel slug to host the job thread.")],["runner_key",_.string().describe("Runner (computer) to run the job on.")],["cwd",_.string().describe("Working directory on the runner.")],["work_description",_.string().min(1).describe("What the job should do - the initial instruction.")],["model",_.string().optional().describe("Model override (optional).")],["model_provider",_.string().optional().describe("Model provider override, e.g. 'wafer' (optional).")],["execution_mode",_.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional).")],["project_task_id",_.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job.")],["visibility",_.enum(["project","private"]).optional().describe("Job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants.")]]),async f=>await d(c.agentStartCodingJob(f))),e.registerTool("linzumi_interrupt_coding_job","Interrupt a coding job: mode 'steer' (default) discards its queued follow-ups so your next message lands first; mode 'stop' terminates the current turn.",Object.fromEntries([["channel",_.string().describe("Channel slug hosting the job thread.")],["thread_id",_.string().uuid().describe("The job thread UUID.")],["mode",_.enum(["steer","stop"]).optional().describe("Interrupt mode; defaults to 'steer'.")]]),async f=>await d(c.agentInterruptCodingJob(f))),e.registerTool("linzumi_send_coding_job_message","Message a coding job or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",Object.fromEntries([["channel",_.string().optional().describe("Channel slug hosting the job thread. Required unless to_user is set.")],["thread_id",_.string().uuid().optional().describe("The job thread UUID. Required unless to_user is set.")],["to_user",_.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox.")],["body",_.string().min(1).describe("Message body to send.")],["delivery",_.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")]]),async f=>await d(c.agentSendCodingJobMessage(f))),e.registerTool("linzumi_read_coding_job_thread","Read a coding job's thread (asker-visible history) plus its workflow status metadata.",Object.fromEntries([["channel",_.string().describe("Channel slug hosting the job thread.")],["thread_id",_.string().uuid().describe("The job thread UUID.")],["limit",_.number().int().min(1).max(100).optional().describe("Maximum replies to return.")],["before_seq",_.number().int().positive().optional().describe("Return replies before this channel seq.")]]),async f=>await d(c.agentReadCodingJobThread(f))),e.registerTool("linzumi_resolve_job_approval","Resolve a coding job's pending approval request with the asking user's decision ('approve' or 'deny'). Only relays the asker's authority - never approve without their explicit instruction.",Object.fromEntries([["channel",_.string().describe("Channel slug hosting the job thread.")],["thread_id",_.string().uuid().describe("The job thread UUID.")],["source_seq",_.number().int().positive().describe("Channel seq of the message the approval request rides on.")],["request_id",_.string().describe("The approval request id.")],["decision",_.enum(["approve","deny"]).describe("The asker's decision.")]]),async f=>await d(c.agentResolveJobApproval(f))),e.registerTool("linzumi_archive_coding_job","Archive a coding job's thread (or any thread the asking user owns) so it leaves the active list; history is preserved. Do this when the asker says to archive a job or thread - never just promise it.",Object.fromEntries([["channel",_.string().describe("Channel slug hosting the thread.")],["thread_id",_.string().uuid().describe("The thread UUID to archive.")]]),async f=>await d(c.agentArchiveCodingJob(f))),e.registerTool("linzumi_unarchive_coding_job","Unarchive a previously archived coding job thread the asking user owns, returning it to the active list.",Object.fromEntries([["channel",_.string().describe("Channel slug hosting the thread.")],["thread_id",_.string().uuid().describe("The thread UUID to unarchive.")]]),async f=>await d(c.agentUnarchiveCodingJob(f))),e.registerTool("linzumi_set_thread_status","Set a thread's lifecycle status as the asking user: 'closed' marks it done, 'open' reopens it. Works on threads the asker owns.",Object.fromEntries([["channel",_.string().describe("Channel slug hosting the thread.")],["thread_id",_.string().uuid().describe("The thread UUID.")],["status",_.enum(["open","closed"]).describe("Replacement lifecycle status ('closed' = done).")]]),async f=>await d(c.agentSetThreadStatus(f))),e.registerTool("linzumi_create_channel","Create a new public channel in this workspace as the asking user. The slug is derived from the name.",Object.fromEntries([["name",_.string().min(1).describe("Channel name to create.")]]),async f=>await d(c.agentCreateChannel(f))),e.registerTool("linzumi_rename_channel","Rename a channel's display name as the asking user. The channel's URL slug stays stable.",Object.fromEntries([["channel",_.string().describe("Current channel slug to rename.")],["name",_.string().min(1).describe("New display name.")]]),async f=>await d(c.agentRenameChannel(f))),e.registerTool("linzumi_archive_channel","Archive a channel in this workspace as the asking user. History is preserved; the channel leaves the active sidebar.",Object.fromEntries([["channel",_.string().describe("Channel slug to archive.")]]),async f=>await d(c.agentArchiveChannel(f))),e.registerTool("linzumi_unarchive_channel","Unarchive a previously archived channel as the asking user.",Object.fromEntries([["channel",_.string().describe("Channel slug to unarchive.")]]),async f=>await d(c.agentUnarchiveChannel(f))),e.registerTool("linzumi_add_reaction","Add an emoji reaction to a channel message as the asking user. Accepts unicode emoji or a workspace :shortcode:.",Object.fromEntries([["channel",_.string().describe("Channel slug containing the message.")],["message_seq",_.number().int().positive().describe("Channel seq of the message to react to.")],["emoji",_.string().min(1).describe("Emoji to add (unicode or :shortcode:).")]]),async f=>await d(c.agentAddReaction(f))),e.registerTool("linzumi_remove_reaction","Remove the asking user's emoji reaction from a channel message.",Object.fromEntries([["channel",_.string().describe("Channel slug containing the message.")],["message_seq",_.number().int().positive().describe("Channel seq of the reacted message.")],["emoji",_.string().min(1).describe("Emoji to remove (unicode or :shortcode:).")]]),async f=>await d(c.agentRemoveReaction(f))),e.registerTool("linzumi_pin_message","Pin a channel message as the asking user. Thread replies re-point to their root message.",Object.fromEntries([["channel",_.string().describe("Channel slug containing the message.")],["message_seq",_.number().int().positive().describe("Channel seq of the message to pin.")]]),async f=>await d(c.agentPinMessage(f))),e.registerTool("linzumi_unpin_message","Remove a pin from a channel message as the asking user.",Object.fromEntries([["channel",_.string().describe("Channel slug containing the message.")],["message_seq",_.number().int().positive().describe("Channel seq of the pinned message.")]]),async f=>await d(c.agentUnpinMessage(f)))),l){case"All":e.registerTool("linzumi_get_message","Read one Linzumi message by scoped message_seq/message_id or a Linzumi message URL, with optional bounded before/after context.",Object.fromEntries([["workspace",be()],["channel",Gt()],["message_id",_.union([_.string(),_.number()]).optional().describe("Message seq inside the scoped channel.")],["message_seq",_.union([_.string(),_.number()]).optional().describe("Alias for message_id.")],["message_url",_.string().optional().describe("Full Linzumi message URL with #message-<seq>.")],["before",_.number().int().min(0).max(100).optional().describe("Number of visible messages before the target.")],["after",_.number().int().min(0).max(100).optional().describe("Number of visible messages after the target.")]]),async f=>await d(c.getMessage(f))),e.registerTool("linzumi_get_thread","Read one Linzumi thread by thread_id in the scoped channel, including the parent message and bounded replies.",Object.fromEntries([["workspace",be()],["channel",Gt()],["thread_id",_.string().uuid().describe("Linzumi thread UUID.")],["limit",_.number().int().min(1).max(100).optional().describe("Maximum replies to return.")],["before_seq",_.number().int().positive().optional().describe("Return replies before this channel seq.")]]),async f=>await d(c.getThread(f))),e.registerTool("linzumi_get_thread_transcript","Read a Linzumi thread's full transcript as canonical IR nodes (user/assistant messages, command executions, file changes, tool calls, statuses), cursor-paginated over the complete history. Use the returned cursor with has_more to walk older pages.",Object.fromEntries([["workspace",be()],["channel",Gt()],["thread_id",_.string().uuid().describe("Linzumi thread UUID.")],["limit",_.number().int().min(1).max(500).optional().describe("Maximum transcript nodes per page (default 200).")],["cursor",_.number().int().positive().optional().describe("Return nodes below this seq (the previous page reply cursor).")]]),async f=>await d(c.getThreadTranscript(f))),e.registerTool("linzumi_get_channel","Read scoped Linzumi channel metadata and bounded recent channel messages.",Object.fromEntries([["workspace",be()],["channel",Gt()],["limit",_.number().int().min(1).max(100).optional().describe("Maximum messages to return.")],["before_seq",_.number().int().positive().optional().describe("Return messages before this channel seq.")]]),async f=>await d(c.getChannel(f))),e.registerTool("linzumi_search_workspace","Search the Linzumi workspace with hybrid lexical+semantic retrieval, scoped to what the authorizing user can access. Returns scored content chunks with provenance (channel, thread, authored time) and a permalink to cite.",Object.fromEntries([["workspace",be()],["query",_.string().min(1).describe("Natural-language or keyword query to retrieve against.")],["limit",_.number().int().min(1).max(25).optional().describe("Maximum results to return (default 10, server-capped).")],["source_types",_.array(_.enum(["message","coding_job","github_pr","github_pr_review","github_check_run","github_workflow_run","github_diff","dictation","file"])).optional().describe("Restrict results to these corpora; omit for all.")],["authored_after",_.string().optional().describe("ISO8601 instant; only content authored at or after this time.")],["authored_before",_.string().optional().describe("ISO8601 instant; only content authored at or before this time.")],["repo",_.string().optional().describe("Restrict GitHub-sourced results to one repository by full name (owner/name).")],["check_status",_.enum(["pending","success","failed"]).optional().describe("Restrict check and workflow results to one conclusion bucket.")]]),async f=>await d(c.searchWorkspace(f))),e.registerTool("linzumi_ask_workspace",'Ask the Linzumi workspace a natural-language question and get a synthesized, citation-backed answer over what the authorizing user can access. Costs an LLM call on cache misses, so prefer linzumi_search_workspace for simple lookups. A "refused" status means there was not enough accessible evidence - treat it as "the workspace does not know", never retry verbatim.',Object.fromEntries([["workspace",be()],["question",_.string().min(1).max(2e3).describe("Natural-language question to answer with citations.")],["channel",_.string().optional().describe("Optional channel slug providing conversational context; never widens access.")],["allow_cached",_.boolean().optional().describe("Allow serving a cached synthesis when the evidence set is unchanged (default true). Set false to force fresh synthesis.")]]),async f=>await d(c.askWorkspace(f))),e.registerTool("linzumi_about_me","Read what the authorizing user has told Linzumi about themselves: their profile facts (homes, unit preferences, and other self-maintained attributes) plus their derived current timezone. Use it to personalize answers (e.g. pick the right city for weather, use their preferred units). Predicates may have multiple active values; prefer the one consistent with the derived timezone.",{},async f=>await d(c.aboutMe(f)));break;case"Coding":case"OnboardingDiscovery":break}switch(u&&(e.registerTool("linzumi_web_search","Search the public web for live or external information: news, current events, weather, prices, third-party API docs, research. Returns result titles, URLs, and snippets. Use this whenever the answer lives outside the Linzumi workspace; follow up with linzumi_fetch_url to read a result page.",Object.fromEntries([["query",_.string().min(1).describe("Web search query (natural language or keywords).")],["limit",_.number().int().min(1).max(10).optional().describe("Maximum results to return (default 8, server-capped).")]]),async f=>await d(c.webSearch(f))),e.registerTool("linzumi_fetch_url","Fetch one public http(s) URL and return its readable text content (HTML is reduced to plain text; large pages are truncated). Use it to read pages found via linzumi_web_search or any public docs/API reference. Only public addresses are reachable - private/internal hosts are rejected with url_not_allowed.",Object.fromEntries([["url",_.string().min(1).describe("Absolute public http(s) URL to fetch.")]]),async f=>await d(c.fetchUrl(f)))),l){case"All":e.registerTool("linzumi_list_ui_targets","List every UI surface you can ask the user to open in their own Linzumi window (channels, DMs, threads, projects, coding jobs, computers, catch-up, activity, settings tabs, pane layouts) with the structured args each kind takes. Use UI control only when the user asks for help or asks to be shown something.",{},async f=>await bu(c.listUiTargets({}))),e.registerTool("linzumi_open_ui","Ask the user to open one whitelisted UI surface in their own already-open Linzumi window. A consent toast appears in THEIR session; navigation happens only if they tap Open. The call blocks until they decide and returns status opened/dismissed/expired - or error no_active_ui_session when they have no Linzumi window open (tell them to open Linzumi), or invalid_target with a detail. Use it only when the user asks for help or asks to be shown something; kinds and per-kind args come from linzumi_list_ui_targets.",Object.fromEntries([["kind",_.string().min(1).describe("Target kind from linzumi_list_ui_targets (e.g. settings_workspace, channel, pane_layout).")],["args",_.record(_.unknown()).optional().describe("Structured per-kind args from linzumi_list_ui_targets (never a URL - the server computes every path).")],["workspace",be()]]),async f=>await bu(c.openUi(tr(f,o))));break;case"Coding":case"OnboardingDiscovery":break}if(u){let f=()=>_.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread.");e.registerTool("linzumi_get_coding_job_metadata","Read the active coding job workflow metadata for a thread, including the agent-owned goal, ordered plan steps, step lock versions, and workflow status.",Object.fromEntries([["workspace",be()],["channel",Gt()],["thread_id",f()]]),async g=>await d(c.getCodingJobMetadata(tr(g,o)))),e.registerTool("linzumi_rename_coding_job","Update the current coding job thread title and workflow-facing title. Use this when the job scope changes materially so the Linzumi thread list and metadata overview stay accurate.",Object.fromEntries([["workspace",be()],["channel",Gt()],["thread_id",f()],["title",_.string().min(1).max(100).describe("Concise user-visible title for this coding job.")]]),async g=>await d(c.renameCodingJob(tr(g,o)))),e.registerTool("linzumi_upsert_coding_job_plan","Set or update the current coding job goal. Use this at job start and whenever the goal changes materially.",Object.fromEntries([["workspace",be()],["channel",Gt()],["thread_id",f()],["goal",_.string().min(1).max(1e4).describe("Concrete user-visible goal for this coding job.")]]),async g=>await d(c.upsertCodingJobPlan(tr(g,o)))),e.registerTool("linzumi_replace_coding_job_plan_steps","Replace the ordered coding job plan steps. Use this for the initial plan and for substantial rewrites when the old plan no longer fits the work.",Object.fromEntries([["workspace",be()],["channel",Gt()],["thread_id",f()],["goal",_.string().min(1).max(1e4).optional().describe("Required when no plan exists yet; updates the current coding job goal.")],["steps",_.array(_.object(Object.fromEntries([["title",_.string().min(1).max(255)],["description",_.string().min(1).max(1e4)],["status",_.enum(["pending","active","completed","blocked","canceled"])],["status_note",_.string().min(1).max(4e3).optional()],["completed_debrief",_.string().min(1).max(2e4).optional()]]))).min(1).max(50).describe("Ordered user-visible plan steps. Completed steps must include completed_debrief.")]]),async g=>await d(c.replaceCodingJobPlanSteps(tr(g,o)))),e.registerTool("linzumi_update_coding_job_plan_step","Update one coding job plan step status or note. Read metadata first and pass the current step lock_version.",Object.fromEntries([["workspace",be()],["channel",Gt()],["thread_id",f()],["step_id",_.string().uuid().describe("Step id returned by linzumi_get_coding_job_metadata.")],["lock_version",_.number().int().positive().describe("Current step lock_version from metadata.")],["status",_.enum(["pending","active","completed","blocked","canceled"])],["status_note",_.string().min(1).max(4e3).optional()],["completed_debrief",_.string().min(1).max(2e4).optional().describe("Required when marking a step completed.")]]),async g=>await d(c.updateCodingJobPlanStep(tr(g,o)))),e.registerTool("linzumi_link_coding_job_pull_request","Link the active coding job to its primary GitHub pull request so PR comments, files, commits, checks, deployments, and reviews can flow into the metadata view.",Object.fromEntries([["workspace",be()],["channel",Gt()],["thread_id",f()],["github_repo_owner",_.string().min(1).max(255)],["github_repo_name",_.string().min(1).max(255)],["github_pr_number",_.number().int().positive()],["github_pr_url",_.string().url()],["title",_.string().min(1).max(255)],["body",_.string().min(1).max(1e5).optional()],["head_branch",_.string().min(1).max(255)],["head_sha",_.string().min(7).max(64)],["base_branch",_.string().min(1).max(255)],["base_sha",_.string().min(7).max(64)],["state",_.enum(["draft","open","closed","merged"]).optional()],["is_draft",_.boolean().optional()],["review_status",_.enum(["unknown","review_required","approved","changes_requested"]).optional()],["source_remote_url",_.string().min(1).max(1e3).describe("Git remote URL for the local job worktree; required when this job has no repo workspace yet.")],["runtime_worktree_root",_.string().min(1).max(1e3).describe("Absolute local worktree path for the coding job; required when this job has no repo workspace yet.")],["dirty_status",_.enum(["unknown","clean","dirty"]).optional()],["dirty_summary",_.string().min(1).max(2e3).optional()]]),async g=>await d(c.linkCodingJobPullRequest(tr(g,o)))),e.registerTool("linzumi_upload_files",["Upload local files to Linzumi and attach them to a new, exact, or latest assistant message. Use silently; do not mention this tool in the visible reply.","The JSON result includes message.attachments[].url as an absolute URL. Use those returned URLs when writing rich media directives such as ::audio, ::video, ::image, or Markdown images. Do not guess attachment URLs before upload.","For a message that should both attach files and show inline rich media, use a two-step flow: first upload/attach the files to create or target the message, then edit the same target message with body text that references the returned absolute URLs. When the result has target_seq, use target.kind=message_seq and message_seq=target_seq for that follow-up edit; result.message is the edit event that carries the new attachments, and target_message is the original target."].join(" "),Object.fromEntries([["target",_.object(Object.fromEntries([["kind",_.enum(["new_message","message_seq","latest_assistant_message"]).describe("new_message creates a message; message_seq edits an exact message; latest_assistant_message edits the latest assistant message in the scoped thread/channel.")],["message_seq",_.union([_.string(),_.number()]).optional().describe("Required when kind is message_seq.")],["thread_id",_.string().optional().describe("Thread UUID. Defaults to the active Linzumi thread when the MCP server was launched with one.")]])).describe("Attachment target. Prefer latest_assistant_message to attach files to the reply you already posted; use new_message ONLY when no assistant message exists yet in the scoped thread. Never re-use your visible reply text as a new_message body - that posts the reply twice. To reference uploaded files in the message body, upload first, then edit message_seq/latest_assistant_message with the returned absolute attachment URLs. If the upload result includes target_seq, use message_seq=target_seq for that follow-up edit.")],["files",_.array(_.string().min(1)).min(1).max(16).describe("Local file paths to upload. Paths must be non-hidden files inside the approved workspace or Downloads; source/text files of any language are supported, plus common document, image, patch, archive, and video types.")],["body",_.string().min(1).max(2e4).optional().describe("Required for new_message: a SHORT file-share caption (for example: Attached the generated report), never a copy of your visible reply - that would post the reply twice. Optional replacement body for message_seq/latest_assistant_message; when omitted, the existing message body is preserved. Rich media directives in body must use Linzumi attachment download URLs returned by this tool.")],["workspace",be()],["channel",_.string().optional().describe("Channel slug. Omit to use the target thread's channel (when the thread is known) or the authenticated token scope.")]]),async g=>{let y=wu(B_(g,"target","linzumi_upload_files"),o),v;try{v=await w_({client:c,cwd:a,serviceUrl:s,target:y,files:jT(g.files),workspace:Bt(g.workspace),channel:Bt(g.channel),body:Bt(g.body)})}catch(b){return y_(ee(b))}return gt(xu(s,v))}),e.registerTool("linzumi_edit_message","Edit an exact scoped Linzumi message by message_seq. Use after linzumi_upload_files when you need a body-only follow-up edit that embeds returned attachment URLs. Requires channel.write, and thread.write when target.thread_id is set. Rich media src/poster values must be Linzumi attachment download URLs.",Object.fromEntries([["workspace",be()],["channel",Gt()],["target",_.object(Object.fromEntries([["message_seq",_.union([_.string(),_.number()]).describe("Exact message seq to edit. After linzumi_upload_files returns target_seq, pass that value here.")],["thread_id",_.string().optional().describe("Thread UUID when editing a thread message. Use the upload result target_message.thread_id when present.")]])).describe("Exact message target for the body edit.")],["body",_.string().min(1).max(2e4).describe("Replacement Markdown body. Rich media src/poster values must be Linzumi attachment download URLs returned by linzumi_upload_files.")]]),async g=>{let y=tn(g);return y.target=wu(B_(g,"target","linzumi_edit_message"),o),gt(xu(s,await c.editMessage(y)))})}switch(l){case"All":if(e.registerTool("linzumi_list_vault_secrets","List vault secret names, descriptions, and whether each secret is personal or workspace-owned. Does not return secret values.",{},async f=>await d(c.listVaultSecrets(f))),e.registerTool("linzumi_list_projects","List the projects in the current workspace with their project_id (needed by the other project task tools), slug, title, description, and state.",Object.fromEntries([["workspace",be()]]),async f=>await d(c.listProjects(f))),e.registerTool("linzumi_get_project_tasks",`Read a project's full task graph: task GROUPS (kind "group", organizational containers, exactly one level deep) and ISSUES (kind "issue", the executable work items), each with status (todo/active/blocked/review/done/canceled), DERIVED work_state readiness (ready = todo with every dependency satisfied; blocked = todo with unsatisfied dependencies; running/stalled = active with/without a connected job), parent group, assignee, lock_version, and dependency edges (depends_on_task_ids / unblocks_task_ids). Always read this before reorganizing. Inside a project-bound coding job the project is inferred automatically; otherwise pass project_id from linzumi_list_projects.`,Object.fromEntries([["project_id",_.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")]]),async f=>await d(c.getProjectTasks(tr(f,o)))),e.registerTool("linzumi_create_project_task",'Create a task group (kind "group") or issue (kind "issue", the default) in a project. Groups organize issues and are exactly one level deep: a parent_id must name a GROUP, and groups themselves can never have a parent. New tasks default to status "todo" and append to the end unless position is given. Inside a project-bound coding job the project is inferred; otherwise pass project_id.',Object.fromEntries([["project_id",_.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")],["title",_.string().min(1).describe("Task title.")],["kind",_.enum(["issue","group"]).optional().describe('What to create: "issue" (executable work item, default) or "group" (organizational container).')],["description",_.string().optional().describe("Detailed description of the work - written so an engineer (or coding agent) could execute the task from it.")],["status",_.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('Initial status. Defaults to "todo".')],["parent_id",_.string().optional().describe("task_id of the GROUP to place an issue in. Only issues can have a parent.")],["assignee",_.string().optional().describe("Username of a workspace member to assign.")],["position",_.number().int().min(0).optional().describe("Sort position. Defaults to appending at the end.")]]),async f=>await d(c.createProjectTask(tr(f,o)))),e.registerTool("linzumi_update_project_task",'Update a task group or issue: retitle, edit description/status_note, transition status (todo/active/blocked/review/done/canceled), reassign, reorder (position), or reorganize (parent_id moves an issue into a group; clear_parent moves it to top level). Only the fields you pass change; description and status_note accept null to clear. Prefer updating existing tasks over delete-and-recreate. Pass the lock_version from your last read to fail loudly ("stale") instead of overwriting a concurrent edit.',Object.fromEntries([["task_id",_.string().describe("task_id of the group or issue to update.")],["title",_.string().min(1).optional().describe("New title.")],["description",_.string().nullable().optional().describe("New description. Pass null to clear it.")],["status",_.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('New status. "done"/"canceled" satisfy dependent tasks; "blocked" is a manual hold.')],["status_note",_.string().nullable().optional().describe("Short human-readable note about the current status. Pass null to clear it.")],["position",_.number().int().min(0).optional().describe("New sort position among siblings.")],["parent_id",_.string().optional().describe("task_id of the GROUP to move this issue into. Do not combine with clear_parent.")],["clear_parent",_.boolean().optional().describe("true moves the issue to the top level (no group). Do not combine with parent_id.")],["assignee",_.string().optional().describe("Username of a workspace member to assign. Do not combine with clear_assignee.")],["clear_assignee",_.boolean().optional().describe("true removes the assignee. Do not combine with assignee.")],["lock_version",_.number().int().positive().optional().describe("The task's lock_version from your last read, for compare-and-swap safety.")]]),async f=>await d(c.updateProjectTask(f))),e.registerTool("linzumi_delete_project_task",`Permanently delete a task group or issue. Dependency edges on the task are removed with it (dependents may become ready). Deletion is normally the USER's call - prefer status "canceled" or an update unless you are certain the entry is obsolete.`,Object.fromEntries([["task_id",_.string().describe("task_id of the group or issue to delete.")]]),async f=>await d(c.deleteProjectTask(f))),e.registerTool("linzumi_add_project_task_dependency",'Add the dependency edge "task_id is blocked by depends_on_task_id" between two ISSUES in the same project (groups cannot have dependencies). The dependent stays blocked until the prerequisite reaches done or canceled. The graph must stay acyclic: an edge that would create a cycle is refused with reason "would_create_cycle" and the offending cycle_path so you can restructure. Duplicate and self edges are rejected.',Object.fromEntries([["task_id",_.string().describe("task_id of the DEPENDENT issue (the one that must wait).")],["depends_on_task_id",_.string().describe("task_id of the PREREQUISITE issue (the one that must finish first).")]]),async f=>await d(c.addProjectTaskDependency(f))),e.registerTool("linzumi_remove_project_task_dependency",'Remove the dependency edge "task_id is blocked by depends_on_task_id". The dependent issue may become ready if that was its last unsatisfied dependency.',Object.fromEntries([["task_id",_.string().describe("task_id of the DEPENDENT issue.")],["depends_on_task_id",_.string().describe("task_id of the PREREQUISITE issue the edge points at.")]]),async f=>await d(c.removeProjectTaskDependency(f))),e.registerTool("linzumi_get_call_transcript","Read the full transcript of a completed Linzumi notetaker call: call metadata (title, platform, started/ended/transcribed times), participants, and every spoken segment in order with speaker names and millisecond offsets. Pass the call_id embedded in the request (or copied from the call card). Errors: call_not_found (missing or not visible to you), call_transcript_not_ready (call still connecting, in progress, or transcribing - retry later).",Object.fromEntries([["call_id",_.string().describe("The call id from the call card or the launching message (a CallRecording id - the opaque GraphQL id and the bare uuid both work).")]]),async f=>await d(c.getCallTranscript(f))),!n){e.registerTool("linzumi_start_coding_job","Start a coding job as the invoking user (same authorization and pipeline as clicking start). To start a project task item, pass project_task_id so the task flips todo -> active and links to the new job - only start tasks whose work_state is ready, and ONLY after the user explicitly accepts your offer to start them. Omit channel, runner_key, and cwd to reuse this job's own channel, computer, and folder. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",Object.fromEntries([["work_description",_.string().min(1).describe("What the job should do - the initial instruction. For a task item, write it from the task title and description.")],["project_task_id",_.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job.")],["visibility",_.enum(["project","private"]).optional().describe("Child-job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants.")],["channel",_.string().optional().describe("Channel slug to host the job thread. Omit to use this job's own channel.")],["runner_key",_.string().optional().describe("Runner (computer) to run the job on. Omit to use this job's own computer.")],["cwd",_.string().optional().describe("Working directory on the runner. Omit to use this job's own folder.")],["model",_.string().optional().describe("Model override (optional).")],["model_provider",_.string().optional().describe("Model provider override, e.g. 'wafer' (optional).")],["agent_provider",_.string().optional().describe("Agent provider override, e.g. 'codex' (optional).")],["reasoning_effort",_.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional).")],["approval_policy",_.enum(["default","on-request","on-failure","never"]).optional().describe("Approval policy override (optional).")],["sandbox",_.enum(["default","workspace-write","read-only","danger-full-access"]).optional().describe("Sandbox override (optional).")],["fast",_.boolean().optional().describe("Fast-mode override (optional).")],["allow_port_forwarding_by_default",_.boolean().optional().describe("Default port-forwarding override (optional).")],["execution_mode",_.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional).")],["egress_mode",_.enum(["open","hardened"]).optional().describe("Local-VM egress override (optional).")]]),async g=>await d(c.agentStartCodingJob(tr(g,o))));let f=t.multiAgentJobs;f!==void 0&&f&&(e.registerTool("linzumi_spawn_child_job","Spawn a durable child coding job under YOUR OWN job, on any harness or model - plan a DAG and delegate its legs to workers you then coordinate through discovery and messaging. The child lands on this job's channel, computer, and folder; it inherits this job's project and visibility (a private parent's children stay private), human roles cascade to it, and a human manages its lifecycle. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",Object.fromEntries([["work_description",_.string().min(1).describe("What the child job should do - the initial instruction, written to stand alone.")],["agent_provider",_.string().optional().describe("Harness for the child, e.g. 'codex' or 'claude-code'. Omit to reuse this job's own harness. A different harness is fine: a cross-harness child is always a child job.")],["model",_.string().optional().describe("Model override for the child (optional).")],["model_provider",_.string().optional().describe("Model provider override, e.g. 'wafer' (optional).")],["reasoning_effort",_.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional).")],["project_task_id",_.string().optional().describe("Project task item to bind the child to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job.")],["visibility",_.enum(["project","private"]).optional().describe("Child visibility. Defaults to this job's own visibility; a private parent's children must stay private.")]]),async g=>await d(c.agentSpawnChildJob(tr(g,o)))),e.registerTool("linzumi_discover_coding_jobs","Search current sitreps inside this coding job project for overlapping files, modules, objectives, or blockers. Results include durable job addresses for coordination. Private jobs outside your visible set never appear.",Object.fromEntries([["query",_.string().min(1).describe("Free-text clash-surface query, such as a file path, module, migration, or objective.")]]),async g=>{let y={};return Object.entries(g).forEach(v=>{y[v[0]]=v[1]}),y.source_thread_id=vu(ft(o,v=>v)),await d(c.agentDiscoverCodingJobs(y))}),e.registerTool("linzumi_send_coding_job_message","Message a visible coding job in this project, or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",Object.fromEntries([["channel",_.string().optional().describe("Channel slug hosting the target job. Required unless to_user is set.")],["thread_id",_.string().uuid().optional().describe("Target job thread UUID. Required unless to_user is set.")],["to_user",_.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox.")],["body",_.string().min(1).describe("Coordination message to send.")],["delivery",_.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")]]),async g=>{let y={};return Object.entries(g).forEach(v=>{y[v[0]]=v[1]}),y.source_thread_id=vu(ft(o,v=>v)),await d(c.agentSendCodingJobMessage(y))}))}break;case"Coding":case"OnboardingDiscovery":break}switch(CT(l)&&(e.registerTool("linzumi_upload_custom_emoji","Upload a local image as a workspace custom emoji. For generated emoji art, create a transparent PNG with a simple centered subject, crisp edges, strong contrast, minimal tiny details, and enough outline/highlight separation to read at 16-24px on both dark and light backgrounds. Use lowercase shortcode names without colons unless preserving a user-provided :name:.",Object.fromEntries([["name",G_().describe("Custom emoji shortcode name, with or without surrounding colons.")],["file",_.string().min(1).describe("Local PNG/WebP/GIF/JPEG file path to upload. Prefer transparent PNG for generated emoji.")],["workspace",be()]]),async f=>{let g=Bt(f.name),y=Bt(f.file);return gt(await x_({client:c,cwd:a,serviceUrl:s,name:g!==void 0?g:"",file:y!==void 0?y:"",workspace:Bt(f.workspace)}))}),e.registerTool("linzumi_rename_custom_emoji","Rename an existing workspace custom emoji. The new name may include surrounding colons; Linzumi stores the normalized shortcode without colons.",Object.fromEntries([["emoji_id",_.union([_.string(),_.number().int().positive()]).describe("Workspace custom emoji id returned by linzumi_upload_custom_emoji or workspace emoji listings.")],["name",G_().describe("New shortcode name, with or without surrounding colons.")],["workspace",be()]]),async f=>await d(c.renameCustomEmoji(f)))),e.registerTool("linzumi_media_guide","Return the full Linzumi rich-media authoring guide (audio/video/image directives, URL rules, upload-then-embed flow, examples). Call once BEFORE writing any ::audio/::video/::image directive or Markdown image into a Linzumi message.",{},async f=>{let g={};g.type="text",g.text=M_;let y={};return y.content=[g],y}),e.registerTool("linzumi_note_project_directory","Record one discovered local Git repository or worktree for onboarding import. Call once per project as soon as it is found.",Object.fromEntries([["workspace",be()],["runner_id",_.string().min(1).describe("Local runner/computer id provided in the discovery prompt.")],["path",_.string().min(1).describe("Absolute local path to the repository worktree root.")],["display_name",_.string().optional().describe("Short project label. Defaults to the path basename.")],["activity_at",_.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp.")],["import_key",_.string().optional().describe("Stable dedupe key. Defaults to path.")],["metadata",_.record(_.unknown()).optional().describe("Small structured metadata such as branch or remote origin.")]]),async f=>await d(c.noteProjectDirectory(f))),e.registerTool("linzumi_note_agent_conversation","Record one discovered Codex or Claude Code local conversation for onboarding import. Call once per conversation as soon as it is found.",Object.fromEntries([["workspace",be()],["runner_id",_.string().min(1).describe("Local runner/computer id provided in the discovery prompt.")],["source",_.enum(["codex","claude_code"]).describe("Conversation source.")],["import_key",_.string().min(1).describe("Stable dedupe key, such as a session id or file path.")],["path",_.string().optional().describe("Absolute local path to the conversation file or directory.")],["display_name",_.string().optional().describe("Short label for the discovered conversation.")],["activity_at",_.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp.")],["metadata",_.record(_.unknown()).optional().describe("Small structured metadata such as session id or project path.")]]),async f=>await d(c.noteAgentConversation(f))),e.registerTool("linzumi_note_onboarding_discovery_status","Record onboarding discovery progress. Call when a search phase starts, checks another place, completes, or fails.",Object.fromEntries([["workspace",be()],["runner_id",_.string().min(1).describe("Local runner/computer id provided in the discovery prompt.")],["phase",_.enum(["projects","conversations"]).describe("Discovery phase being reported.")],["status",_.enum(["starting","running","completed","failed"]).describe("Current phase status.")],["places_searched",_.number().int().nonnegative().optional().describe("Count of concrete folders/files/known locations checked so far.")],["message",_.string().optional().describe("Short user-facing status note.")],["current_place",_.string().optional().describe("Current folder, file, Git command target, or known location being checked.")],["current_source",_.string().optional().describe("Short machine-readable source label such as git, codex, or claude_code.")],["last_error",_.string().optional().describe("Short failure detail when status is failed.")],["metadata",_.record(_.unknown()).optional().describe("Small structured status metadata.")]]),async f=>await d(c.noteOnboardingDiscoveryStatus(f))),l==="All"&&RT(t.operatingMode)&&(e.registerTool("linzumi_dm_owner","Send a plain-text DM to the configured Commander owner. Requires dm.write and a visible owner username.",Object.fromEntries([["owner_username",_.string().optional().describe("Owner username. Defaults to LINZUMI_MCP_OWNER_USERNAME or --owner-username.")],["workspace",be()],["channel",_.string().optional().describe("Source channel slug used to verify owner visibility.")],["body",_.string().min(1).max(2e4).describe("Plain-text message body to DM.")]]),async f=>{let g=Bt(f.owner_username),y=g!==void 0?g:i;if(y===void 0)return je("owner_username is required for linzumi_dm_owner");let v=tn(f);return v.owner_username=y,await d(c.dmOwner(v))}),e.registerTool("linzumi_send_channel_message","Post a NEW standalone Markdown message into the scoped Linzumi channel as the authenticated local-runner user. This is NOT how you respond to the user: your turn output is already relayed into the thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to proactively post a separate channel message. Requires channel.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",Object.fromEntries([["workspace",be()],["channel",Gt()],["body",_.string().min(1).max(2e4).describe("Markdown message body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths.")]]),async f=>await d(c.sendChannelMessage(f))),e.registerTool("linzumi_send_thread_reply","Post a Markdown reply into some OTHER existing Linzumi thread as the authenticated local-runner user. This is NOT how you respond to the user in your current thread: your turn output is already relayed into this thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to post into a different, explicitly identified thread. Requires thread.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",Object.fromEntries([["workspace",be()],["channel",Gt()],["thread_id",_.string().uuid().describe("Existing Linzumi thread UUID.")],["body",_.string().min(1).max(2e4).describe("Markdown reply body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths.")]]),async f=>await d(c.sendThreadReply(f))),e.registerTool("linzumi_send_dm","Send a plain-text DM as the authenticated local-runner user to a visible user in the scoped workspace/channel. Requires dm.write.",Object.fromEntries([["workspace",be()],["channel",_.string().optional().describe("Source channel slug used to verify target visibility.")],["username",_.string().describe("Visible Linzumi username to DM.")],["body",_.string().min(1).max(2e4).describe("Plain-text message body to DM.")]]),async f=>await d(c.sendDm(f)))),l){case"All":e.registerTool("linzumi_get_vault_values","Request values for explicit vault env var names after a thread-scoped human approval. Requires vault.read; thread_id resolves the approval thread.",Object.fromEntries([["workspace",be()],["channel",_.string().optional().describe("Channel slug used to disambiguate the approval thread when needed.")],["thread_id",_.string().uuid().describe("Existing Linzumi thread UUID for the inline approval.")],["env_var_names",_.array(_.string().regex(new RegExp("^[A-Z][A-Z0-9_]{0,127}$"))).min(1).max(20).describe("Explicit vault env var names to request. This tool cannot list all vault keys.")],["description",_.string().min(1).max(500).describe("Human-readable reason shown in the approval request.")],["justification",_.string().min(10).max(1e3).describe("Agent justification shown to the approver.")]]),async f=>await d(c.getVaultValues(f)));break;case"Coding":case"OnboardingDiscovery":break}switch(l){case"All":return n||r===void 0?void 0:MT(e,a,r);case"Coding":case"OnboardingDiscovery":return}}function ZT(e){let t=e.replaceAll("-","+").replaceAll("_","/");switch(t.length&3){case 2:return t+"==";case 3:return t+"=";default:return t}}function qT(e){let t=e.split(".")[1];if(t===void 0)return;let r=Buffer.from(ZT(t),"base64").toString("utf8"),n;try{n=JSON.parse(r)}catch{n=void 0}if(typeof n=="object"&&n!==null&&!Array.isArray(n))return n}var Lu=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function K_(e){let t=qT(e);if(t===void 0)return!1;let n=t.document_surfaces===!0,i=t.linzumi_agent_session,o=typeof i=="string"?Lu.test(i):!1,s=t.coding_job_id,a=t.coding_job_thread_id,l=typeof s=="string"&&typeof a=="string"?Lu.test(s)&&Lu.test(a):!1;return n?o?!0:l:!1}function VT(e){return typeof e==="undefined"?!0:e===null}function Vu(e){let t=$t(e.serviceUrl);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};let r=t._0,n=e.fetchImpl,i=n!==void 0?n:pa,o=e.authMode,s=o!==void 0&&o!=="LocalRunner"?"/api/v2/personal-agent-mcp":"/api/v2/local-runner-mcp",a=e.operatingMode,l=a!==void 0?Iu(a):"text",c=async(u,d,h)=>{let p=Br(d,r),m;m=p.TAG==="Ok"?p._0:je(p._0);let f={};Object.entries(h).forEach(F=>{f[F[0]]=F[1]}),f.operating_mode=l;let g={};g.authorization="Bearer "+e.accessToken;let y;if(u==="Get"){let F=m.searchParams;Object.entries(f).forEach(ce=>{let Je=ce[1];if(!VT(Je)){F.set(ce[0],String(Je));return}}),y=await i.json(m.toString(),{method:"GET",headers:g})}else g["content-type"]="application/json",y=await i.json(m.toString(),{method:"POST",headers:g,body:JSON.stringify(f)});let v=await y.json(),b;if(b=typeof v=="object"&&v!==null&&!Array.isArray(v)?v:void 0,b===void 0)return je("Linzumi MCP API returned non-object JSON from "+d);let w=y.ok,S=kt(b.ok,!0),Z=0;if(w){if(S)return b;Z=1}else Z=1;if(Z===1){let F=b.error,ce,Je=0;typeof F=="string"?ce=F:Je=2,Je===2&&(ce="HTTP "+y.status.toString());let Ee=b.detail,bt=typeof Ee=="string"?" detail="+Ee:"";return je("Linzumi MCP API "+d+" failed: "+ce+bt)}};return{TAG:"Ok",_0:{validateAuth:()=>c("Get",s+"/validate",{}),issueOnboardingDiscoveryToken:u=>c("Post",s+"/onboarding-discovery-token",u),getMessage:u=>c("Get",s+"/message",u),getThread:u=>c("Get",s+"/thread",u),getThreadTranscript:u=>c("Get",s+"/thread-transcript",u),getChannel:u=>c("Get",s+"/channel",u),searchWorkspace:u=>c("Get",s+"/search",u),askWorkspace:u=>c("Post",s+"/ask",u),aboutMe:u=>c("Get",s+"/about-me",u),webSearch:u=>c("Get",s+"/web-search",u),fetchUrl:u=>c("Get",s+"/fetch-url",u),listUiTargets:u=>c("Get",s+"/ui-targets",u),openUi:u=>c("Post",s+"/open-ui",u),getCodingJobMetadata:u=>c("Get",s+"/coding-job-metadata",u),listProjects:u=>c("Get",s+"/projects",u),getProjectTasks:u=>c("Get",s+"/project-tasks",u),createProjectTask:u=>c("Post",s+"/project-tasks/create",u),updateProjectTask:u=>c("Post",s+"/project-tasks/update",u),deleteProjectTask:u=>c("Post",s+"/project-tasks/delete",u),addProjectTaskDependency:u=>c("Post",s+"/project-tasks/add-dependency",u),removeProjectTaskDependency:u=>c("Post",s+"/project-tasks/remove-dependency",u),getCallTranscript:u=>c("Get",s+"/call-transcript",u),renameCodingJob:u=>c("Post",s+"/coding-job-title",u),upsertCodingJobPlan:u=>c("Post",s+"/coding-job-plan",u),replaceCodingJobPlanSteps:u=>c("Post",s+"/coding-job-plan/steps",u),updateCodingJobPlanStep:u=>c("Post",s+"/coding-job-plan/step",u),linkCodingJobPullRequest:u=>c("Post",s+"/coding-job-primary-pr",u),listVaultSecrets:u=>c("Get",s+"/vault-secrets",u),noteProjectDirectory:u=>c("Post",s+"/discovered-project",u),noteAgentConversation:u=>c("Post",s+"/discovered-conversation",u),noteOnboardingDiscoveryStatus:u=>c("Post",s+"/discovery-status",u),sendChannelMessage:u=>c("Post",s+"/channel-message",u),editMessage:u=>c("Post",s+"/message/edit",u),agentReply:u=>c("Post",s+"/agent-reply",u),agentTurnProgress:u=>c("Post",s+"/agent-turn-progress",u),agentDocumentTool:u=>c("Post",s+"/agent/document-tool",u),agentListCodingJobs:u=>c("Get",s+"/agent/coding-jobs",u),agentStartCodingJob:u=>c("Post",s+"/agent/start-coding-job",u),agentSpawnChildJob:u=>c("Post",s+"/agent/spawn-child-job",u),agentInterruptCodingJob:u=>c("Post",s+"/agent/interrupt-coding-job",u),agentSendCodingJobMessage:u=>c("Post",s+"/agent/send-coding-job-message",u),agentDiscoverCodingJobs:u=>c("Get",s+"/agent/discover-coding-jobs",u),agentReadCodingJobThread:u=>c("Get",s+"/agent/coding-job-thread",u),agentResolveJobApproval:u=>c("Post",s+"/agent/resolve-job-approval",u),agentArchiveCodingJob:u=>c("Post",s+"/agent/archive-coding-job",u),agentUnarchiveCodingJob:u=>c("Post",s+"/agent/unarchive-coding-job",u),agentSetThreadStatus:u=>c("Post",s+"/agent/set-thread-status",u),agentCreateChannel:u=>c("Post",s+"/agent/create-channel",u),agentRenameChannel:u=>c("Post",s+"/agent/rename-channel",u),agentArchiveChannel:u=>c("Post",s+"/agent/archive-channel",u),agentUnarchiveChannel:u=>c("Post",s+"/agent/unarchive-channel",u),agentAddReaction:u=>c("Post",s+"/agent/add-reaction",u),agentRemoveReaction:u=>c("Post",s+"/agent/remove-reaction",u),agentPinMessage:u=>c("Post",s+"/agent/pin-message",u),agentUnpinMessage:u=>c("Post",s+"/agent/unpin-message",u),prepareMessageUploads:u=>c("Post",s+"/message-uploads/prepare",u),attachMessageFiles:u=>c("Post",s+"/message-files/attach",u),prepareCustomEmoji:u=>c("Post",s+"/custom-emoji/prepare",u),renameCustomEmoji:u=>c("Post",s+"/custom-emoji/rename",u),sendThreadReply:u=>c("Post",s+"/thread-reply",u),sendDm:u=>c("Post",s+"/dm",u),dmOwner:u=>c("Post",s+"/dm-owner",u),getVaultValues:u=>c("Post",s+"/vault-values",u)}}}var FT=Object.freeze({status:"aborted"});function k(e,t,r){function n(a,l){var c;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(c=a._zod).traits??(c.traits=new Set),a._zod.traits.add(e),t(a,l);for(let u in s.prototype)u in a||Object.defineProperty(a,u,{value:s.prototype[u].bind(a)});a._zod.constr=s,a._zod.def=l}let i=r?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function s(a){var l;let c=r?.Parent?new o:this;n(c,a),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var nn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ua={};function Jt(e){return e&&Object.assign(Ua,e),Ua}var te={};zl(te,{BIGINT_FORMAT_RANGES:()=>X_,Class:()=>Fu,NUMBER_FORMAT_RANGES:()=>Qu,aborted:()=>mi,allowsEval:()=>Wu,assert:()=>HT,assertEqual:()=>GT,assertIs:()=>JT,assertNever:()=>WT,assertNotEqual:()=>BT,assignProp:()=>Ju,cached:()=>os,captureStackTrace:()=>Ga,cleanEnum:()=>cz,cleanRegex:()=>as,clone:()=>Wt,createTransparentProxy:()=>tz,defineLazy:()=>we,esc:()=>fi,escapeRegex:()=>Sn,extend:()=>iz,finalizeIssue:()=>hr,floatSafeRemainder:()=>Bu,getElementAtPath:()=>KT,getEnumValues:()=>is,getLengthableOrigin:()=>cs,getParsedType:()=>ez,getSizableOrigin:()=>Y_,isObject:()=>Yi,isPlainObject:()=>eo,issue:()=>Xu,joinValues:()=>Fa,jsonStringifyReplacer:()=>Gu,merge:()=>oz,normalizeParams:()=>L,nullish:()=>ss,numKeys:()=>YT,omit:()=>nz,optionalKeys:()=>Ku,partial:()=>sz,pick:()=>rz,prefixIssues:()=>Dr,primitiveTypes:()=>Q_,promiseAllObject:()=>QT,propertyKeyTypes:()=>Hu,randomString:()=>XT,required:()=>az,stringifyPrimitive:()=>Ba,unwrapMessage:()=>ns});function GT(e){return e}function BT(e){return e}function JT(e){}function WT(e){throw new Error}function HT(e){}function is(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function Fa(e,t="|"){return e.map(r=>Ba(r)).join(t)}function Gu(e,t){return typeof t=="bigint"?t.toString():t}function os(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ss(e){return e==null}function as(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Bu(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return o%s/10**i}function we(e,t,r){Object.defineProperty(e,t,{get(){{let i=r();return e[t]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Ju(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function KT(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function QT(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let i={};for(let o=0;o<t.length;o++)i[t[o]]=n[o];return i})}function XT(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function fi(e){return JSON.stringify(e)}var Ga=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Yi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Wu=os(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function eo(e){if(Yi(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Yi(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function YT(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var ez=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Hu=new Set(["string","number","symbol"]),Q_=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Sn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wt(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function L(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function tz(e){let t;return new Proxy({},{get(r,n,i){return t??(t=e()),Reflect.get(t,n,i)},set(r,n,i,o){return t??(t=e()),Reflect.set(t,n,i,o)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,i){return t??(t=e()),Reflect.defineProperty(t,n,i)}})}function Ba(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Ku(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Qu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},X_={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function rz(e,t){let r={},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return Wt(e,{...e._zod.def,shape:r,checks:[]})}function nz(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return Wt(e,{...e._zod.def,shape:r,checks:[]})}function iz(e,t){if(!eo(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return Ju(this,"shape",n),n},checks:[]};return Wt(e,r)}function oz(e,t){return Wt(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Ju(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function sz(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(i[o]=e?new e({type:"optional",innerType:n[o]}):n[o])}else for(let o in n)i[o]=e?new e({type:"optional",innerType:n[o]}):n[o];return Wt(t,{...t._zod.def,shape:i,checks:[]})}function az(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let o in r){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(i[o]=new e({type:"nonoptional",innerType:n[o]}))}else for(let o in n)i[o]=new e({type:"nonoptional",innerType:n[o]});return Wt(t,{...t._zod.def,shape:i,checks:[]})}function mi(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Dr(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function ns(e){return typeof e=="string"?e:e?.message}function hr(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let i=ns(e.inst?._zod.def?.error?.(e))??ns(t?.error?.(e))??ns(r.customError?.(e))??ns(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Y_(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function cs(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Xu(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function cz(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Fu=class{constructor(...t){}};var ey=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,Gu,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ja=k("$ZodError",ey),ls=k("$ZodError",ey,{Parent:Error});function Yu(e,t=r=>r.message){let r={},n=[];for(let i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function ed(e,t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>i({issues:a}));else if(s.code==="invalid_key")i({issues:s.issues});else if(s.code==="invalid_element")i({issues:s.issues});else if(s.path.length===0)n._errors.push(r(s));else{let a=n,l=0;for(;l<s.path.length;){let c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return i(e),n}var td=e=>(t,r,n,i)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new nn;if(s.issues.length){let a=new(i?.Err??e)(s.issues.map(l=>hr(l,o,Jt())));throw Ga(a,i?.callee),a}return s.value},rd=td(ls),nd=e=>async(t,r,n,i)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(i?.Err??e)(s.issues.map(l=>hr(l,o,Jt())));throw Ga(a,i?.callee),a}return s.value},id=nd(ls),od=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new nn;return o.issues.length?{success:!1,error:new(e??Ja)(o.issues.map(s=>hr(s,i,Jt())))}:{success:!0,data:o.value}},pi=od(ls),sd=e=>async(t,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},o=t._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(s=>hr(s,i,Jt())))}:{success:!0,data:o.value}},hi=sd(ls);var ty=/^[cC][^\s-]{8,}$/,ry=/^[0-9a-z]+$/,ny=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,iy=/^[0-9a-vA-V]{20}$/,oy=/^[A-Za-z0-9]{27}$/,sy=/^[a-zA-Z0-9_-]{21}$/,ay=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var cy=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ad=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var ly=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var uz="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function uy(){return new RegExp(uz,"u")}var dy=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,fy=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,my=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,py=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,hy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,cd=/^[A-Za-z0-9_-]*$/,gy=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var _y=/^\+(?:[0-9]){6,14}[0-9]$/,yy="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",vy=new RegExp(`^${yy}$`);function by(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function wy(e){return new RegExp(`^${by(e)}$`)}function xy(e){let t=by({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${yy}T(?:${n})$`)}var ky=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Sy=/^\d+$/,$y=/^-?\d+(?:\.\d+)?/i,Ty=/true|false/i,zy=/null/i;var Ey=/^[^A-Z]*$/,Ay=/^[^a-z]*$/;var ot=k("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Oy={number:"number",bigint:"bigint",object:"date"},ld=k("$ZodCheckLessThan",(e,t)=>{ot.init(e,t);let r=Oy[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,o=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ud=k("$ZodCheckGreaterThan",(e,t)=>{ot.init(e,t);let r=Oy[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Py=k("$ZodCheckMultipleOf",(e,t)=>{ot.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Bu(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Cy=k("$ZodCheckNumberFormat",(e,t)=>{ot.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[i,o]=Qu[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=i,a.maximum=o,r&&(a.pattern=Sy)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:e})}});var Ry=k("$ZodCheckMaxLength",(e,t)=>{var r;ot.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!ss(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let i=n.value;if(i.length<=t.maximum)return;let s=cs(i);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Iy=k("$ZodCheckMinLength",(e,t)=>{var r;ot.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!ss(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let i=n.value;if(i.length>=t.minimum)return;let s=cs(i);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),jy=k("$ZodCheckLengthEquals",(e,t)=>{var r;ot.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!ss(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=n=>{let i=n.value,o=i.length;if(o===t.length)return;let s=cs(i),a=o>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),us=k("$ZodCheckStringFormat",(e,t)=>{var r,n;ot.init(e,t),e._zod.onattach.push(i=>{let o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Ny=k("$ZodCheckRegex",(e,t)=>{us.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),My=k("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ey),us.init(e,t)}),Dy=k("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ay),us.init(e,t)}),Zy=k("$ZodCheckIncludes",(e,t)=>{ot.init(e,t);let r=Sn(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(i=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),qy=k("$ZodCheckStartsWith",(e,t)=>{ot.init(e,t);let r=new RegExp(`^${Sn(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Ly=k("$ZodCheckEndsWith",(e,t)=>{ot.init(e,t);let r=new RegExp(`.*${Sn(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Vy=k("$ZodCheckOverwrite",(e,t)=>{ot.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Ha=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
318
+ command = `+Ed(e.command)+`
319
+ args = `+hz(e.args)+`
320
+ `+t}var av="Other",cv="linzumi_ask_user_question",_z="plan_mode_native_interview_tool",yz="no_active_turn";function Ts(e){return JSON.stringify(e)}function vz(e){let t=e.trim().toLowerCase();switch(t){case"other":case"something else":case"something else...":return!0;default:return t.includes("other")?!0:t.includes("something else")}}function bz(e){let t=ft(e),r=ws(t!==void 0?t.questions:void 0);if(r===void 0)return{TAG:"Invalid",_0:"questions: expected an array"};let n=r.length;if(n===0)return{TAG:"Invalid",_0:"questions: min 1, got 0"};if(n>4)return{TAG:"Invalid",_0:"questions: max 4, got "+n.toString()};let i={contents:void 0},o=[],s=new Set;r.forEach((u,c)=>{if(i.contents!==void 0)return;let d=c.toString(),h=ft(u);if(h===void 0){i.contents="questions["+d+"]: expected an object";return}let m=Qe(h.question);if(m===void 0){i.contents="questions["+d+"].question: must be a non-empty string";return}if(s.has(m)){i.contents="questions: duplicate question text "+Ts(m);return}let p=Qe(h.header);if(p===void 0){i.contents="questions["+d+"].header: must be a non-empty string";return}if(p.length>12){i.contents="questions["+d+"].header: max 12 chars, got "+p.length.toString();return}let f=h.multiSelect;if(f!==void 0){let K=0;if(typeof f!="boolean"&&(K=2),K===2){i.contents="questions["+d+"].multiSelect: must be a boolean";return}}let g=ws(h.options);if(g===void 0){i.contents="questions["+d+"].options: expected an array";return}let y=g.length;if(y<2){i.contents="questions["+d+"].options: min 2, got "+y.toString();return}if(y>4){i.contents="questions["+d+"].options: max 4, got "+y.toString();return}let v=[],b=new Set;if(g.forEach((K,ce)=>{if(i.contents!==void 0)return;let G=ce.toString(),H=ft(K),fe=H!==void 0?Qe(H.label):void 0;if(H!==void 0&&fe!==void 0){let ge=H.description,j=0;if(ge!==void 0){let $=0;if(typeof ge=="string"?j=2:$=3,$===3){i.contents="questions["+d+"].options["+G+"].description: must be a string";return}}else j=2;if(j===2){if(vz(fe)){i.contents="questions["+d+"].options["+G+"].label: "+Ts(fe)+" is reserved for the built-in Other option";return}if(b.has(fe)){i.contents="questions["+d+"].options: duplicate label "+Ts(fe);return}b.add(fe);let $=H.description,R;R=typeof $=="string"?$:"",v.push({label:fe,description:R});return}}i.contents="questions["+d+"].options["+G+"].label: must be a non-empty string"}),i.contents!==void 0)return;s.add(m);let S=h.multiSelect,q;q=S===!0,o.push({question:m,header:p,options:v,multiSelect:q})});let a=i.contents;return a!==void 0?{TAG:"Invalid",_0:a}:{TAG:"Parsed",_0:{questions:o}}}function wz(e){let t={};e.questions.forEach(a=>{let u={};u.type="string",u.description=a.header,t[a.question]=u});let r={};r.type="object",r.properties=t,r.required=e.questions.map(a=>a.question);let n=e.questions.map(a=>{let u={};return u.question=a.question,u.header=a.header,u.multiSelect=a.multiSelect,u.options=a.options.map(c=>{let l={};return l.label=c.label,l.description=c.description,l}),u}),i={};i.version=1,i.questions=n;let o={};o[cv]=i;let s={};return s.message="Linzumi interview: the user is being asked in the Linzumi thread.",s.requestedSchema=r,s._meta=o,s}function xz(e,t){let r=ft(t);if(r===void 0)return{TAG:"AnswersInvalid",_0:"the runner accepted the interview but returned no answers; it may predate linzumi_ask_user_question support"};let n={contents:void 0},i={};e.questions.forEach(s=>{if(n.contents!==void 0)return;let u=r[s.question];if(typeof u=="string"){let c=0,l;try{l=JSON.parse(u),c=2}catch{n.contents="the runner returned an undecodable answer for question "+Ts(s.question);return}if(c===2){i[s.question]=l;return}}n.contents="the runner returned no answer for question "+Ts(s.question)});let o=n.contents;return o!==void 0?{TAG:"AnswersInvalid",_0:o}:{TAG:"Answers",_0:i}}function kz(e){let t=ft(e);if(t===void 0)return;let r=ft(t[cv]);return Qe(r!==void 0?r.reason:void 0)}function dn(e){let t={};t.type="text",t.text=e;let r={};return r.content=[t],r.isError=!0,r}function Sz(e){if(e===void 0)return"undefined";if(e===null)return"null";switch(typeof e){case"string":return e;case"number":return e.toString();default:return JSON.stringify(e)}}async function lv(e,t){let r=bz(t);if(r.TAG!=="Parsed")return dn(r._0);let n=r._0,i=0,o;try{o=await e(wz(n),2147483647),i=1}catch(s){let a=X(s);return dn("the interview could not be delivered to the user: "+wn(a))}if(i===1){let s=ft(o),a=s!==void 0?s:{},u=a.action,c=0;if(typeof u=="string")switch(u){case"accept":let l=xz(n,a.content);if(l.TAG!=="Answers")return dn(l._0);let d={};return d.answers=l._0,St(d);case"cancel":return dn("the user dismissed the question without answering");case"decline":let h=kz(a._meta);return dn(h!==void 0?h===_z?"linzumi_ask_user_question is unavailable during a Plan-mode turn: use the native request_user_input interview tool instead":h===yz?"the interview was declined: no active turn is bound to this session":"the interview request was declined by the runner":"the interview request was declined by the runner");default:c=2}else c=2;if(c===2)return dn("the interview returned an unknown action: "+Sz(u))}}var uv="linzumi_ask_user_question",Od=4,Ad=12,Pd=2,Cd=4;function $z(e){switch(e){case"All":return!0;case"Coding":case"OnboardingDiscovery":return!1}}function Ez(e){return e==="Voice"}function zz(e){return e.trim().replace(new RegExp("^:+"),"").replace(new RegExp(":+$"),"").toLowerCase()}function dv(){return _.string().min(1).refine(e=>zz(e).length<=64,{message:"Custom emoji shortcode name must be at most 64 characters after trimming surrounding colons."})}function Ee(){return _.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")}function Qt(){return _.string().optional().describe("Channel slug. Omit to use the authenticated token scope.")}function Xt(e){if(typeof e=="string")return e}function fv(e,t,r){let n=ft(e[t]);return n!==void 0?n:Ve(r+" "+t+" must be an object")}function Oz(e){return e!==void 0?Array.isArray(e)?Ht(e,t=>{if(typeof t=="string")return t}):[]:[]}function Az(e){return e!==void 0?Array.isArray(e)?Ht(e,t=>{if(typeof t=="number")return t}):[]:[]}function mv(e){if(typeof e=="number")return e}function pv(e){let t={};t.name=e.record.name,t.command=e.record.command,t.cwd=e.record.cwd,t.ports=e.record.ports.map(s=>s),t.restart_on_branch_change=e.record.restartOnBranchChange,t.desired_state=vd(e.record.desiredState),t.liveness=Hy(e.liveness),t.port_health=e.portProbes.map(s=>{let a={};return a.port=s.port,a.listening=s.listening,a});let r=e.record.startedAtMs;t.started_at_ms=r!==void 0?r:null;let n=e.lastExit,i;if(n!==void 0){let s={},a=n.code;s.code=a!==void 0?a:null;let u=n.signal;s.signal=u!==void 0?u:null,s.at_ms=n.atMs,i=s}else i=null;t.last_exit=i,t.log_path=e.record.logPath;let o=e.failure;return t.failure=o!==void 0?{reason:o.reason,at_ms:o.atMs}:null,t}function Pz(e,t,r){e.registerTool("linzumi_dev_service_start","Start a long-running local dev server (npm run dev, storybook, docker compose up, ...) as a MANAGED SERVICE owned by the Linzumi runner. Use this instead of running dev servers in your own shell: a managed service survives the end of your turn and branch switches, is auto-restarted if it crashes, and its declared ports are health-probed and surfaced in the product. Calling start for an existing name declaratively RESTARTS it (e.g. after a checkout). Declare EVERY port the app serves from (primary plus HMR/asset/bundle sibling ports).",Object.fromEntries([["name",_.string().regex(new RegExp("^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")).describe("Stable service name (slug), e.g. 'web' or 'storybook'. Reusing a name restarts that service.")],["command",_.string().min(1).describe("Shell command that runs the server in the foreground (never daemonize/screen/nohup it yourself), e.g. 'npm run dev'. Runs via the user's login shell.")],["cwd",_.string().optional().describe("Working directory for the service. Defaults to the session cwd.")],["ports",_.array(_.number().int().min(1).max(65535)).max(16).default([]).describe("Every TCP port this service listens on (primary AND related ports such as the Vite/HMR bundle port). Used for health probes and product visibility.")],["restart_on_branch_change",_.boolean().optional().describe("Restart the service automatically when the git branch of its cwd changes (for servers that go stale across checkouts).")],["wait_for_ports_ms",_.number().int().min(0).max(6e4).optional().describe("How long to wait for the declared ports to accept connections before returning (default 15000).")]]),async n=>{let i=Xt(n.name),o=i!==void 0?i:"",s=Xt(n.command),a=s!==void 0?s:"",u=Xt(n.cwd),c=await Xy({scopeDir:r.scopeDir,definition:{name:o,command:a,cwd:u!==void 0?u:t,ports:Az(n.ports),restartOnBranchChange:Ot(n.restart_on_branch_change,!0)},ownerPid:r.ownerPid});if(c.TAG==="Ok"){let d=c._0,h=mv(n.wait_for_ports_ms),m=Date.now()+(h!==void 0?h:15e3),p=d.ports.length===0;for(;!p&&Date.now()<m;)p=(await Promise.all(d.ports.map(w=>kd(w|0)))).every(w=>w),p||await Da(250);let g=(await Sd(r.scopeDir)).find(b=>b.record.name===d.name),y={};y.ok=!0;let v;if(g!==void 0)v=pv(g);else{let b={};b.name=d.name,v=b}return y.service=v,g!==void 0&&g.liveness!=="Running"&&(y.hint="The service is not (fully) serving its declared ports yet. Check linzumi_dev_service_logs before assuming it works."),St(y)}let l={};return l.ok=!1,l.error=c._0,St(l)}),e.registerTool("linzumi_dev_service_stop","Stop a managed dev service (SIGTERM, then SIGKILL after a grace period). The registration is kept so linzumi_dev_service_start can bring it back.",Object.fromEntries([["name",_.string().min(1).describe("Service name to stop.")]]),async n=>{let i=Xt(n.name),o=i!==void 0?i:"",s=await Td(r.scopeDir,o,void 0),a={};return s.TAG==="Ok"?(a.ok=!0,a.name=s._0.name,a.desired_state="stopped"):(a.ok=!1,a.error=s._0),St(a)}),e.registerTool("linzumi_dev_service_status","List every managed dev service with liveness (running / unhealthy / exited / failed / stopped), per-port health probes, last exit, and any terminal failure reason. Live state - always check this before concluding a dev server is up or down.",{},async n=>{let i=await Sd(r.scopeDir),o={};return o.services=i.map(s=>pv(s)),St(o)}),e.registerTool("linzumi_dev_service_logs","Read the tail of a managed dev service's combined stdout/stderr log.",Object.fromEntries([["name",_.string().min(1).describe("Service name.")],["max_bytes",_.number().int().min(256).max(65536).optional().describe("Tail size in bytes (default 16384).")]]),async n=>{let i=Xt(n.name),o=i!==void 0?i:"",s=mv(n.max_bytes),a=ev(r.scopeDir,o,s!==void 0?s:16384),u={};return a!==void 0?(u.ok=!0,u.name=o,u.log_tail=a):(u.ok=!1,u.error="no log for service: "+o),St(u)}),e.registerTool("linzumi_dev_service_remove","Stop a managed dev service AND delete its registration (it will not be resurrected on runner restart). Use stop instead when the user may want it back.",Object.fromEntries([["name",_.string().min(1).describe("Service name to remove.")]]),async n=>{let i=Xt(n.name),o=i!==void 0?i:"",s=await Yy(r.scopeDir,o,wc),a={};return s.TAG==="Ok"?(a.ok=!0,a.name=s._0.name,a.removed=!0):(a.ok=!1,a.error=s._0),St(a)})}function hv(e,t){let r=t.devServices,n=t.agentSession,i=t.ownerUsername,o=t.defaultThreadId,s=t.serviceUrl,a=t.cwd,u=t.toolScope,c=t.client,l;switch(u){case"All":case"Coding":l=!0;break;case"OnboardingDiscovery":l=!1;break}let d=async f=>St(await f),h=async(f,g)=>(g.tool=f,await d(c.agentDocumentTool(g))),m=t.documentSurfaces;m!==void 0&&m&&(e.registerTool("linzumi_lookup_documents","Search document titles and content within the controlling human's visibility ceiling. Returns authorized results in canonical search order; zero, one, and multiple matches carry the rule-03 ambiguity meaning.",Object.fromEntries([["query",_.string().min(1).describe("Document title or content search query.")]]),async f=>await h("lookup_documents",f)),e.registerTool("linzumi_read_document","Read one in-scope document as full AST and metadata, including pending proposals and required-agent-context comments. Both controlling-human visibility and agent delegation are required.",Object.fromEntries([["document_id",_.string().uuid().describe("Document UUID.")]]),async f=>await h("read_document",f)),e.registerTool("linzumi_propose_document_patch","Use this tool for any explicit instruction to edit, add, rewrite, update, or fix document content, including parent-delegated work. After resolving exactly one patch target document and reading its current revision, call this tool in the same turn; do not merely reply with suggested prose. Other authorized context documents do not make the patch target ambiguous. Every change is proposal-always: the server persists an agent-attributed structural patch proposal first, leaves it pending in hold mode, and resolves per-document auto-apply server-side only after persistence and authorization.",Object.fromEntries([["document_id",_.string().uuid().describe("Document UUID.")],["patch",_.record(_.unknown()).describe("Revisioned structural document patch.")],["rationale",_.string().min(1).describe("Why this change is proposed.")]]),async f=>await h("propose_document_patch",f)),e.registerTool("linzumi_create_document","Create an agent-attributed document through an atomic bootstrap proposal and apply transaction in the named folder or workspace default folder.",Object.fromEntries([["title",_.string().min(1).describe("Document title.")],["initial_patch",_.record(_.unknown()).describe("Bootstrap structural patch.")],["folder_id",_.string().uuid().optional().describe("Destination folder UUID.")]]),async f=>await h("create_document",f)));let p=t.askUserQuestion;switch(p!==void 0&&e.registerTool(uv,"Ask the user up to "+Od.toString()+" structured multiple-choice questions and BLOCK until they answer in the Linzumi thread. Use this whenever you need a decision or clarification mid-task. Each question needs a short header (max "+Ad.toString()+" chars) and "+Pd.toString()+"-"+Cd.toString()+' options {label, description}; a built-in "'+av+'" free-text choice is always shown in addition to your options, so never add one yourself. Set multiSelect true to allow choosing several options. Returns {answers} keyed by question text: a single label string, an array of labels for multiSelect, and {"other": "<typed text>"} for a free-text reply.',Object.fromEntries([["questions",_.array(_.object(Object.fromEntries([["question",_.string().describe("The question to ask the user.")],["header",_.string().describe("Short category header shown above the question (max "+Ad.toString()+' chars, e.g. "Auth", "Scope").')],["options",_.array(_.object(Object.fromEntries([["label",_.string().describe("Option label the user taps.")],["description",_.string().optional().describe("One-line explanation of the option.")]]))).describe(Pd.toString()+"-"+Cd.toString()+" options for this question.")],["multiSelect",_.boolean().optional().describe("True lets the user select several options; the answer becomes an array.")]]))).describe("1-"+Od.toString()+" questions to ask atomically.")]]),async f=>await lv(p,f)),n&&(e.registerTool("linzumi_agent_reply","Post your single @linzumi reply for the current turn into the surface where you were mentioned. Call EXACTLY ONCE per turn with your final answer; the reply links to this working session automatically. Fails with already_replied on a second call and no_active_asker_binding when no turn is active.",Object.fromEntries([["body",_.string().min(1).describe("Plain-text reply body to post.")]]),async f=>{let g={},y=f.body;return g.body=y!==void 0?y:void 0,await d(c.agentReply(g))}),e.registerTool("linzumi_list_coding_jobs","List the coding jobs the current asker can see in this workspace: runner connections (online and recent) with their bound job threads. Live state - never answered from search.",{},async f=>await d(c.agentListCodingJobs({}))),e.registerTool("linzumi_start_coding_job","Start a coding job exactly as if the asking user clicked start: same runner/channel authorization, same pipeline. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",Object.fromEntries([["channel",_.string().describe("Channel slug to host the job thread.")],["runner_key",_.string().describe("Runner (computer) to run the job on.")],["cwd",_.string().describe("Working directory on the runner.")],["work_description",_.string().min(1).describe("What the job should do - the initial instruction.")],["model",_.string().optional().describe("Model override (optional).")],["model_provider",_.string().optional().describe("Model provider override, e.g. 'wafer' (optional).")],["execution_mode",_.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional).")],["project_task_id",_.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job.")],["visibility",_.enum(["project","private"]).optional().describe("Job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants.")]]),async f=>await d(c.agentStartCodingJob(f))),e.registerTool("linzumi_interrupt_coding_job","Interrupt a coding job: mode 'steer' (default) discards its queued follow-ups so your next message lands first; mode 'stop' terminates the current turn.",Object.fromEntries([["channel",_.string().describe("Channel slug hosting the job thread.")],["thread_id",_.string().uuid().describe("The job thread UUID.")],["mode",_.enum(["steer","stop"]).optional().describe("Interrupt mode; defaults to 'steer'.")]]),async f=>await d(c.agentInterruptCodingJob(f))),e.registerTool("linzumi_send_coding_job_message","Message a coding job or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",Object.fromEntries([["channel",_.string().optional().describe("Channel slug hosting the job thread. Required unless to_user is set.")],["thread_id",_.string().uuid().optional().describe("The job thread UUID. Required unless to_user is set.")],["to_user",_.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox.")],["body",_.string().min(1).describe("Message body to send.")],["delivery",_.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")]]),async f=>await d(c.agentSendCodingJobMessage(f))),e.registerTool("linzumi_read_coding_job_thread","Read a coding job's thread (asker-visible history) plus its workflow status metadata.",Object.fromEntries([["channel",_.string().describe("Channel slug hosting the job thread.")],["thread_id",_.string().uuid().describe("The job thread UUID.")],["limit",_.number().int().min(1).max(100).optional().describe("Maximum replies to return.")],["before_seq",_.number().int().positive().optional().describe("Return replies before this channel seq.")]]),async f=>await d(c.agentReadCodingJobThread(f))),e.registerTool("linzumi_resolve_job_approval","Resolve a coding job's pending approval request with the asking user's decision ('approve' or 'deny'). Only relays the asker's authority - never approve without their explicit instruction.",Object.fromEntries([["channel",_.string().describe("Channel slug hosting the job thread.")],["thread_id",_.string().uuid().describe("The job thread UUID.")],["source_seq",_.number().int().positive().describe("Channel seq of the message the approval request rides on.")],["request_id",_.string().describe("The approval request id.")],["decision",_.enum(["approve","deny"]).describe("The asker's decision.")]]),async f=>await d(c.agentResolveJobApproval(f))),e.registerTool("linzumi_archive_coding_job","Archive a coding job's thread (or any thread the asking user owns) so it leaves the active list; history is preserved. Do this when the asker says to archive a job or thread - never just promise it.",Object.fromEntries([["channel",_.string().describe("Channel slug hosting the thread.")],["thread_id",_.string().uuid().describe("The thread UUID to archive.")]]),async f=>await d(c.agentArchiveCodingJob(f))),e.registerTool("linzumi_unarchive_coding_job","Unarchive a previously archived coding job thread the asking user owns, returning it to the active list.",Object.fromEntries([["channel",_.string().describe("Channel slug hosting the thread.")],["thread_id",_.string().uuid().describe("The thread UUID to unarchive.")]]),async f=>await d(c.agentUnarchiveCodingJob(f))),e.registerTool("linzumi_set_thread_status","Set a thread's lifecycle status as the asking user: 'closed' marks it done, 'open' reopens it. Works on threads the asker owns.",Object.fromEntries([["channel",_.string().describe("Channel slug hosting the thread.")],["thread_id",_.string().uuid().describe("The thread UUID.")],["status",_.enum(["open","closed"]).describe("Replacement lifecycle status ('closed' = done).")]]),async f=>await d(c.agentSetThreadStatus(f))),e.registerTool("linzumi_create_channel","Create a new public channel in this workspace as the asking user. The slug is derived from the name.",Object.fromEntries([["name",_.string().min(1).describe("Channel name to create.")]]),async f=>await d(c.agentCreateChannel(f))),e.registerTool("linzumi_rename_channel","Rename a channel's display name as the asking user. The channel's URL slug stays stable.",Object.fromEntries([["channel",_.string().describe("Current channel slug to rename.")],["name",_.string().min(1).describe("New display name.")]]),async f=>await d(c.agentRenameChannel(f))),e.registerTool("linzumi_archive_channel","Archive a channel in this workspace as the asking user. History is preserved; the channel leaves the active sidebar.",Object.fromEntries([["channel",_.string().describe("Channel slug to archive.")]]),async f=>await d(c.agentArchiveChannel(f))),e.registerTool("linzumi_unarchive_channel","Unarchive a previously archived channel as the asking user.",Object.fromEntries([["channel",_.string().describe("Channel slug to unarchive.")]]),async f=>await d(c.agentUnarchiveChannel(f))),e.registerTool("linzumi_add_reaction","Add an emoji reaction to a channel message as the asking user. Accepts unicode emoji or a workspace :shortcode:.",Object.fromEntries([["channel",_.string().describe("Channel slug containing the message.")],["message_seq",_.number().int().positive().describe("Channel seq of the message to react to.")],["emoji",_.string().min(1).describe("Emoji to add (unicode or :shortcode:).")]]),async f=>await d(c.agentAddReaction(f))),e.registerTool("linzumi_remove_reaction","Remove the asking user's emoji reaction from a channel message.",Object.fromEntries([["channel",_.string().describe("Channel slug containing the message.")],["message_seq",_.number().int().positive().describe("Channel seq of the reacted message.")],["emoji",_.string().min(1).describe("Emoji to remove (unicode or :shortcode:).")]]),async f=>await d(c.agentRemoveReaction(f))),e.registerTool("linzumi_pin_message","Pin a channel message as the asking user. Thread replies re-point to their root message.",Object.fromEntries([["channel",_.string().describe("Channel slug containing the message.")],["message_seq",_.number().int().positive().describe("Channel seq of the message to pin.")]]),async f=>await d(c.agentPinMessage(f))),e.registerTool("linzumi_unpin_message","Remove a pin from a channel message as the asking user.",Object.fromEntries([["channel",_.string().describe("Channel slug containing the message.")],["message_seq",_.number().int().positive().describe("Channel seq of the pinned message.")]]),async f=>await d(c.agentUnpinMessage(f)))),u){case"All":e.registerTool("linzumi_get_message","Read one Linzumi message by scoped message_seq/message_id or a Linzumi message URL, with optional bounded before/after context.",Object.fromEntries([["workspace",Ee()],["channel",Qt()],["message_id",_.union([_.string(),_.number()]).optional().describe("Message seq inside the scoped channel.")],["message_seq",_.union([_.string(),_.number()]).optional().describe("Alias for message_id.")],["message_url",_.string().optional().describe("Full Linzumi message URL with #message-<seq>.")],["before",_.number().int().min(0).max(100).optional().describe("Number of visible messages before the target.")],["after",_.number().int().min(0).max(100).optional().describe("Number of visible messages after the target.")]]),async f=>await d(c.getMessage(f))),e.registerTool("linzumi_get_thread","Read one Linzumi thread by thread_id in the scoped channel, including the parent message and bounded replies.",Object.fromEntries([["workspace",Ee()],["channel",Qt()],["thread_id",_.string().uuid().describe("Linzumi thread UUID.")],["limit",_.number().int().min(1).max(100).optional().describe("Maximum replies to return.")],["before_seq",_.number().int().positive().optional().describe("Return replies before this channel seq.")]]),async f=>await d(c.getThread(f))),e.registerTool("linzumi_get_thread_transcript","Read a Linzumi thread's full transcript as canonical IR nodes (user/assistant messages, command executions, file changes, tool calls, statuses), cursor-paginated over the complete history. Use the returned cursor with has_more to walk older pages.",Object.fromEntries([["workspace",Ee()],["channel",Qt()],["thread_id",_.string().uuid().describe("Linzumi thread UUID.")],["limit",_.number().int().min(1).max(500).optional().describe("Maximum transcript nodes per page (default 200).")],["cursor",_.number().int().positive().optional().describe("Return nodes below this seq (the previous page reply cursor).")]]),async f=>await d(c.getThreadTranscript(f))),e.registerTool("linzumi_get_channel","Read scoped Linzumi channel metadata and bounded recent channel messages.",Object.fromEntries([["workspace",Ee()],["channel",Qt()],["limit",_.number().int().min(1).max(100).optional().describe("Maximum messages to return.")],["before_seq",_.number().int().positive().optional().describe("Return messages before this channel seq.")]]),async f=>await d(c.getChannel(f))),e.registerTool("linzumi_search_workspace","Search the Linzumi workspace with hybrid lexical+semantic retrieval, scoped to what the authorizing user can access. Returns scored content chunks with provenance (channel, thread, authored time) and a permalink to cite.",Object.fromEntries([["workspace",Ee()],["query",_.string().min(1).describe("Natural-language or keyword query to retrieve against.")],["limit",_.number().int().min(1).max(25).optional().describe("Maximum results to return (default 10, server-capped).")],["source_types",_.array(_.enum(["message","coding_job","github_pr","github_pr_review","github_check_run","github_workflow_run","github_diff","dictation","file"])).optional().describe("Restrict results to these corpora; omit for all.")],["authored_after",_.string().optional().describe("ISO8601 instant; only content authored at or after this time.")],["authored_before",_.string().optional().describe("ISO8601 instant; only content authored at or before this time.")],["repo",_.string().optional().describe("Restrict GitHub-sourced results to one repository by full name (owner/name).")],["check_status",_.enum(["pending","success","failed"]).optional().describe("Restrict check and workflow results to one conclusion bucket.")]]),async f=>await d(c.searchWorkspace(f))),e.registerTool("linzumi_ask_workspace",'Ask the Linzumi workspace a natural-language question and get a synthesized, citation-backed answer over what the authorizing user can access. Costs an LLM call on cache misses, so prefer linzumi_search_workspace for simple lookups. A "refused" status means there was not enough accessible evidence - treat it as "the workspace does not know", never retry verbatim.',Object.fromEntries([["workspace",Ee()],["question",_.string().min(1).max(2e3).describe("Natural-language question to answer with citations.")],["channel",_.string().optional().describe("Optional channel slug providing conversational context; never widens access.")],["allow_cached",_.boolean().optional().describe("Allow serving a cached synthesis when the evidence set is unchanged (default true). Set false to force fresh synthesis.")]]),async f=>await d(c.askWorkspace(f))),e.registerTool("linzumi_about_me","Read what the authorizing user has told Linzumi about themselves: their profile facts (homes, unit preferences, and other self-maintained attributes) plus their derived current timezone. Use it to personalize answers (e.g. pick the right city for weather, use their preferred units). Predicates may have multiple active values; prefer the one consistent with the derived timezone.",{},async f=>await d(c.aboutMe(f)));break;case"Coding":case"OnboardingDiscovery":break}switch(l&&(e.registerTool("linzumi_web_search","Search the public web for live or external information: news, current events, weather, prices, third-party API docs, research. Returns result titles, URLs, and snippets. Use this whenever the answer lives outside the Linzumi workspace; follow up with linzumi_fetch_url to read a result page.",Object.fromEntries([["query",_.string().min(1).describe("Web search query (natural language or keywords).")],["limit",_.number().int().min(1).max(10).optional().describe("Maximum results to return (default 8, server-capped).")]]),async f=>await d(c.webSearch(f))),e.registerTool("linzumi_fetch_url","Fetch one public http(s) URL and return its readable text content (HTML is reduced to plain text; large pages are truncated). Use it to read pages found via linzumi_web_search or any public docs/API reference. Only public addresses are reachable - private/internal hosts are rejected with url_not_allowed.",Object.fromEntries([["url",_.string().min(1).describe("Absolute public http(s) URL to fetch.")]]),async f=>await d(c.fetchUrl(f)))),u){case"All":e.registerTool("linzumi_list_ui_targets","List every UI surface you can ask the user to open in their own Linzumi window (channels, DMs, threads, projects, coding jobs, computers, catch-up, activity, settings tabs, pane layouts) with the structured args each kind takes. Use UI control only when the user asks for help or asks to be shown something.",{},async f=>await td(c.listUiTargets({}))),e.registerTool("linzumi_open_ui","Ask the user to open one whitelisted UI surface in their own already-open Linzumi window. A consent toast appears in THEIR session; navigation happens only if they tap Open. The call blocks until they decide and returns status opened/dismissed/expired - or error no_active_ui_session when they have no Linzumi window open (tell them to open Linzumi), or invalid_target with a detail. Use it only when the user asks for help or asks to be shown something; kinds and per-kind args come from linzumi_list_ui_targets.",Object.fromEntries([["kind",_.string().min(1).describe("Target kind from linzumi_list_ui_targets (e.g. settings_workspace, channel, pane_layout).")],["args",_.record(_.unknown()).optional().describe("Structured per-kind args from linzumi_list_ui_targets (never a URL - the server computes every path).")],["workspace",Ee()]]),async f=>await td(c.openUi(sr(f,o))));break;case"Coding":case"OnboardingDiscovery":break}if(l){let f=()=>_.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread.");e.registerTool("linzumi_get_coding_job_metadata","Read the active coding job workflow metadata for a thread, including the agent-owned goal, ordered plan steps, step lock versions, and workflow status.",Object.fromEntries([["workspace",Ee()],["channel",Qt()],["thread_id",f()]]),async g=>await d(c.getCodingJobMetadata(sr(g,o)))),e.registerTool("linzumi_rename_coding_job","Update the current coding job thread title and workflow-facing title. Use this when the job scope changes materially so the Linzumi thread list and metadata overview stay accurate.",Object.fromEntries([["workspace",Ee()],["channel",Qt()],["thread_id",f()],["title",_.string().min(1).max(100).describe("Concise user-visible title for this coding job.")]]),async g=>await d(c.renameCodingJob(sr(g,o)))),e.registerTool("linzumi_upsert_coding_job_plan","Set or update the current coding job goal. Use this at job start and whenever the goal changes materially.",Object.fromEntries([["workspace",Ee()],["channel",Qt()],["thread_id",f()],["goal",_.string().min(1).max(1e4).describe("Concrete user-visible goal for this coding job.")]]),async g=>await d(c.upsertCodingJobPlan(sr(g,o)))),e.registerTool("linzumi_replace_coding_job_plan_steps","Replace the ordered coding job plan steps. Use this for the initial plan and for substantial rewrites when the old plan no longer fits the work.",Object.fromEntries([["workspace",Ee()],["channel",Qt()],["thread_id",f()],["goal",_.string().min(1).max(1e4).optional().describe("Required when no plan exists yet; updates the current coding job goal.")],["steps",_.array(_.object(Object.fromEntries([["title",_.string().min(1).max(255)],["description",_.string().min(1).max(1e4)],["status",_.enum(["pending","active","completed","blocked","canceled"])],["status_note",_.string().min(1).max(4e3).optional()],["completed_debrief",_.string().min(1).max(2e4).optional()]]))).min(1).max(50).describe("Ordered user-visible plan steps. Completed steps must include completed_debrief.")]]),async g=>await d(c.replaceCodingJobPlanSteps(sr(g,o)))),e.registerTool("linzumi_update_coding_job_plan_step","Update one coding job plan step status or note. Read metadata first and pass the current step lock_version.",Object.fromEntries([["workspace",Ee()],["channel",Qt()],["thread_id",f()],["step_id",_.string().uuid().describe("Step id returned by linzumi_get_coding_job_metadata.")],["lock_version",_.number().int().positive().describe("Current step lock_version from metadata.")],["status",_.enum(["pending","active","completed","blocked","canceled"])],["status_note",_.string().min(1).max(4e3).optional()],["completed_debrief",_.string().min(1).max(2e4).optional().describe("Required when marking a step completed.")]]),async g=>await d(c.updateCodingJobPlanStep(sr(g,o)))),e.registerTool("linzumi_link_coding_job_pull_request","Link the active coding job to its primary GitHub pull request so PR comments, files, commits, checks, deployments, and reviews can flow into the metadata view.",Object.fromEntries([["workspace",Ee()],["channel",Qt()],["thread_id",f()],["github_repo_owner",_.string().min(1).max(255)],["github_repo_name",_.string().min(1).max(255)],["github_pr_number",_.number().int().positive()],["github_pr_url",_.string().url()],["title",_.string().min(1).max(255)],["body",_.string().min(1).max(1e5).optional()],["head_branch",_.string().min(1).max(255)],["head_sha",_.string().min(7).max(64)],["base_branch",_.string().min(1).max(255)],["base_sha",_.string().min(7).max(64)],["state",_.enum(["draft","open","closed","merged"]).optional()],["is_draft",_.boolean().optional()],["review_status",_.enum(["unknown","review_required","approved","changes_requested"]).optional()],["source_remote_url",_.string().min(1).max(1e3).describe("Git remote URL for the local job worktree; required when this job has no repo workspace yet.")],["runtime_worktree_root",_.string().min(1).max(1e3).describe("Absolute local worktree path for the coding job; required when this job has no repo workspace yet.")],["dirty_status",_.enum(["unknown","clean","dirty"]).optional()],["dirty_summary",_.string().min(1).max(2e3).optional()]]),async g=>await d(c.linkCodingJobPullRequest(sr(g,o)))),e.registerTool("linzumi_upload_files",["Upload local files to Linzumi and attach them to a new, exact, or latest assistant message. Use silently; do not mention this tool in the visible reply.","The JSON result includes message.attachments[].url as an absolute URL. Use those returned URLs when writing rich media directives such as ::audio, ::video, ::image, or Markdown images. Do not guess attachment URLs before upload.","For a message that should both attach files and show inline rich media, use a two-step flow: first upload/attach the files to create or target the message, then edit the same target message with body text that references the returned absolute URLs. When the result has target_seq, use target.kind=message_seq and message_seq=target_seq for that follow-up edit; result.message is the edit event that carries the new attachments, and target_message is the original target."].join(" "),Object.fromEntries([["target",_.object(Object.fromEntries([["kind",_.enum(["new_message","message_seq","latest_assistant_message"]).describe("new_message creates a message; message_seq edits an exact message; latest_assistant_message edits the latest assistant message in the scoped thread/channel.")],["message_seq",_.union([_.string(),_.number()]).optional().describe("Required when kind is message_seq.")],["thread_id",_.string().optional().describe("Thread UUID. Defaults to the active Linzumi thread when the MCP server was launched with one.")]])).describe("Attachment target. Prefer latest_assistant_message to attach files to the reply you already posted; use new_message ONLY when no assistant message exists yet in the scoped thread. Never re-use your visible reply text as a new_message body - that posts the reply twice. To reference uploaded files in the message body, upload first, then edit message_seq/latest_assistant_message with the returned absolute attachment URLs. If the upload result includes target_seq, use message_seq=target_seq for that follow-up edit.")],["files",_.array(_.string().min(1)).min(1).max(16).describe("Local file paths to upload. Paths must be non-hidden files inside the approved workspace or Downloads; source/text files of any language are supported, plus common document, image, patch, archive, and video types.")],["body",_.string().min(1).max(2e4).optional().describe("Required for new_message: a SHORT file-share caption (for example: Attached the generated report), never a copy of your visible reply - that would post the reply twice. Optional replacement body for message_seq/latest_assistant_message; when omitted, the existing message body is preserved. Rich media directives in body must use Linzumi attachment download URLs returned by this tool.")],["workspace",Ee()],["channel",_.string().optional().describe("Channel slug. Omit to use the target thread's channel (when the thread is known) or the authenticated token scope.")]]),async g=>{let y=rd(fv(g,"target","linzumi_upload_files"),o),v;try{v=await fy({client:c,cwd:a,serviceUrl:s,target:y,files:Oz(g.files),workspace:Xt(g.workspace),channel:Xt(g.channel),body:Xt(g.body)})}catch(b){return ly(X(b))}return St(nd(s,v))}),e.registerTool("linzumi_edit_message","Edit an exact scoped Linzumi message by message_seq. Use after linzumi_upload_files when you need a body-only follow-up edit that embeds returned attachment URLs. Requires channel.write, and thread.write when target.thread_id is set. Rich media src/poster values must be Linzumi attachment download URLs.",Object.fromEntries([["workspace",Ee()],["channel",Qt()],["target",_.object(Object.fromEntries([["message_seq",_.union([_.string(),_.number()]).describe("Exact message seq to edit. After linzumi_upload_files returns target_seq, pass that value here.")],["thread_id",_.string().optional().describe("Thread UUID when editing a thread message. Use the upload result target_message.thread_id when present.")]])).describe("Exact message target for the body edit.")],["body",_.string().min(1).max(2e4).describe("Replacement Markdown body. Rich media src/poster values must be Linzumi attachment download URLs returned by linzumi_upload_files.")]]),async g=>{let y=cn(g);return y.target=rd(fv(g,"target","linzumi_edit_message"),o),St(nd(s,await c.editMessage(y)))})}switch(u){case"All":if(e.registerTool("linzumi_list_vault_secrets","List vault secret names, descriptions, and whether each secret is personal or workspace-owned. Does not return secret values.",{},async f=>await d(c.listVaultSecrets(f))),e.registerTool("linzumi_list_projects","List the projects in the current workspace with their project_id (needed by the other project task tools), slug, title, description, and state.",Object.fromEntries([["workspace",Ee()]]),async f=>await d(c.listProjects(f))),e.registerTool("linzumi_get_project_tasks",`Read a project's full task graph: task GROUPS (kind "group", organizational containers, exactly one level deep) and ISSUES (kind "issue", the executable work items), each with status (todo/active/blocked/review/done/canceled), DERIVED work_state readiness (ready = todo with every dependency satisfied; blocked = todo with unsatisfied dependencies; running/stalled = active with/without a connected job), parent group, assignee, lock_version, and dependency edges (depends_on_task_ids / unblocks_task_ids). Always read this before reorganizing. Inside a project-bound coding job the project is inferred automatically; otherwise pass project_id from linzumi_list_projects.`,Object.fromEntries([["project_id",_.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")]]),async f=>await d(c.getProjectTasks(sr(f,o)))),e.registerTool("linzumi_create_project_task",'Create a task group (kind "group") or issue (kind "issue", the default) in a project. Groups organize issues and are exactly one level deep: a parent_id must name a GROUP, and groups themselves can never have a parent. New tasks default to status "todo" and append to the end unless position is given. Inside a project-bound coding job the project is inferred; otherwise pass project_id.',Object.fromEntries([["project_id",_.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")],["title",_.string().min(1).describe("Task title.")],["kind",_.enum(["issue","group"]).optional().describe('What to create: "issue" (executable work item, default) or "group" (organizational container).')],["description",_.string().optional().describe("Detailed description of the work - written so an engineer (or coding agent) could execute the task from it.")],["status",_.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('Initial status. Defaults to "todo".')],["parent_id",_.string().optional().describe("task_id of the GROUP to place an issue in. Only issues can have a parent.")],["assignee",_.string().optional().describe("Username of a workspace member to assign.")],["position",_.number().int().min(0).optional().describe("Sort position. Defaults to appending at the end.")]]),async f=>await d(c.createProjectTask(sr(f,o)))),e.registerTool("linzumi_update_project_task",'Update a task group or issue: retitle, edit description/status_note, transition status (todo/active/blocked/review/done/canceled), reassign, reorder (position), or reorganize (parent_id moves an issue into a group; clear_parent moves it to top level). Only the fields you pass change; description and status_note accept null to clear. Prefer updating existing tasks over delete-and-recreate. Pass the lock_version from your last read to fail loudly ("stale") instead of overwriting a concurrent edit.',Object.fromEntries([["task_id",_.string().describe("task_id of the group or issue to update.")],["title",_.string().min(1).optional().describe("New title.")],["description",_.string().nullable().optional().describe("New description. Pass null to clear it.")],["status",_.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('New status. "done"/"canceled" satisfy dependent tasks; "blocked" is a manual hold.')],["status_note",_.string().nullable().optional().describe("Short human-readable note about the current status. Pass null to clear it.")],["position",_.number().int().min(0).optional().describe("New sort position among siblings.")],["parent_id",_.string().optional().describe("task_id of the GROUP to move this issue into. Do not combine with clear_parent.")],["clear_parent",_.boolean().optional().describe("true moves the issue to the top level (no group). Do not combine with parent_id.")],["assignee",_.string().optional().describe("Username of a workspace member to assign. Do not combine with clear_assignee.")],["clear_assignee",_.boolean().optional().describe("true removes the assignee. Do not combine with assignee.")],["lock_version",_.number().int().positive().optional().describe("The task's lock_version from your last read, for compare-and-swap safety.")]]),async f=>await d(c.updateProjectTask(f))),e.registerTool("linzumi_delete_project_task",`Permanently delete a task group or issue. Dependency edges on the task are removed with it (dependents may become ready). Deletion is normally the USER's call - prefer status "canceled" or an update unless you are certain the entry is obsolete.`,Object.fromEntries([["task_id",_.string().describe("task_id of the group or issue to delete.")]]),async f=>await d(c.deleteProjectTask(f))),e.registerTool("linzumi_add_project_task_dependency",'Add the dependency edge "task_id is blocked by depends_on_task_id" between two ISSUES in the same project (groups cannot have dependencies). The dependent stays blocked until the prerequisite reaches done or canceled. The graph must stay acyclic: an edge that would create a cycle is refused with reason "would_create_cycle" and the offending cycle_path so you can restructure. Duplicate and self edges are rejected.',Object.fromEntries([["task_id",_.string().describe("task_id of the DEPENDENT issue (the one that must wait).")],["depends_on_task_id",_.string().describe("task_id of the PREREQUISITE issue (the one that must finish first).")]]),async f=>await d(c.addProjectTaskDependency(f))),e.registerTool("linzumi_remove_project_task_dependency",'Remove the dependency edge "task_id is blocked by depends_on_task_id". The dependent issue may become ready if that was its last unsatisfied dependency.',Object.fromEntries([["task_id",_.string().describe("task_id of the DEPENDENT issue.")],["depends_on_task_id",_.string().describe("task_id of the PREREQUISITE issue the edge points at.")]]),async f=>await d(c.removeProjectTaskDependency(f))),e.registerTool("linzumi_get_call_transcript","Read the full transcript of a completed Linzumi notetaker call: call metadata (title, platform, started/ended/transcribed times), participants, and every spoken segment in order with speaker names and millisecond offsets. Pass the call_id embedded in the request (or copied from the call card). Errors: call_not_found (missing or not visible to you), call_transcript_not_ready (call still connecting, in progress, or transcribing - retry later).",Object.fromEntries([["call_id",_.string().describe("The call id from the call card or the launching message (a CallRecording id - the opaque GraphQL id and the bare uuid both work).")]]),async f=>await d(c.getCallTranscript(f))),!n){e.registerTool("linzumi_start_coding_job","Start a coding job as the invoking user (same authorization and pipeline as clicking start). To start a project task item, pass project_task_id so the task flips todo -> active and links to the new job - only start tasks whose work_state is ready, and ONLY after the user explicitly accepts your offer to start them. Omit channel, runner_key, and cwd to reuse this job's own channel, computer, and folder. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",Object.fromEntries([["work_description",_.string().min(1).describe("What the job should do - the initial instruction. For a task item, write it from the task title and description.")],["project_task_id",_.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job.")],["visibility",_.enum(["project","private"]).optional().describe("Child-job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants.")],["channel",_.string().optional().describe("Channel slug to host the job thread. Omit to use this job's own channel.")],["runner_key",_.string().optional().describe("Runner (computer) to run the job on. Omit to use this job's own computer.")],["cwd",_.string().optional().describe("Working directory on the runner. Omit to use this job's own folder.")],["model",_.string().optional().describe("Model override (optional).")],["model_provider",_.string().optional().describe("Model provider override, e.g. 'wafer' (optional).")],["agent_provider",_.string().optional().describe("Agent provider override, e.g. 'codex' (optional).")],["reasoning_effort",_.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional).")],["approval_policy",_.enum(["default","on-request","on-failure","never"]).optional().describe("Approval policy override (optional).")],["sandbox",_.enum(["default","workspace-write","read-only","danger-full-access"]).optional().describe("Sandbox override (optional).")],["fast",_.boolean().optional().describe("Fast-mode override (optional).")],["allow_port_forwarding_by_default",_.boolean().optional().describe("Default port-forwarding override (optional).")],["execution_mode",_.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional).")],["egress_mode",_.enum(["open","hardened"]).optional().describe("Local-VM egress override (optional).")]]),async g=>await d(c.agentStartCodingJob(sr(g,o))));let f=t.multiAgentJobs;f!==void 0&&f&&(e.registerTool("linzumi_spawn_child_job","Spawn a durable child coding job under YOUR OWN job, on any harness or model - plan a DAG and delegate its legs to workers you then coordinate through discovery and messaging. The child lands on this job's channel, computer, and folder; it inherits this job's project and visibility (a private parent's children stay private), human roles cascade to it, and a human manages its lifecycle. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",Object.fromEntries([["work_description",_.string().min(1).describe("What the child job should do - the initial instruction, written to stand alone.")],["agent_provider",_.string().optional().describe("Harness for the child, e.g. 'codex' or 'claude-code'. Omit to reuse this job's own harness. A different harness is fine: a cross-harness child is always a child job.")],["model",_.string().optional().describe("Model override for the child (optional).")],["model_provider",_.string().optional().describe("Model provider override, e.g. 'wafer' (optional).")],["reasoning_effort",_.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional).")],["project_task_id",_.string().optional().describe("Project task item to bind the child to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job.")],["visibility",_.enum(["project","private"]).optional().describe("Child visibility. Defaults to this job's own visibility; a private parent's children must stay private.")]]),async g=>await d(c.agentSpawnChildJob(sr(g,o)))),e.registerTool("linzumi_discover_coding_jobs","Search current sitreps inside this coding job project for overlapping files, modules, objectives, or blockers. Results include durable job addresses for coordination. Private jobs outside your visible set never appear.",Object.fromEntries([["query",_.string().min(1).describe("Free-text clash-surface query, such as a file path, module, migration, or objective.")]]),async g=>{let y={};return Object.entries(g).forEach(v=>{y[v[0]]=v[1]}),y.source_thread_id=ed(wt(o,v=>v)),await d(c.agentDiscoverCodingJobs(y))}),e.registerTool("linzumi_send_coding_job_message","Message a visible coding job in this project, or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",Object.fromEntries([["channel",_.string().optional().describe("Channel slug hosting the target job. Required unless to_user is set.")],["thread_id",_.string().uuid().optional().describe("Target job thread UUID. Required unless to_user is set.")],["to_user",_.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox.")],["body",_.string().min(1).describe("Coordination message to send.")],["delivery",_.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")]]),async g=>{let y={};return Object.entries(g).forEach(v=>{y[v[0]]=v[1]}),y.source_thread_id=ed(wt(o,v=>v)),await d(c.agentSendCodingJobMessage(y))}))}break;case"Coding":case"OnboardingDiscovery":break}switch($z(u)&&(e.registerTool("linzumi_upload_custom_emoji","Upload a local image as a workspace custom emoji. For generated emoji art, create a transparent PNG with a simple centered subject, crisp edges, strong contrast, minimal tiny details, and enough outline/highlight separation to read at 16-24px on both dark and light backgrounds. Use lowercase shortcode names without colons unless preserving a user-provided :name:.",Object.fromEntries([["name",dv().describe("Custom emoji shortcode name, with or without surrounding colons.")],["file",_.string().min(1).describe("Local PNG/WebP/GIF/JPEG file path to upload. Prefer transparent PNG for generated emoji.")],["workspace",Ee()]]),async f=>{let g=Xt(f.name),y=Xt(f.file);return St(await my({client:c,cwd:a,serviceUrl:s,name:g!==void 0?g:"",file:y!==void 0?y:"",workspace:Xt(f.workspace)}))}),e.registerTool("linzumi_rename_custom_emoji","Rename an existing workspace custom emoji. The new name may include surrounding colons; Linzumi stores the normalized shortcode without colons.",Object.fromEntries([["emoji_id",_.union([_.string(),_.number().int().positive()]).describe("Workspace custom emoji id returned by linzumi_upload_custom_emoji or workspace emoji listings.")],["name",dv().describe("New shortcode name, with or without surrounding colons.")],["workspace",Ee()]]),async f=>await d(c.renameCustomEmoji(f)))),e.registerTool("linzumi_media_guide","Return the full Linzumi rich-media authoring guide (audio/video/image directives, URL rules, upload-then-embed flow, examples). Call once BEFORE writing any ::audio/::video/::image directive or Markdown image into a Linzumi message.",{},async f=>{let g={};g.type="text",g.text=nv;let y={};return y.content=[g],y}),e.registerTool("linzumi_note_project_directory","Record one discovered local Git repository or worktree for onboarding import. Call once per project as soon as it is found.",Object.fromEntries([["workspace",Ee()],["runner_id",_.string().min(1).describe("Local runner/computer id provided in the discovery prompt.")],["path",_.string().min(1).describe("Absolute local path to the repository worktree root.")],["display_name",_.string().optional().describe("Short project label. Defaults to the path basename.")],["activity_at",_.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp.")],["import_key",_.string().optional().describe("Stable dedupe key. Defaults to path.")],["metadata",_.record(_.unknown()).optional().describe("Small structured metadata such as branch or remote origin.")]]),async f=>await d(c.noteProjectDirectory(f))),e.registerTool("linzumi_note_agent_conversation","Record one discovered Codex or Claude Code local conversation for onboarding import. Call once per conversation as soon as it is found.",Object.fromEntries([["workspace",Ee()],["runner_id",_.string().min(1).describe("Local runner/computer id provided in the discovery prompt.")],["source",_.enum(["codex","claude_code"]).describe("Conversation source.")],["import_key",_.string().min(1).describe("Stable dedupe key, such as a session id or file path.")],["path",_.string().optional().describe("Absolute local path to the conversation file or directory.")],["display_name",_.string().optional().describe("Short label for the discovered conversation.")],["activity_at",_.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp.")],["metadata",_.record(_.unknown()).optional().describe("Small structured metadata such as session id or project path.")]]),async f=>await d(c.noteAgentConversation(f))),e.registerTool("linzumi_note_onboarding_discovery_status","Record onboarding discovery progress. Call when a search phase starts, checks another place, completes, or fails.",Object.fromEntries([["workspace",Ee()],["runner_id",_.string().min(1).describe("Local runner/computer id provided in the discovery prompt.")],["phase",_.enum(["projects","conversations"]).describe("Discovery phase being reported.")],["status",_.enum(["starting","running","completed","failed"]).describe("Current phase status.")],["places_searched",_.number().int().nonnegative().optional().describe("Count of concrete folders/files/known locations checked so far.")],["message",_.string().optional().describe("Short user-facing status note.")],["current_place",_.string().optional().describe("Current folder, file, Git command target, or known location being checked.")],["current_source",_.string().optional().describe("Short machine-readable source label such as git, codex, or claude_code.")],["last_error",_.string().optional().describe("Short failure detail when status is failed.")],["metadata",_.record(_.unknown()).optional().describe("Small structured status metadata.")]]),async f=>await d(c.noteOnboardingDiscoveryStatus(f))),u==="All"&&Ez(t.operatingMode)&&(e.registerTool("linzumi_dm_owner","Send a plain-text DM to the configured Commander owner. Requires dm.write and a visible owner username.",Object.fromEntries([["owner_username",_.string().optional().describe("Owner username. Defaults to LINZUMI_MCP_OWNER_USERNAME or --owner-username.")],["workspace",Ee()],["channel",_.string().optional().describe("Source channel slug used to verify owner visibility.")],["body",_.string().min(1).max(2e4).describe("Plain-text message body to DM.")]]),async f=>{let g=Xt(f.owner_username),y=g!==void 0?g:i;if(y===void 0)return Ve("owner_username is required for linzumi_dm_owner");let v=cn(f);return v.owner_username=y,await d(c.dmOwner(v))}),e.registerTool("linzumi_send_channel_message","Post a NEW standalone Markdown message into the scoped Linzumi channel as the authenticated local-runner user. This is NOT how you respond to the user: your turn output is already relayed into the thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to proactively post a separate channel message. Requires channel.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",Object.fromEntries([["workspace",Ee()],["channel",Qt()],["body",_.string().min(1).max(2e4).describe("Markdown message body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths.")]]),async f=>await d(c.sendChannelMessage(f))),e.registerTool("linzumi_send_thread_reply","Post a Markdown reply into some OTHER existing Linzumi thread as the authenticated local-runner user. This is NOT how you respond to the user in your current thread: your turn output is already relayed into this thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to post into a different, explicitly identified thread. Requires thread.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",Object.fromEntries([["workspace",Ee()],["channel",Qt()],["thread_id",_.string().uuid().describe("Existing Linzumi thread UUID.")],["body",_.string().min(1).max(2e4).describe("Markdown reply body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths.")]]),async f=>await d(c.sendThreadReply(f))),e.registerTool("linzumi_send_dm","Send a plain-text DM as the authenticated local-runner user to a visible user in the scoped workspace/channel. Requires dm.write.",Object.fromEntries([["workspace",Ee()],["channel",_.string().optional().describe("Source channel slug used to verify target visibility.")],["username",_.string().describe("Visible Linzumi username to DM.")],["body",_.string().min(1).max(2e4).describe("Plain-text message body to DM.")]]),async f=>await d(c.sendDm(f)))),u){case"All":e.registerTool("linzumi_get_vault_values","Request values for explicit vault env var names after a thread-scoped human approval. Requires vault.read; thread_id resolves the approval thread.",Object.fromEntries([["workspace",Ee()],["channel",_.string().optional().describe("Channel slug used to disambiguate the approval thread when needed.")],["thread_id",_.string().uuid().describe("Existing Linzumi thread UUID for the inline approval.")],["env_var_names",_.array(_.string().regex(new RegExp("^[A-Z][A-Z0-9_]{0,127}$"))).min(1).max(20).describe("Explicit vault env var names to request. This tool cannot list all vault keys.")],["description",_.string().min(1).max(500).describe("Human-readable reason shown in the approval request.")],["justification",_.string().min(10).max(1e3).describe("Agent justification shown to the approver.")]]),async f=>await d(c.getVaultValues(f)));break;case"Coding":case"OnboardingDiscovery":break}switch(u){case"All":return n||r===void 0?void 0:Pz(e,a,r);case"Coding":case"OnboardingDiscovery":return}}function Rz(e){let t=e.replaceAll("-","+").replaceAll("_","/");switch(t.length&3){case 2:return t+"==";case 3:return t+"=";default:return t}}function Iz(e){let t=e.split(".")[1];if(t===void 0)return;let r=Buffer.from(Rz(t),"base64").toString("utf8"),n;try{n=JSON.parse(r)}catch{n=void 0}if(typeof n=="object"&&n!==null&&!Array.isArray(n))return n}var Rd=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function gv(e){let t=Iz(e);if(t===void 0)return!1;let n=t.document_surfaces===!0,i=t.linzumi_agent_session,o=typeof i=="string"?Rd.test(i):!1,s=t.coding_job_id,a=t.coding_job_thread_id,u=typeof s=="string"&&typeof a=="string"?Rd.test(s)&&Rd.test(a):!1;return n?o?!0:u:!1}function Nz(e){return typeof e==="undefined"?!0:e===null}function Id(e){let t=Pt(e.serviceUrl);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};let r=t._0,n=e.fetchImpl,i=n!==void 0?n:Ma,o=e.authMode,s=o!==void 0&&o!=="LocalRunner"?"/api/v2/personal-agent-mcp":"/api/v2/local-runner-mcp",a=e.operatingMode,u=a!==void 0?$d(a):"text",c=async(l,d,h)=>{let m=Xr(d,r),p;p=m.TAG==="Ok"?m._0:Ve(m._0);let f={};Object.entries(h).forEach(K=>{f[K[0]]=K[1]}),f.operating_mode=u;let g={};g.authorization="Bearer "+e.accessToken;let y;if(l==="Get"){let K=p.searchParams;Object.entries(f).forEach(ce=>{let C=ce[1];if(!Nz(C)){K.set(ce[0],String(C));return}}),y=await i.json(p.toString(),{method:"GET",headers:g})}else g["content-type"]="application/json",y=await i.json(p.toString(),{method:"POST",headers:g,body:JSON.stringify(f)});let v=await y.json(),b;if(b=typeof v=="object"&&v!==null&&!Array.isArray(v)?v:void 0,b===void 0)return Ve("Linzumi MCP API returned non-object JSON from "+d);let w=y.ok,S=Ot(b.ok,!0),q=0;if(w){if(S)return b;q=1}else q=1;if(q===1){let K=b.error,ce,C=0;typeof K=="string"?ce=K:C=2,C===2&&(ce="HTTP "+y.status.toString());let G=b.detail,H=typeof G=="string"?" detail="+G:"";return Ve("Linzumi MCP API "+d+" failed: "+ce+H)}};return{TAG:"Ok",_0:{validateAuth:()=>c("Get",s+"/validate",{}),issueOnboardingDiscoveryToken:l=>c("Post",s+"/onboarding-discovery-token",l),getMessage:l=>c("Get",s+"/message",l),getThread:l=>c("Get",s+"/thread",l),getThreadTranscript:l=>c("Get",s+"/thread-transcript",l),getChannel:l=>c("Get",s+"/channel",l),searchWorkspace:l=>c("Get",s+"/search",l),askWorkspace:l=>c("Post",s+"/ask",l),aboutMe:l=>c("Get",s+"/about-me",l),webSearch:l=>c("Get",s+"/web-search",l),fetchUrl:l=>c("Get",s+"/fetch-url",l),listUiTargets:l=>c("Get",s+"/ui-targets",l),openUi:l=>c("Post",s+"/open-ui",l),getCodingJobMetadata:l=>c("Get",s+"/coding-job-metadata",l),listProjects:l=>c("Get",s+"/projects",l),getProjectTasks:l=>c("Get",s+"/project-tasks",l),createProjectTask:l=>c("Post",s+"/project-tasks/create",l),updateProjectTask:l=>c("Post",s+"/project-tasks/update",l),deleteProjectTask:l=>c("Post",s+"/project-tasks/delete",l),addProjectTaskDependency:l=>c("Post",s+"/project-tasks/add-dependency",l),removeProjectTaskDependency:l=>c("Post",s+"/project-tasks/remove-dependency",l),getCallTranscript:l=>c("Get",s+"/call-transcript",l),renameCodingJob:l=>c("Post",s+"/coding-job-title",l),upsertCodingJobPlan:l=>c("Post",s+"/coding-job-plan",l),replaceCodingJobPlanSteps:l=>c("Post",s+"/coding-job-plan/steps",l),updateCodingJobPlanStep:l=>c("Post",s+"/coding-job-plan/step",l),linkCodingJobPullRequest:l=>c("Post",s+"/coding-job-primary-pr",l),listVaultSecrets:l=>c("Get",s+"/vault-secrets",l),noteProjectDirectory:l=>c("Post",s+"/discovered-project",l),noteAgentConversation:l=>c("Post",s+"/discovered-conversation",l),noteOnboardingDiscoveryStatus:l=>c("Post",s+"/discovery-status",l),sendChannelMessage:l=>c("Post",s+"/channel-message",l),editMessage:l=>c("Post",s+"/message/edit",l),agentReply:l=>c("Post",s+"/agent-reply",l),agentTurnProgress:l=>c("Post",s+"/agent-turn-progress",l),agentDocumentTool:l=>c("Post",s+"/agent/document-tool",l),agentListCodingJobs:l=>c("Get",s+"/agent/coding-jobs",l),agentStartCodingJob:l=>c("Post",s+"/agent/start-coding-job",l),agentSpawnChildJob:l=>c("Post",s+"/agent/spawn-child-job",l),agentInterruptCodingJob:l=>c("Post",s+"/agent/interrupt-coding-job",l),agentSendCodingJobMessage:l=>c("Post",s+"/agent/send-coding-job-message",l),agentDiscoverCodingJobs:l=>c("Get",s+"/agent/discover-coding-jobs",l),agentReadCodingJobThread:l=>c("Get",s+"/agent/coding-job-thread",l),agentResolveJobApproval:l=>c("Post",s+"/agent/resolve-job-approval",l),agentArchiveCodingJob:l=>c("Post",s+"/agent/archive-coding-job",l),agentUnarchiveCodingJob:l=>c("Post",s+"/agent/unarchive-coding-job",l),agentSetThreadStatus:l=>c("Post",s+"/agent/set-thread-status",l),agentCreateChannel:l=>c("Post",s+"/agent/create-channel",l),agentRenameChannel:l=>c("Post",s+"/agent/rename-channel",l),agentArchiveChannel:l=>c("Post",s+"/agent/archive-channel",l),agentUnarchiveChannel:l=>c("Post",s+"/agent/unarchive-channel",l),agentAddReaction:l=>c("Post",s+"/agent/add-reaction",l),agentRemoveReaction:l=>c("Post",s+"/agent/remove-reaction",l),agentPinMessage:l=>c("Post",s+"/agent/pin-message",l),agentUnpinMessage:l=>c("Post",s+"/agent/unpin-message",l),prepareMessageUploads:l=>c("Post",s+"/message-uploads/prepare",l),attachMessageFiles:l=>c("Post",s+"/message-files/attach",l),prepareCustomEmoji:l=>c("Post",s+"/custom-emoji/prepare",l),renameCustomEmoji:l=>c("Post",s+"/custom-emoji/rename",l),sendThreadReply:l=>c("Post",s+"/thread-reply",l),sendDm:l=>c("Post",s+"/dm",l),dmOwner:l=>c("Post",s+"/dm-owner",l),getVaultValues:l=>c("Post",s+"/vault-values",l)}}}var Dz=Object.freeze({status:"aborted"});function k(e,t,r){function n(a,u){var c;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(c=a._zod).traits??(c.traits=new Set),a._zod.traits.add(e),t(a,u);for(let l in s.prototype)l in a||Object.defineProperty(a,l,{value:s.prototype[l].bind(a)});a._zod.constr=s,a._zod.def=u}let i=r?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function s(a){var u;let c=r?.Parent?new o:this;n(c,a),(u=c._zod).deferred??(u.deferred=[]);for(let l of c._zod.deferred)l();return c}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var fn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},kc={};function Yt(e){return e&&Object.assign(kc,e),kc}var ae={};au(ae,{BIGINT_FORMAT_RANGES:()=>yv,Class:()=>Nd,NUMBER_FORMAT_RANGES:()=>Ud,aborted:()=>Ai,allowsEval:()=>Ld,assert:()=>Uz,assertEqual:()=>Zz,assertIs:()=>qz,assertNever:()=>Fz,assertNotEqual:()=>Lz,assignProp:()=>Zd,cached:()=>zs,captureStackTrace:()=>Tc,cleanEnum:()=>rO,cleanRegex:()=>As,clone:()=>er,createTransparentProxy:()=>Hz,defineLazy:()=>ze,esc:()=>Oi,escapeRegex:()=>jn,extend:()=>Xz,finalizeIssue:()=>xr,floatSafeRemainder:()=>Dd,getElementAtPath:()=>Gz,getEnumValues:()=>Es,getLengthableOrigin:()=>Ps,getParsedType:()=>Wz,getSizableOrigin:()=>vv,isObject:()=>xo,isPlainObject:()=>ko,issue:()=>Gd,joinValues:()=>Sc,jsonStringifyReplacer:()=>Md,merge:()=>Yz,normalizeParams:()=>J,nullish:()=>Os,numKeys:()=>Jz,omit:()=>Qz,optionalKeys:()=>Fd,partial:()=>eO,pick:()=>Kz,prefixIssues:()=>Gr,primitiveTypes:()=>_v,promiseAllObject:()=>Vz,propertyKeyTypes:()=>qd,randomString:()=>Bz,required:()=>tO,stringifyPrimitive:()=>$c,unwrapMessage:()=>$s});function Zz(e){return e}function Lz(e){return e}function qz(e){}function Fz(e){throw new Error}function Uz(e){}function Es(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function Sc(e,t="|"){return e.map(r=>$c(r)).join(t)}function Md(e,t){return typeof t=="bigint"?t.toString():t}function zs(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Os(e){return e==null}function As(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Dd(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return o%s/10**i}function ze(e,t,r){Object.defineProperty(e,t,{get(){{let i=r();return e[t]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Zd(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Gz(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Vz(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let i={};for(let o=0;o<t.length;o++)i[t[o]]=n[o];return i})}function Bz(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Oi(e){return JSON.stringify(e)}var Tc=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function xo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ld=zs(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function ko(e){if(xo(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(xo(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Jz(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var Wz=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},qd=new Set(["string","number","symbol"]),_v=new Set(["string","number","bigint","boolean","symbol","undefined"]);function jn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function er(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function J(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Hz(e){let t;return new Proxy({},{get(r,n,i){return t??(t=e()),Reflect.get(t,n,i)},set(r,n,i,o){return t??(t=e()),Reflect.set(t,n,i,o)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,i){return t??(t=e()),Reflect.defineProperty(t,n,i)}})}function $c(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Fd(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Ud={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},yv={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Kz(e,t){let r={},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return er(e,{...e._zod.def,shape:r,checks:[]})}function Qz(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return er(e,{...e._zod.def,shape:r,checks:[]})}function Xz(e,t){if(!ko(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return Zd(this,"shape",n),n},checks:[]};return er(e,r)}function Yz(e,t){return er(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Zd(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function eO(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(i[o]=e?new e({type:"optional",innerType:n[o]}):n[o])}else for(let o in n)i[o]=e?new e({type:"optional",innerType:n[o]}):n[o];return er(t,{...t._zod.def,shape:i,checks:[]})}function tO(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let o in r){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(i[o]=new e({type:"nonoptional",innerType:n[o]}))}else for(let o in n)i[o]=new e({type:"nonoptional",innerType:n[o]});return er(t,{...t._zod.def,shape:i,checks:[]})}function Ai(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Gr(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function $s(e){return typeof e=="string"?e:e?.message}function xr(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let i=$s(e.inst?._zod.def?.error?.(e))??$s(t?.error?.(e))??$s(r.customError?.(e))??$s(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function vv(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Ps(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Gd(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function rO(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Nd=class{constructor(...t){}};var bv=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,Md,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ec=k("$ZodError",bv),Cs=k("$ZodError",bv,{Parent:Error});function Vd(e,t=r=>r.message){let r={},n=[];for(let i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function Bd(e,t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>i({issues:a}));else if(s.code==="invalid_key")i({issues:s.issues});else if(s.code==="invalid_element")i({issues:s.issues});else if(s.path.length===0)n._errors.push(r(s));else{let a=n,u=0;for(;u<s.path.length;){let c=s.path[u];u===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(s))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return i(e),n}var Jd=e=>(t,r,n,i)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new fn;if(s.issues.length){let a=new(i?.Err??e)(s.issues.map(u=>xr(u,o,Yt())));throw Tc(a,i?.callee),a}return s.value},Wd=Jd(Cs),Hd=e=>async(t,r,n,i)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(i?.Err??e)(s.issues.map(u=>xr(u,o,Yt())));throw Tc(a,i?.callee),a}return s.value},Kd=Hd(Cs),Qd=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new fn;return o.issues.length?{success:!1,error:new(e??Ec)(o.issues.map(s=>xr(s,i,Yt())))}:{success:!0,data:o.value}},Pi=Qd(Cs),Xd=e=>async(t,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},o=t._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(s=>xr(s,i,Yt())))}:{success:!0,data:o.value}},Ci=Xd(Cs);var wv=/^[cC][^\s-]{8,}$/,xv=/^[0-9a-z]+$/,kv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Sv=/^[0-9a-vA-V]{20}$/,Tv=/^[A-Za-z0-9]{27}$/,$v=/^[a-zA-Z0-9_-]{21}$/,Ev=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var zv=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Yd=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var Ov=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var iO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Av(){return new RegExp(iO,"u")}var Pv=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Cv=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Rv=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Iv=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ef=/^[A-Za-z0-9_-]*$/,Nv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Mv=/^\+(?:[0-9]){6,14}[0-9]$/,Dv="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Zv=new RegExp(`^${Dv}$`);function Lv(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function qv(e){return new RegExp(`^${Lv(e)}$`)}function Fv(e){let t=Lv({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Dv}T(?:${n})$`)}var Uv=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Gv=/^\d+$/,Vv=/^-?\d+(?:\.\d+)?/i,Bv=/true|false/i,Jv=/null/i;var Wv=/^[^A-Z]*$/,Hv=/^[^a-z]*$/;var pt=k("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Kv={number:"number",bigint:"bigint",object:"date"},tf=k("$ZodCheckLessThan",(e,t)=>{pt.init(e,t);let r=Kv[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,o=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),rf=k("$ZodCheckGreaterThan",(e,t)=>{pt.init(e,t);let r=Kv[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Qv=k("$ZodCheckMultipleOf",(e,t)=>{pt.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Dd(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Xv=k("$ZodCheckNumberFormat",(e,t)=>{pt.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[i,o]=Ud[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=i,a.maximum=o,r&&(a.pattern=Gv)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:e})}});var Yv=k("$ZodCheckMaxLength",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Os(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let i=n.value;if(i.length<=t.maximum)return;let s=Ps(i);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),eb=k("$ZodCheckMinLength",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Os(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let i=n.value;if(i.length>=t.minimum)return;let s=Ps(i);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),tb=k("$ZodCheckLengthEquals",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Os(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=n=>{let i=n.value,o=i.length;if(o===t.length)return;let s=Ps(i),a=o>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Rs=k("$ZodCheckStringFormat",(e,t)=>{var r,n;pt.init(e,t),e._zod.onattach.push(i=>{let o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),rb=k("$ZodCheckRegex",(e,t)=>{Rs.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),nb=k("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Wv),Rs.init(e,t)}),ib=k("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Hv),Rs.init(e,t)}),ob=k("$ZodCheckIncludes",(e,t)=>{pt.init(e,t);let r=jn(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(i=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),sb=k("$ZodCheckStartsWith",(e,t)=>{pt.init(e,t);let r=new RegExp(`^${jn(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),ab=k("$ZodCheckEndsWith",(e,t)=>{pt.init(e,t);let r=new RegExp(`.*${jn(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var cb=k("$ZodCheckOverwrite",(e,t)=>{pt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Oc=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
290
321
  `).filter(s=>s),i=Math.min(...n.map(s=>s.length-s.trimStart().length)),o=n.map(s=>s.slice(i)).map(s=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let t=Function,r=this?.args,i=[...(this?.content??[""]).map(o=>` ${o}`)];return new t(...r,i.join(`
291
- `))}};var Fy={major:4,minor:0,patch:0};var fe=k("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Fy;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let i of n)for(let o of i._zod.onattach)o(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(o,s,a)=>{let l=mi(o),c;for(let u of s){if(u._zod.def.when){if(!u._zod.def.when(o))continue}else if(l)continue;let d=o.issues.length,h=u._zod.check(o);if(h instanceof Promise&&a?.async===!1)throw new nn;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,o.issues.length!==d&&(l||(l=mi(o,d)))});else{if(o.issues.length===d)continue;l||(l=mi(o,d))}}return c?c.then(()=>o):o};e._zod.run=(o,s)=>{let a=e._zod.parse(o,s);if(a instanceof Promise){if(s.async===!1)throw new nn;return a.then(l=>i(l,n,s))}return i(a,n,s)}}e["~standard"]={validate:i=>{try{let o=pi(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return hi(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),ds=k("$ZodString",(e,t)=>{fe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ky(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),xe=k("$ZodStringFormat",(e,t)=>{us.init(e,t),ds.init(e,t)}),fd=k("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=cy),xe.init(e,t)}),md=k("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ad(n))}else t.pattern??(t.pattern=ad());xe.init(e,t)}),pd=k("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ly),xe.init(e,t)}),hd=k("$ZodURL",(e,t)=>{xe.init(e,t),e._zod.check=r=>{try{let n=r.value,i=new URL(n),o=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:gy.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),gd=k("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=uy()),xe.init(e,t)}),_d=k("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=sy),xe.init(e,t)}),yd=k("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ty),xe.init(e,t)}),vd=k("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ry),xe.init(e,t)}),bd=k("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ny),xe.init(e,t)}),wd=k("$ZodXID",(e,t)=>{t.pattern??(t.pattern=iy),xe.init(e,t)}),xd=k("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=oy),xe.init(e,t)}),ev=k("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=xy(t)),xe.init(e,t)}),tv=k("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=vy),xe.init(e,t)}),rv=k("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=wy(t)),xe.init(e,t)}),nv=k("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ay),xe.init(e,t)}),kd=k("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=dy),xe.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Sd=k("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=fy),xe.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),$d=k("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=my),xe.init(e,t)}),Td=k("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=py),xe.init(e,t),e._zod.check=r=>{let[n,i]=r.value.split("/");try{if(!i)throw new Error;let o=Number(i);if(`${o}`!==i)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function iv(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var zd=k("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=hy),xe.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{iv(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function dz(e){if(!cd.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return iv(r)}var Ed=k("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=cd),xe.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{dz(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Ad=k("$ZodE164",(e,t)=>{t.pattern??(t.pattern=_y),xe.init(e,t)});function fz(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}var Od=k("$ZodJWT",(e,t)=>{xe.init(e,t),e._zod.check=r=>{fz(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Qa=k("$ZodNumber",(e,t)=>{fe.init(e,t),e._zod.pattern=e._zod.bag.pattern??$y,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),r}}),Pd=k("$ZodNumber",(e,t)=>{Cy.init(e,t),Qa.init(e,t)}),Cd=k("$ZodBoolean",(e,t)=>{fe.init(e,t),e._zod.pattern=Ty,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}});var Rd=k("$ZodNull",(e,t)=>{fe.init(e,t),e._zod.pattern=zy,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}});var Id=k("$ZodUnknown",(e,t)=>{fe.init(e,t),e._zod.parse=r=>r}),jd=k("$ZodNever",(e,t)=>{fe.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Gy(e,t,r){e.issues.length&&t.issues.push(...Dr(r,e.issues)),t.value[r]=e.value}var Nd=k("$ZodArray",(e,t)=>{fe.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let a=i[s],l=t.element._zod.run({value:a,issues:[]},n);l instanceof Promise?o.push(l.then(c=>Gy(c,r,s))):Gy(l,r,s)}return o.length?Promise.all(o).then(()=>r):r}});function Ka(e,t,r){e.issues.length&&t.issues.push(...Dr(r,e.issues)),t.value[r]=e.value}function By(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...Dr(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var Xa=k("$ZodObject",(e,t)=>{fe.init(e,t);let r=os(()=>{let d=Object.keys(t.shape);for(let p of d)if(!(t.shape[p]instanceof fe))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let h=Ku(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(h)}});we(e._zod,"propValues",()=>{let d=t.shape,h={};for(let p in d){let m=d[p]._zod;if(m.values){h[p]??(h[p]=new Set);for(let f of m.values)h[p].add(f)}}return h});let n=d=>{let h=new Ha(["shape","payload","ctx"]),p=r.value,m=v=>{let b=fi(v);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};h.write("const input = payload.value;");let f=Object.create(null),g=0;for(let v of p.keys)f[v]=`key_${g++}`;h.write("const newResult = {}");for(let v of p.keys)if(p.optionalKeys.has(v)){let b=f[v];h.write(`const ${b} = ${m(v)};`);let w=fi(v);h.write(`
322
+ `))}};var ub={major:4,minor:0,patch:0};var Se=k("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ub;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let i of n)for(let o of i._zod.onattach)o(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(o,s,a)=>{let u=Ai(o),c;for(let l of s){if(l._zod.def.when){if(!l._zod.def.when(o))continue}else if(u)continue;let d=o.issues.length,h=l._zod.check(o);if(h instanceof Promise&&a?.async===!1)throw new fn;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,o.issues.length!==d&&(u||(u=Ai(o,d)))});else{if(o.issues.length===d)continue;u||(u=Ai(o,d))}}return c?c.then(()=>o):o};e._zod.run=(o,s)=>{let a=e._zod.parse(o,s);if(a instanceof Promise){if(s.async===!1)throw new fn;return a.then(u=>i(u,n,s))}return i(a,n,s)}}e["~standard"]={validate:i=>{try{let o=Pi(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Ci(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),Is=k("$ZodString",(e,t)=>{Se.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Uv(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Oe=k("$ZodStringFormat",(e,t)=>{Rs.init(e,t),Is.init(e,t)}),of=k("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=zv),Oe.init(e,t)}),sf=k("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Yd(n))}else t.pattern??(t.pattern=Yd());Oe.init(e,t)}),af=k("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ov),Oe.init(e,t)}),cf=k("$ZodURL",(e,t)=>{Oe.init(e,t),e._zod.check=r=>{try{let n=r.value,i=new URL(n),o=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Nv.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),lf=k("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Av()),Oe.init(e,t)}),uf=k("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=$v),Oe.init(e,t)}),df=k("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=wv),Oe.init(e,t)}),ff=k("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=xv),Oe.init(e,t)}),mf=k("$ZodULID",(e,t)=>{t.pattern??(t.pattern=kv),Oe.init(e,t)}),pf=k("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Sv),Oe.init(e,t)}),hf=k("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Tv),Oe.init(e,t)}),bb=k("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Fv(t)),Oe.init(e,t)}),wb=k("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Zv),Oe.init(e,t)}),xb=k("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=qv(t)),Oe.init(e,t)}),kb=k("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ev),Oe.init(e,t)}),gf=k("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Pv),Oe.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),_f=k("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Cv),Oe.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),yf=k("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Rv),Oe.init(e,t)}),vf=k("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Iv),Oe.init(e,t),e._zod.check=r=>{let[n,i]=r.value.split("/");try{if(!i)throw new Error;let o=Number(i);if(`${o}`!==i)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Sb(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var bf=k("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=jv),Oe.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Sb(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function oO(e){if(!ef.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Sb(r)}var wf=k("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ef),Oe.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{oO(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),xf=k("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Mv),Oe.init(e,t)});function sO(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}var kf=k("$ZodJWT",(e,t)=>{Oe.init(e,t),e._zod.check=r=>{sO(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Pc=k("$ZodNumber",(e,t)=>{Se.init(e,t),e._zod.pattern=e._zod.bag.pattern??Vv,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),r}}),Sf=k("$ZodNumber",(e,t)=>{Xv.init(e,t),Pc.init(e,t)}),Tf=k("$ZodBoolean",(e,t)=>{Se.init(e,t),e._zod.pattern=Bv,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}});var $f=k("$ZodNull",(e,t)=>{Se.init(e,t),e._zod.pattern=Jv,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}});var Ef=k("$ZodUnknown",(e,t)=>{Se.init(e,t),e._zod.parse=r=>r}),zf=k("$ZodNever",(e,t)=>{Se.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function db(e,t,r){e.issues.length&&t.issues.push(...Gr(r,e.issues)),t.value[r]=e.value}var Of=k("$ZodArray",(e,t)=>{Se.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let a=i[s],u=t.element._zod.run({value:a,issues:[]},n);u instanceof Promise?o.push(u.then(c=>db(c,r,s))):db(u,r,s)}return o.length?Promise.all(o).then(()=>r):r}});function Ac(e,t,r){e.issues.length&&t.issues.push(...Gr(r,e.issues)),t.value[r]=e.value}function fb(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...Gr(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var Cc=k("$ZodObject",(e,t)=>{Se.init(e,t);let r=zs(()=>{let d=Object.keys(t.shape);for(let m of d)if(!(t.shape[m]instanceof Se))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let h=Fd(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(h)}});ze(e._zod,"propValues",()=>{let d=t.shape,h={};for(let m in d){let p=d[m]._zod;if(p.values){h[m]??(h[m]=new Set);for(let f of p.values)h[m].add(f)}}return h});let n=d=>{let h=new Oc(["shape","payload","ctx"]),m=r.value,p=v=>{let b=Oi(v);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};h.write("const input = payload.value;");let f=Object.create(null),g=0;for(let v of m.keys)f[v]=`key_${g++}`;h.write("const newResult = {}");for(let v of m.keys)if(m.optionalKeys.has(v)){let b=f[v];h.write(`const ${b} = ${p(v)};`);let w=Oi(v);h.write(`
292
323
  if (${b}.issues.length) {
293
324
  if (input[${w}] === undefined) {
294
325
  if (${w} in input) {
@@ -307,19 +338,19 @@ args = `+wT(e.args)+`
307
338
  } else {
308
339
  newResult[${w}] = ${b}.value;
309
340
  }
310
- `)}else{let b=f[v];h.write(`const ${b} = ${m(v)};`),h.write(`
341
+ `)}else{let b=f[v];h.write(`const ${b} = ${p(v)};`),h.write(`
311
342
  if (${b}.issues.length) payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
312
343
  ...iss,
313
- path: iss.path ? [${fi(v)}, ...iss.path] : [${fi(v)}]
314
- })));`),h.write(`newResult[${fi(v)}] = ${b}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");let y=h.compile();return(v,b)=>y(d,v,b)},i,o=Yi,s=!Ua.jitless,l=s&&Wu.value,c=t.catchall,u;e._zod.parse=(d,h)=>{u??(u=r.value);let p=d.value;if(!o(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d;let m=[];if(s&&l&&h?.async===!1&&h.jitless!==!0)i||(i=n(t.shape)),d=i(d,h);else{d.value={};let b=u.shape;for(let w of u.keys){let S=b[w],Z=S._zod.run({value:p[w],issues:[]},h),F=S._zod.optin==="optional"&&S._zod.optout==="optional";Z instanceof Promise?m.push(Z.then(ce=>F?By(ce,d,w,p):Ka(ce,d,w))):F?By(Z,d,w,p):Ka(Z,d,w)}}if(!c)return m.length?Promise.all(m).then(()=>d):d;let f=[],g=u.keySet,y=c._zod,v=y.def.type;for(let b of Object.keys(p)){if(g.has(b))continue;if(v==="never"){f.push(b);continue}let w=y.run({value:p[b],issues:[]},h);w instanceof Promise?m.push(w.then(S=>Ka(S,d,b))):Ka(w,d,b)}return f.length&&d.issues.push({code:"unrecognized_keys",keys:f,input:p,inst:e}),m.length?Promise.all(m).then(()=>d):d}});function Jy(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(o=>hr(o,n,Jt())))}),t}var Ya=k("$ZodUnion",(e,t)=>{fe.init(e,t),we(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),we(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),we(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),we(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>as(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let i=!1,o=[];for(let s of t.options){let a=s._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)o.push(a),i=!0;else{if(a.issues.length===0)return a;o.push(a)}}return i?Promise.all(o).then(s=>Jy(s,r,e,n)):Jy(o,r,e,n)}}),Md=k("$ZodDiscriminatedUnion",(e,t)=>{Ya.init(e,t);let r=e._zod.parse;we(e._zod,"propValues",()=>{let i={};for(let o of t.options){let s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(let[a,l]of Object.entries(s)){i[a]||(i[a]=new Set);for(let c of l)i[a].add(c)}}return i});let n=os(()=>{let i=t.options,o=new Map;for(let s of i){let a=s._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let l of a){if(o.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);o.set(l,s)}}return o});e._zod.parse=(i,o)=>{let s=i.value;if(!Yi(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;let a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(i,o):t.unionFallback?r(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),i)}}),Dd=k("$ZodIntersection",(e,t)=>{fe.init(e,t),e._zod.parse=(r,n)=>{let i=r.value,o=t.left._zod.run({value:i,issues:[]},n),s=t.right._zod.run({value:i,issues:[]},n);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([l,c])=>Wy(r,l,c)):Wy(r,o,s)}});function dd(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(eo(e)&&eo(t)){let r=Object.keys(t),n=Object.keys(e).filter(o=>r.indexOf(o)!==-1),i={...e,...t};for(let o of n){let s=dd(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let i=e[n],o=t[n],s=dd(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Wy(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),mi(e))return e;let n=dd(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}var Zd=k("$ZodRecord",(e,t)=>{fe.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!eo(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;let o=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let l of s)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){let c=t.valueType._zod.run({value:i[l],issues:[]},n);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&r.issues.push(...Dr(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...Dr(l,c.issues)),r.value[l]=c.value)}let a;for(let l in i)s.has(l)||(a=a??[],a.push(l));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:a})}else{r.value={};for(let s of Reflect.ownKeys(i)){if(s==="__proto__")continue;let a=t.keyType._zod.run({value:s,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(c=>hr(c,n,Jt())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}let l=t.valueType._zod.run({value:i[s],issues:[]},n);l instanceof Promise?o.push(l.then(c=>{c.issues.length&&r.issues.push(...Dr(s,c.issues)),r.value[a.value]=c.value})):(l.issues.length&&r.issues.push(...Dr(s,l.issues)),r.value[a.value]=l.value)}}return o.length?Promise.all(o).then(()=>r):r}});var qd=k("$ZodEnum",(e,t)=>{fe.init(e,t);let r=is(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Hu.has(typeof n)).map(n=>typeof n=="string"?Sn(n):n.toString()).join("|")})$`),e._zod.parse=(n,i)=>{let o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:e}),n}}),Ld=k("$ZodLiteral",(e,t)=>{fe.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Sn(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let i=r.value;return e._zod.values.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}});var Vd=k("$ZodTransform",(e,t)=>{fe.init(e,t),e._zod.parse=(r,n)=>{let i=t.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(r.value=s,r));if(i instanceof Promise)throw new nn;return r.value=i,r}}),Ud=k("$ZodOptional",(e,t)=>{fe.init(e,t),e._zod.optin="optional",e._zod.optout="optional",we(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),we(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${as(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),Fd=k("$ZodNullable",(e,t)=>{fe.init(e,t),we(e._zod,"optin",()=>t.innerType._zod.optin),we(e._zod,"optout",()=>t.innerType._zod.optout),we(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${as(r.source)}|null)$`):void 0}),we(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Gd=k("$ZodDefault",(e,t)=>{fe.init(e,t),e._zod.optin="optional",we(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>Hy(o,t)):Hy(i,t)}});function Hy(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Bd=k("$ZodPrefault",(e,t)=>{fe.init(e,t),e._zod.optin="optional",we(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),Jd=k("$ZodNonOptional",(e,t)=>{fe.init(e,t),we(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>Ky(o,e)):Ky(i,e)}});function Ky(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Wd=k("$ZodCatch",(e,t)=>{fe.init(e,t),e._zod.optin="optional",we(e._zod,"optout",()=>t.innerType._zod.optout),we(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>hr(s,n,Jt()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(o=>hr(o,n,Jt()))},input:r.value}),r.issues=[]),r)}});var Hd=k("$ZodPipe",(e,t)=>{fe.init(e,t),we(e._zod,"values",()=>t.in._zod.values),we(e._zod,"optin",()=>t.in._zod.optin),we(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{let i=t.in._zod.run(r,n);return i instanceof Promise?i.then(o=>Qy(o,t,n)):Qy(i,t,n)}});function Qy(e,t,r){return mi(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var Kd=k("$ZodReadonly",(e,t)=>{fe.init(e,t),we(e._zod,"propValues",()=>t.innerType._zod.propValues),we(e._zod,"values",()=>t.innerType._zod.values),we(e._zod,"optin",()=>t.innerType._zod.optin),we(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(Xy):Xy(i)}});function Xy(e){return e.value=Object.freeze(e.value),e}var Qd=k("$ZodCustom",(e,t)=>{ot.init(e,t),fe.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(o=>Yy(o,r,n,e));Yy(i,r,n,e)}});function Yy(e,t,r,n){if(!e){let i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),t.issues.push(Xu(i))}}var mz=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},pz=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${mz(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ba(n.values[0])}`:`Invalid option: expected one of ${Fa(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",o=t(n.origin);return o?`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",o=t(n.origin);return o?`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${o.unit}`:`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Fa(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function ov(){return{localeError:pz()}}var fs=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function sv(){return new fs}var $n=sv();function Xd(e,t){return new e({type:"string",...L(t)})}function Yd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...L(t)})}function ec(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...L(t)})}function ef(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...L(t)})}function tf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...L(t)})}function rf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...L(t)})}function nf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...L(t)})}function of(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...L(t)})}function sf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...L(t)})}function af(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...L(t)})}function cf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...L(t)})}function lf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...L(t)})}function uf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...L(t)})}function df(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...L(t)})}function ff(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...L(t)})}function mf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...L(t)})}function pf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...L(t)})}function hf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...L(t)})}function gf(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...L(t)})}function _f(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...L(t)})}function yf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...L(t)})}function vf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...L(t)})}function bf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...L(t)})}function av(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...L(t)})}function cv(e,t){return new e({type:"string",format:"date",check:"string_format",...L(t)})}function lv(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...L(t)})}function uv(e,t){return new e({type:"string",format:"duration",check:"string_format",...L(t)})}function wf(e,t){return new e({type:"number",checks:[],...L(t)})}function xf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...L(t)})}function kf(e,t){return new e({type:"boolean",...L(t)})}function Sf(e,t){return new e({type:"null",...L(t)})}function $f(e){return new e({type:"unknown"})}function Tf(e,t){return new e({type:"never",...L(t)})}function tc(e,t){return new ld({check:"less_than",...L(t),value:e,inclusive:!1})}function ms(e,t){return new ld({check:"less_than",...L(t),value:e,inclusive:!0})}function rc(e,t){return new ud({check:"greater_than",...L(t),value:e,inclusive:!1})}function ps(e,t){return new ud({check:"greater_than",...L(t),value:e,inclusive:!0})}function nc(e,t){return new Py({check:"multiple_of",...L(t),value:e})}function ic(e,t){return new Ry({check:"max_length",...L(t),maximum:e})}function to(e,t){return new Iy({check:"min_length",...L(t),minimum:e})}function oc(e,t){return new jy({check:"length_equals",...L(t),length:e})}function zf(e,t){return new Ny({check:"string_format",format:"regex",...L(t),pattern:e})}function Ef(e){return new My({check:"string_format",format:"lowercase",...L(e)})}function Af(e){return new Dy({check:"string_format",format:"uppercase",...L(e)})}function Of(e,t){return new Zy({check:"string_format",format:"includes",...L(t),includes:e})}function Pf(e,t){return new qy({check:"string_format",format:"starts_with",...L(t),prefix:e})}function Cf(e,t){return new Ly({check:"string_format",format:"ends_with",...L(t),suffix:e})}function gi(e){return new Vy({check:"overwrite",tx:e})}function Rf(e){return gi(t=>t.normalize(e))}function If(){return gi(e=>e.trim())}function jf(){return gi(e=>e.toLowerCase())}function Nf(){return gi(e=>e.toUpperCase())}function dv(e,t,r){return new e({type:"array",element:t,...L(r)})}function Mf(e,t,r){let n=L(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Df(e,t,r){return new e({type:"custom",check:"custom",fn:t,...L(r)})}var sc=class{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??$n,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;let i=t._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},s=this.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,a);let l=t._zod.toJSONSchema?.();if(l)a.schema=l;else{let d={...r,schemaPath:[...r.schemaPath,t],path:r.path},h=t._zod.parent;if(h)a.ref=h,this.process(h,d),this.seen.get(h).isParent=!0;else{let p=a.schema;switch(i.type){case"string":{let m=p;m.type="string";let{minimum:f,maximum:g,format:y,patterns:v,contentEncoding:b}=t._zod.bag;if(typeof f=="number"&&(m.minLength=f),typeof g=="number"&&(m.maxLength=g),y&&(m.format=o[y]??y,m.format===""&&delete m.format),b&&(m.contentEncoding=b),v&&v.size>0){let w=[...v];w.length===1?m.pattern=w[0].source:w.length>1&&(a.schema.allOf=[...w.map(S=>({...this.target==="draft-7"?{type:"string"}:{},pattern:S.source}))])}break}case"number":{let m=p,{minimum:f,maximum:g,format:y,multipleOf:v,exclusiveMaximum:b,exclusiveMinimum:w}=t._zod.bag;typeof y=="string"&&y.includes("int")?m.type="integer":m.type="number",typeof w=="number"&&(m.exclusiveMinimum=w),typeof f=="number"&&(m.minimum=f,typeof w=="number"&&(w>=f?delete m.minimum:delete m.exclusiveMinimum)),typeof b=="number"&&(m.exclusiveMaximum=b),typeof g=="number"&&(m.maximum=g,typeof b=="number"&&(b<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof v=="number"&&(m.multipleOf=v);break}case"boolean":{let m=p;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{p.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{p.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=p,{minimum:f,maximum:g}=t._zod.bag;typeof f=="number"&&(m.minItems=f),typeof g=="number"&&(m.maxItems=g),m.type="array",m.items=this.process(i.element,{...d,path:[...d.path,"items"]});break}case"object":{let m=p;m.type="object",m.properties={};let f=i.shape;for(let v in f)m.properties[v]=this.process(f[v],{...d,path:[...d.path,"properties",v]});let g=new Set(Object.keys(f)),y=new Set([...g].filter(v=>{let b=i.shape[v]._zod;return this.io==="input"?b.optin===void 0:b.optout===void 0}));y.size>0&&(m.required=Array.from(y)),i.catchall?._zod.def.type==="never"?m.additionalProperties=!1:i.catchall?i.catchall&&(m.additionalProperties=this.process(i.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=p;m.anyOf=i.options.map((f,g)=>this.process(f,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let m=p,f=this.process(i.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(i.right,{...d,path:[...d.path,"allOf",1]}),y=b=>"allOf"in b&&Object.keys(b).length===1,v=[...y(f)?f.allOf:[f],...y(g)?g.allOf:[g]];m.allOf=v;break}case"tuple":{let m=p;m.type="array";let f=i.items.map((v,b)=>this.process(v,{...d,path:[...d.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?m.prefixItems=f:m.items=f,i.rest){let v=this.process(i.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?m.items=v:m.additionalItems=v}i.rest&&(m.items=this.process(i.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=t._zod.bag;typeof g=="number"&&(m.minItems=g),typeof y=="number"&&(m.maxItems=y);break}case"record":{let m=p;m.type="object",m.propertyNames=this.process(i.keyType,{...d,path:[...d.path,"propertyNames"]}),m.additionalProperties=this.process(i.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=p,f=is(i.entries);f.every(g=>typeof g=="number")&&(m.type="number"),f.every(g=>typeof g=="string")&&(m.type="string"),m.enum=f;break}case"literal":{let m=p,f=[];for(let g of i.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");f.push(Number(g))}else f.push(g);if(f.length!==0)if(f.length===1){let g=f[0];m.type=g===null?"null":typeof g,m.const=g}else f.every(g=>typeof g=="number")&&(m.type="number"),f.every(g=>typeof g=="string")&&(m.type="string"),f.every(g=>typeof g=="boolean")&&(m.type="string"),f.every(g=>g===null)&&(m.type="null"),m.enum=f;break}case"file":{let m=p,f={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:v}=t._zod.bag;g!==void 0&&(f.minLength=g),y!==void 0&&(f.maxLength=y),v?v.length===1?(f.contentMediaType=v[0],Object.assign(m,f)):m.anyOf=v.map(b=>({...f,contentMediaType:b})):Object.assign(m,f);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(i.innerType,d);p.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(i.innerType,d),a.ref=i.innerType;break}case"success":{let m=p;m.type="boolean";break}case"default":{this.process(i.innerType,d),a.ref=i.innerType,p.default=JSON.parse(JSON.stringify(i.defaultValue));break}case"prefault":{this.process(i.innerType,d),a.ref=i.innerType,this.io==="input"&&(p._prefault=JSON.parse(JSON.stringify(i.defaultValue)));break}case"catch":{this.process(i.innerType,d),a.ref=i.innerType;let m;try{m=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}p.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=p,f=t._zod.pattern;if(!f)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=f.source;break}case"pipe":{let m=this.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;this.process(m,d),a.ref=m;break}case"readonly":{this.process(i.innerType,d),a.ref=i.innerType,p.readOnly=!0;break}case"promise":{this.process(i.innerType,d),a.ref=i.innerType;break}case"optional":{this.process(i.innerType,d),a.ref=i.innerType;break}case"lazy":{let m=t._zod.innerType;this.process(m,d),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let c=this.metadataRegistry.get(t);return c&&Object.assign(a.schema,c),this.io==="input"&&Ge(t)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(t).schema}emit(t,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},i=this.seen.get(t);if(!i)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=u=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let f=n.external.registry.get(u[0])?.id,g=n.external.uri??(v=>v);if(f)return{ref:g(f)};let y=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(u[1]===i)return{ref:"#"};let p=`#/${d}/`,m=u[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:p+m}},s=u=>{if(u[1].schema.$ref)return;let d=u[1],{ref:h,defId:p}=o(u);d.def={...d.schema},p&&(d.defId=p);let m=d.schema;for(let f in m)delete m[f];m.$ref=h};if(n.cycles==="throw")for(let u of this.seen.entries()){let d=u[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
344
+ path: iss.path ? [${Oi(v)}, ...iss.path] : [${Oi(v)}]
345
+ })));`),h.write(`newResult[${Oi(v)}] = ${b}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");let y=h.compile();return(v,b)=>y(d,v,b)},i,o=xo,s=!kc.jitless,u=s&&Ld.value,c=t.catchall,l;e._zod.parse=(d,h)=>{l??(l=r.value);let m=d.value;if(!o(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),d;let p=[];if(s&&u&&h?.async===!1&&h.jitless!==!0)i||(i=n(t.shape)),d=i(d,h);else{d.value={};let b=l.shape;for(let w of l.keys){let S=b[w],q=S._zod.run({value:m[w],issues:[]},h),K=S._zod.optin==="optional"&&S._zod.optout==="optional";q instanceof Promise?p.push(q.then(ce=>K?fb(ce,d,w,m):Ac(ce,d,w))):K?fb(q,d,w,m):Ac(q,d,w)}}if(!c)return p.length?Promise.all(p).then(()=>d):d;let f=[],g=l.keySet,y=c._zod,v=y.def.type;for(let b of Object.keys(m)){if(g.has(b))continue;if(v==="never"){f.push(b);continue}let w=y.run({value:m[b],issues:[]},h);w instanceof Promise?p.push(w.then(S=>Ac(S,d,b))):Ac(w,d,b)}return f.length&&d.issues.push({code:"unrecognized_keys",keys:f,input:m,inst:e}),p.length?Promise.all(p).then(()=>d):d}});function mb(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(o=>xr(o,n,Yt())))}),t}var Rc=k("$ZodUnion",(e,t)=>{Se.init(e,t),ze(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ze(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ze(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),ze(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>As(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let i=!1,o=[];for(let s of t.options){let a=s._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)o.push(a),i=!0;else{if(a.issues.length===0)return a;o.push(a)}}return i?Promise.all(o).then(s=>mb(s,r,e,n)):mb(o,r,e,n)}}),Af=k("$ZodDiscriminatedUnion",(e,t)=>{Rc.init(e,t);let r=e._zod.parse;ze(e._zod,"propValues",()=>{let i={};for(let o of t.options){let s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(let[a,u]of Object.entries(s)){i[a]||(i[a]=new Set);for(let c of u)i[a].add(c)}}return i});let n=zs(()=>{let i=t.options,o=new Map;for(let s of i){let a=s._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let u of a){if(o.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);o.set(u,s)}}return o});e._zod.parse=(i,o)=>{let s=i.value;if(!xo(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;let a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(i,o):t.unionFallback?r(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),i)}}),Pf=k("$ZodIntersection",(e,t)=>{Se.init(e,t),e._zod.parse=(r,n)=>{let i=r.value,o=t.left._zod.run({value:i,issues:[]},n),s=t.right._zod.run({value:i,issues:[]},n);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([u,c])=>pb(r,u,c)):pb(r,o,s)}});function nf(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ko(e)&&ko(t)){let r=Object.keys(t),n=Object.keys(e).filter(o=>r.indexOf(o)!==-1),i={...e,...t};for(let o of n){let s=nf(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let i=e[n],o=t[n],s=nf(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function pb(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Ai(e))return e;let n=nf(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}var Cf=k("$ZodRecord",(e,t)=>{Se.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!ko(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;let o=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let u of s)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){let c=t.valueType._zod.run({value:i[u],issues:[]},n);c instanceof Promise?o.push(c.then(l=>{l.issues.length&&r.issues.push(...Gr(u,l.issues)),r.value[u]=l.value})):(c.issues.length&&r.issues.push(...Gr(u,c.issues)),r.value[u]=c.value)}let a;for(let u in i)s.has(u)||(a=a??[],a.push(u));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:a})}else{r.value={};for(let s of Reflect.ownKeys(i)){if(s==="__proto__")continue;let a=t.keyType._zod.run({value:s,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(c=>xr(c,n,Yt())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}let u=t.valueType._zod.run({value:i[s],issues:[]},n);u instanceof Promise?o.push(u.then(c=>{c.issues.length&&r.issues.push(...Gr(s,c.issues)),r.value[a.value]=c.value})):(u.issues.length&&r.issues.push(...Gr(s,u.issues)),r.value[a.value]=u.value)}}return o.length?Promise.all(o).then(()=>r):r}});var Rf=k("$ZodEnum",(e,t)=>{Se.init(e,t);let r=Es(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>qd.has(typeof n)).map(n=>typeof n=="string"?jn(n):n.toString()).join("|")})$`),e._zod.parse=(n,i)=>{let o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:e}),n}}),If=k("$ZodLiteral",(e,t)=>{Se.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?jn(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let i=r.value;return e._zod.values.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}});var jf=k("$ZodTransform",(e,t)=>{Se.init(e,t),e._zod.parse=(r,n)=>{let i=t.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(r.value=s,r));if(i instanceof Promise)throw new fn;return r.value=i,r}}),Nf=k("$ZodOptional",(e,t)=>{Se.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ze(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ze(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${As(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),Mf=k("$ZodNullable",(e,t)=>{Se.init(e,t),ze(e._zod,"optin",()=>t.innerType._zod.optin),ze(e._zod,"optout",()=>t.innerType._zod.optout),ze(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${As(r.source)}|null)$`):void 0}),ze(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Df=k("$ZodDefault",(e,t)=>{Se.init(e,t),e._zod.optin="optional",ze(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>hb(o,t)):hb(i,t)}});function hb(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Zf=k("$ZodPrefault",(e,t)=>{Se.init(e,t),e._zod.optin="optional",ze(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),Lf=k("$ZodNonOptional",(e,t)=>{Se.init(e,t),ze(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>gb(o,e)):gb(i,e)}});function gb(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var qf=k("$ZodCatch",(e,t)=>{Se.init(e,t),e._zod.optin="optional",ze(e._zod,"optout",()=>t.innerType._zod.optout),ze(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>xr(s,n,Yt()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(o=>xr(o,n,Yt()))},input:r.value}),r.issues=[]),r)}});var Ff=k("$ZodPipe",(e,t)=>{Se.init(e,t),ze(e._zod,"values",()=>t.in._zod.values),ze(e._zod,"optin",()=>t.in._zod.optin),ze(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{let i=t.in._zod.run(r,n);return i instanceof Promise?i.then(o=>_b(o,t,n)):_b(i,t,n)}});function _b(e,t,r){return Ai(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var Uf=k("$ZodReadonly",(e,t)=>{Se.init(e,t),ze(e._zod,"propValues",()=>t.innerType._zod.propValues),ze(e._zod,"values",()=>t.innerType._zod.values),ze(e._zod,"optin",()=>t.innerType._zod.optin),ze(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(yb):yb(i)}});function yb(e){return e.value=Object.freeze(e.value),e}var Gf=k("$ZodCustom",(e,t)=>{pt.init(e,t),Se.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(o=>vb(o,r,n,e));vb(i,r,n,e)}});function vb(e,t,r,n){if(!e){let i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),t.issues.push(Gd(i))}}var aO=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},cO=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${aO(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${$c(n.values[0])}`:`Invalid option: expected one of ${Sc(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",o=t(n.origin);return o?`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",o=t(n.origin);return o?`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${o.unit}`:`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Sc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Tb(){return{localeError:cO()}}var js=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function $b(){return new js}var Nn=$b();function Vf(e,t){return new e({type:"string",...J(t)})}function Bf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...J(t)})}function Ic(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...J(t)})}function Jf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...J(t)})}function Wf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...J(t)})}function Hf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...J(t)})}function Kf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...J(t)})}function Qf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...J(t)})}function Xf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...J(t)})}function Yf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...J(t)})}function em(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...J(t)})}function tm(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...J(t)})}function rm(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...J(t)})}function nm(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...J(t)})}function im(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...J(t)})}function om(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...J(t)})}function sm(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...J(t)})}function am(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...J(t)})}function cm(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...J(t)})}function lm(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...J(t)})}function um(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...J(t)})}function dm(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...J(t)})}function fm(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...J(t)})}function Eb(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...J(t)})}function zb(e,t){return new e({type:"string",format:"date",check:"string_format",...J(t)})}function Ob(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...J(t)})}function Ab(e,t){return new e({type:"string",format:"duration",check:"string_format",...J(t)})}function mm(e,t){return new e({type:"number",checks:[],...J(t)})}function pm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...J(t)})}function hm(e,t){return new e({type:"boolean",...J(t)})}function gm(e,t){return new e({type:"null",...J(t)})}function _m(e){return new e({type:"unknown"})}function ym(e,t){return new e({type:"never",...J(t)})}function jc(e,t){return new tf({check:"less_than",...J(t),value:e,inclusive:!1})}function Ns(e,t){return new tf({check:"less_than",...J(t),value:e,inclusive:!0})}function Nc(e,t){return new rf({check:"greater_than",...J(t),value:e,inclusive:!1})}function Ms(e,t){return new rf({check:"greater_than",...J(t),value:e,inclusive:!0})}function Mc(e,t){return new Qv({check:"multiple_of",...J(t),value:e})}function Dc(e,t){return new Yv({check:"max_length",...J(t),maximum:e})}function So(e,t){return new eb({check:"min_length",...J(t),minimum:e})}function Zc(e,t){return new tb({check:"length_equals",...J(t),length:e})}function vm(e,t){return new rb({check:"string_format",format:"regex",...J(t),pattern:e})}function bm(e){return new nb({check:"string_format",format:"lowercase",...J(e)})}function wm(e){return new ib({check:"string_format",format:"uppercase",...J(e)})}function xm(e,t){return new ob({check:"string_format",format:"includes",...J(t),includes:e})}function km(e,t){return new sb({check:"string_format",format:"starts_with",...J(t),prefix:e})}function Sm(e,t){return new ab({check:"string_format",format:"ends_with",...J(t),suffix:e})}function Ri(e){return new cb({check:"overwrite",tx:e})}function Tm(e){return Ri(t=>t.normalize(e))}function $m(){return Ri(e=>e.trim())}function Em(){return Ri(e=>e.toLowerCase())}function zm(){return Ri(e=>e.toUpperCase())}function Pb(e,t,r){return new e({type:"array",element:t,...J(r)})}function Om(e,t,r){let n=J(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Am(e,t,r){return new e({type:"custom",check:"custom",fn:t,...J(r)})}var Lc=class{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??Nn,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;let i=t._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},s=this.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,a);let u=t._zod.toJSONSchema?.();if(u)a.schema=u;else{let d={...r,schemaPath:[...r.schemaPath,t],path:r.path},h=t._zod.parent;if(h)a.ref=h,this.process(h,d),this.seen.get(h).isParent=!0;else{let m=a.schema;switch(i.type){case"string":{let p=m;p.type="string";let{minimum:f,maximum:g,format:y,patterns:v,contentEncoding:b}=t._zod.bag;if(typeof f=="number"&&(p.minLength=f),typeof g=="number"&&(p.maxLength=g),y&&(p.format=o[y]??y,p.format===""&&delete p.format),b&&(p.contentEncoding=b),v&&v.size>0){let w=[...v];w.length===1?p.pattern=w[0].source:w.length>1&&(a.schema.allOf=[...w.map(S=>({...this.target==="draft-7"?{type:"string"}:{},pattern:S.source}))])}break}case"number":{let p=m,{minimum:f,maximum:g,format:y,multipleOf:v,exclusiveMaximum:b,exclusiveMinimum:w}=t._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof w=="number"&&(p.exclusiveMinimum=w),typeof f=="number"&&(p.minimum=f,typeof w=="number"&&(w>=f?delete p.minimum:delete p.exclusiveMinimum)),typeof b=="number"&&(p.exclusiveMaximum=b),typeof g=="number"&&(p.maximum=g,typeof b=="number"&&(b<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof v=="number"&&(p.multipleOf=v);break}case"boolean":{let p=m;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=m,{minimum:f,maximum:g}=t._zod.bag;typeof f=="number"&&(p.minItems=f),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(i.element,{...d,path:[...d.path,"items"]});break}case"object":{let p=m;p.type="object",p.properties={};let f=i.shape;for(let v in f)p.properties[v]=this.process(f[v],{...d,path:[...d.path,"properties",v]});let g=new Set(Object.keys(f)),y=new Set([...g].filter(v=>{let b=i.shape[v]._zod;return this.io==="input"?b.optin===void 0:b.optout===void 0}));y.size>0&&(p.required=Array.from(y)),i.catchall?._zod.def.type==="never"?p.additionalProperties=!1:i.catchall?i.catchall&&(p.additionalProperties=this.process(i.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=m;p.anyOf=i.options.map((f,g)=>this.process(f,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let p=m,f=this.process(i.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(i.right,{...d,path:[...d.path,"allOf",1]}),y=b=>"allOf"in b&&Object.keys(b).length===1,v=[...y(f)?f.allOf:[f],...y(g)?g.allOf:[g]];p.allOf=v;break}case"tuple":{let p=m;p.type="array";let f=i.items.map((v,b)=>this.process(v,{...d,path:[...d.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?p.prefixItems=f:p.items=f,i.rest){let v=this.process(i.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=v:p.additionalItems=v}i.rest&&(p.items=this.process(i.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=t._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{let p=m;p.type="object",p.propertyNames=this.process(i.keyType,{...d,path:[...d.path,"propertyNames"]}),p.additionalProperties=this.process(i.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=m,f=Es(i.entries);f.every(g=>typeof g=="number")&&(p.type="number"),f.every(g=>typeof g=="string")&&(p.type="string"),p.enum=f;break}case"literal":{let p=m,f=[];for(let g of i.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");f.push(Number(g))}else f.push(g);if(f.length!==0)if(f.length===1){let g=f[0];p.type=g===null?"null":typeof g,p.const=g}else f.every(g=>typeof g=="number")&&(p.type="number"),f.every(g=>typeof g=="string")&&(p.type="string"),f.every(g=>typeof g=="boolean")&&(p.type="string"),f.every(g=>g===null)&&(p.type="null"),p.enum=f;break}case"file":{let p=m,f={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:v}=t._zod.bag;g!==void 0&&(f.minLength=g),y!==void 0&&(f.maxLength=y),v?v.length===1?(f.contentMediaType=v[0],Object.assign(p,f)):p.anyOf=v.map(b=>({...f,contentMediaType:b})):Object.assign(p,f);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(i.innerType,d);m.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(i.innerType,d),a.ref=i.innerType;break}case"success":{let p=m;p.type="boolean";break}case"default":{this.process(i.innerType,d),a.ref=i.innerType,m.default=JSON.parse(JSON.stringify(i.defaultValue));break}case"prefault":{this.process(i.innerType,d),a.ref=i.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(i.defaultValue)));break}case"catch":{this.process(i.innerType,d),a.ref=i.innerType;let p;try{p=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=m,f=t._zod.pattern;if(!f)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=f.source;break}case"pipe":{let p=this.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;this.process(p,d),a.ref=p;break}case"readonly":{this.process(i.innerType,d),a.ref=i.innerType,m.readOnly=!0;break}case"promise":{this.process(i.innerType,d),a.ref=i.innerType;break}case"optional":{this.process(i.innerType,d),a.ref=i.innerType;break}case"lazy":{let p=t._zod.innerType;this.process(p,d),a.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let c=this.metadataRegistry.get(t);return c&&Object.assign(a.schema,c),this.io==="input"&&rt(t)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(t).schema}emit(t,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},i=this.seen.get(t);if(!i)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let f=n.external.registry.get(l[0])?.id,g=n.external.uri??(v=>v);if(f)return{ref:g(f)};let y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===i)return{ref:"#"};let m=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:m+p}},s=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:h,defId:m}=o(l);d.def={...d.schema},m&&(d.defId=m);let p=d.schema;for(let f in p)delete p[f];p.$ref=h};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
315
346
 
316
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let d=u[1];if(t===u[0]){s(u);continue}if(n.external){let p=n.external.registry.get(u[0])?.id;if(t!==u[0]&&p){s(u);continue}}if(this.metadataRegistry.get(u[0])?.id){s(u);continue}if(d.cycle){s(u);continue}if(d.count>1&&n.reused==="ref"){s(u);continue}}let a=(u,d)=>{let h=this.seen.get(u),p=h.def??h.schema,m={...p};if(h.ref===null)return;let f=h.ref;if(h.ref=null,f){a(f,d);let g=this.seen.get(f).schema;g.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(g)):(Object.assign(p,g),Object.assign(p,m))}h.isParent||this.override({zodSchema:u,jsonSchema:p,path:h.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let u=n.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,i.def);let c=n.external?.defs??{};for(let u of this.seen.entries()){let d=u[1];d.def&&d.defId&&(c[d.defId]=d.def)}n.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}};function Zf(e,t){if(e instanceof fs){let n=new sc(t),i={};for(let a of e._idmap.entries()){let[l,c]=a;n.process(c)}let o={},s={registry:e,uri:t?.uri,defs:i};for(let a of e._idmap.entries()){let[l,c]=a;o[l]=n.emit(c,{...t,external:s})}if(Object.keys(i).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[a]:i}}return{schemas:o}}let r=new sc(t);return r.process(e),r.emit(e,t)}function Ge(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let i=e._zod.def;switch(i.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ge(i.element,r);case"object":{for(let o in i.shape)if(Ge(i.shape[o],r))return!0;return!1}case"union":{for(let o of i.options)if(Ge(o,r))return!0;return!1}case"intersection":return Ge(i.left,r)||Ge(i.right,r);case"tuple":{for(let o of i.items)if(Ge(o,r))return!0;return!!(i.rest&&Ge(i.rest,r))}case"record":return Ge(i.keyType,r)||Ge(i.valueType,r);case"map":return Ge(i.keyType,r)||Ge(i.valueType,r);case"set":return Ge(i.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ge(i.innerType,r);case"lazy":return Ge(i.getter(),r);case"default":return Ge(i.innerType,r);case"prefault":return Ge(i.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ge(i.in,r)||Ge(i.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${i.type}`)}var hs={};zl(hs,{ZodISODate:()=>pv,ZodISODateTime:()=>mv,ZodISODuration:()=>gv,ZodISOTime:()=>hv,date:()=>Lf,datetime:()=>qf,duration:()=>Uf,time:()=>Vf});var mv=k("ZodISODateTime",(e,t)=>{ev.init(e,t),Pe.init(e,t)});function qf(e){return av(mv,e)}var pv=k("ZodISODate",(e,t)=>{tv.init(e,t),Pe.init(e,t)});function Lf(e){return cv(pv,e)}var hv=k("ZodISOTime",(e,t)=>{rv.init(e,t),Pe.init(e,t)});function Vf(e){return lv(hv,e)}var gv=k("ZodISODuration",(e,t)=>{nv.init(e,t),Pe.init(e,t)});function Uf(e){return uv(gv,e)}var _v=(e,t)=>{Ja.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>ed(e,r)},flatten:{value:r=>Yu(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},qD=k("ZodError",_v),gs=k("ZodError",_v,{Parent:Error});var yv=td(gs),vv=nd(gs),bv=od(gs),wv=sd(gs);var Ne=k("ZodType",(e,t)=>(fe.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>Wt(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>yv(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>bv(e,r,n),e.parseAsync=async(r,n)=>vv(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>wv(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(UE(r,n)),e.superRefine=r=>e.check(FE(r)),e.overwrite=r=>e.check(gi(r)),e.optional=()=>Re(e),e.nullable=()=>Sv(e),e.nullish=()=>Re(Sv(e)),e.nonoptional=r=>NE(e,r),e.array=()=>re(e),e.or=r=>$e([e,r]),e.and=r=>cc(e,r),e.transform=r=>Gf(e,Ov(r)),e.default=r=>RE(e,r),e.prefault=r=>jE(e,r),e.catch=r=>DE(e,r),e.pipe=r=>Gf(e,r),e.readonly=()=>LE(e),e.describe=r=>{let n=e.clone();return $n.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return $n.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return $n.get(e);let n=e.clone();return $n.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),$v=k("_ZodString",(e,t)=>{ds.init(e,t),Ne.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(zf(...n)),e.includes=(...n)=>e.check(Of(...n)),e.startsWith=(...n)=>e.check(Pf(...n)),e.endsWith=(...n)=>e.check(Cf(...n)),e.min=(...n)=>e.check(to(...n)),e.max=(...n)=>e.check(ic(...n)),e.length=(...n)=>e.check(oc(...n)),e.nonempty=(...n)=>e.check(to(1,...n)),e.lowercase=n=>e.check(Ef(n)),e.uppercase=n=>e.check(Af(n)),e.trim=()=>e.check(If()),e.normalize=(...n)=>e.check(Rf(...n)),e.toLowerCase=()=>e.check(jf()),e.toUpperCase=()=>e.check(Nf())}),tE=k("ZodString",(e,t)=>{ds.init(e,t),$v.init(e,t),e.email=r=>e.check(Yd(rE,r)),e.url=r=>e.check(of(nE,r)),e.jwt=r=>e.check(bf(yE,r)),e.emoji=r=>e.check(sf(iE,r)),e.guid=r=>e.check(ec(xv,r)),e.uuid=r=>e.check(ef(ac,r)),e.uuidv4=r=>e.check(tf(ac,r)),e.uuidv6=r=>e.check(rf(ac,r)),e.uuidv7=r=>e.check(nf(ac,r)),e.nanoid=r=>e.check(af(oE,r)),e.guid=r=>e.check(ec(xv,r)),e.cuid=r=>e.check(cf(sE,r)),e.cuid2=r=>e.check(lf(aE,r)),e.ulid=r=>e.check(uf(cE,r)),e.base64=r=>e.check(_f(hE,r)),e.base64url=r=>e.check(yf(gE,r)),e.xid=r=>e.check(df(lE,r)),e.ksuid=r=>e.check(ff(uE,r)),e.ipv4=r=>e.check(mf(dE,r)),e.ipv6=r=>e.check(pf(fE,r)),e.cidrv4=r=>e.check(hf(mE,r)),e.cidrv6=r=>e.check(gf(pE,r)),e.e164=r=>e.check(vf(_E,r)),e.datetime=r=>e.check(qf(r)),e.date=r=>e.check(Lf(r)),e.time=r=>e.check(Vf(r)),e.duration=r=>e.check(Uf(r))});function x(e){return Xd(tE,e)}var Pe=k("ZodStringFormat",(e,t)=>{xe.init(e,t),$v.init(e,t)}),rE=k("ZodEmail",(e,t)=>{pd.init(e,t),Pe.init(e,t)});var xv=k("ZodGUID",(e,t)=>{fd.init(e,t),Pe.init(e,t)});var ac=k("ZodUUID",(e,t)=>{md.init(e,t),Pe.init(e,t)});var nE=k("ZodURL",(e,t)=>{hd.init(e,t),Pe.init(e,t)});var iE=k("ZodEmoji",(e,t)=>{gd.init(e,t),Pe.init(e,t)});var oE=k("ZodNanoID",(e,t)=>{_d.init(e,t),Pe.init(e,t)});var sE=k("ZodCUID",(e,t)=>{yd.init(e,t),Pe.init(e,t)});var aE=k("ZodCUID2",(e,t)=>{vd.init(e,t),Pe.init(e,t)});var cE=k("ZodULID",(e,t)=>{bd.init(e,t),Pe.init(e,t)});var lE=k("ZodXID",(e,t)=>{wd.init(e,t),Pe.init(e,t)});var uE=k("ZodKSUID",(e,t)=>{xd.init(e,t),Pe.init(e,t)});var dE=k("ZodIPv4",(e,t)=>{kd.init(e,t),Pe.init(e,t)});var fE=k("ZodIPv6",(e,t)=>{Sd.init(e,t),Pe.init(e,t)});var mE=k("ZodCIDRv4",(e,t)=>{$d.init(e,t),Pe.init(e,t)});var pE=k("ZodCIDRv6",(e,t)=>{Td.init(e,t),Pe.init(e,t)});var hE=k("ZodBase64",(e,t)=>{zd.init(e,t),Pe.init(e,t)});var gE=k("ZodBase64URL",(e,t)=>{Ed.init(e,t),Pe.init(e,t)});var _E=k("ZodE164",(e,t)=>{Ad.init(e,t),Pe.init(e,t)});var yE=k("ZodJWT",(e,t)=>{Od.init(e,t),Pe.init(e,t)});var Tv=k("ZodNumber",(e,t)=>{Qa.init(e,t),Ne.init(e,t),e.gt=(n,i)=>e.check(rc(n,i)),e.gte=(n,i)=>e.check(ps(n,i)),e.min=(n,i)=>e.check(ps(n,i)),e.lt=(n,i)=>e.check(tc(n,i)),e.lte=(n,i)=>e.check(ms(n,i)),e.max=(n,i)=>e.check(ms(n,i)),e.int=n=>e.check(kv(n)),e.safe=n=>e.check(kv(n)),e.positive=n=>e.check(rc(0,n)),e.nonnegative=n=>e.check(ps(0,n)),e.negative=n=>e.check(tc(0,n)),e.nonpositive=n=>e.check(ms(0,n)),e.multipleOf=(n,i)=>e.check(nc(n,i)),e.step=(n,i)=>e.check(nc(n,i)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function ue(e){return wf(Tv,e)}var vE=k("ZodNumberFormat",(e,t)=>{Pd.init(e,t),Tv.init(e,t)});function kv(e){return xf(vE,e)}var bE=k("ZodBoolean",(e,t)=>{Cd.init(e,t),Ne.init(e,t)});function Xe(e){return kf(bE,e)}var wE=k("ZodNull",(e,t)=>{Rd.init(e,t),Ne.init(e,t)});function zv(e){return Sf(wE,e)}var xE=k("ZodUnknown",(e,t)=>{Id.init(e,t),Ne.init(e,t)});function Ce(){return $f(xE)}var kE=k("ZodNever",(e,t)=>{jd.init(e,t),Ne.init(e,t)});function SE(e){return Tf(kE,e)}var $E=k("ZodArray",(e,t)=>{Nd.init(e,t),Ne.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(to(r,n)),e.nonempty=r=>e.check(to(1,r)),e.max=(r,n)=>e.check(ic(r,n)),e.length=(r,n)=>e.check(oc(r,n)),e.unwrap=()=>e.element});function re(e,t){return dv($E,e,t)}var Ev=k("ZodObject",(e,t)=>{Xa.init(e,t),Ne.init(e,t),te.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Nt(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ce()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ce()}),e.strict=()=>e.clone({...e._zod.def,catchall:SE()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>te.extend(e,r),e.merge=r=>te.merge(e,r),e.pick=r=>te.pick(e,r),e.omit=r=>te.omit(e,r),e.partial=(...r)=>te.partial(Pv,e,r[0]),e.required=(...r)=>te.required(Cv,e,r[0])});function O(e,t){let r={type:"object",get shape(){return te.assignProp(this,"shape",{...e}),this.shape},...te.normalizeParams(t)};return new Ev(r)}function Tt(e,t){return new Ev({type:"object",get shape(){return te.assignProp(this,"shape",{...e}),this.shape},catchall:Ce(),...te.normalizeParams(t)})}var Av=k("ZodUnion",(e,t)=>{Ya.init(e,t),Ne.init(e,t),e.options=t.options});function $e(e,t){return new Av({type:"union",options:e,...te.normalizeParams(t)})}var TE=k("ZodDiscriminatedUnion",(e,t)=>{Av.init(e,t),Md.init(e,t)});function Bf(e,t,r){return new TE({type:"union",options:t,discriminator:e,...te.normalizeParams(r)})}var zE=k("ZodIntersection",(e,t)=>{Dd.init(e,t),Ne.init(e,t)});function cc(e,t){return new zE({type:"intersection",left:e,right:t})}var EE=k("ZodRecord",(e,t)=>{Zd.init(e,t),Ne.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ke(e,t,r){return new EE({type:"record",keyType:e,valueType:t,...te.normalizeParams(r)})}var Ff=k("ZodEnum",(e,t)=>{qd.init(e,t),Ne.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,i)=>{let o={};for(let s of n)if(r.has(s))o[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Ff({...t,checks:[],...te.normalizeParams(i),entries:o})},e.exclude=(n,i)=>{let o={...t.entries};for(let s of n)if(r.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new Ff({...t,checks:[],...te.normalizeParams(i),entries:o})}});function Nt(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Ff({type:"enum",entries:r,...te.normalizeParams(t)})}var AE=k("ZodLiteral",(e,t)=>{Ld.init(e,t),Ne.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function I(e,t){return new AE({type:"literal",values:Array.isArray(e)?e:[e],...te.normalizeParams(t)})}var OE=k("ZodTransform",(e,t)=>{Vd.init(e,t),Ne.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(te.issue(o,r.value,t));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(te.issue(s))}};let i=t.transform(r.value,r);return i instanceof Promise?i.then(o=>(r.value=o,r)):(r.value=i,r)}});function Ov(e){return new OE({type:"transform",transform:e})}var Pv=k("ZodOptional",(e,t)=>{Ud.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Re(e){return new Pv({type:"optional",innerType:e})}var PE=k("ZodNullable",(e,t)=>{Fd.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Sv(e){return new PE({type:"nullable",innerType:e})}var CE=k("ZodDefault",(e,t)=>{Gd.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function RE(e,t){return new CE({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var IE=k("ZodPrefault",(e,t)=>{Bd.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function jE(e,t){return new IE({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Cv=k("ZodNonOptional",(e,t)=>{Jd.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function NE(e,t){return new Cv({type:"nonoptional",innerType:e,...te.normalizeParams(t)})}var ME=k("ZodCatch",(e,t)=>{Wd.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function DE(e,t){return new ME({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var ZE=k("ZodPipe",(e,t)=>{Hd.init(e,t),Ne.init(e,t),e.in=t.in,e.out=t.out});function Gf(e,t){return new ZE({type:"pipe",in:e,out:t})}var qE=k("ZodReadonly",(e,t)=>{Kd.init(e,t),Ne.init(e,t)});function LE(e){return new qE({type:"readonly",innerType:e})}var Rv=k("ZodCustom",(e,t)=>{Qd.init(e,t),Ne.init(e,t)});function VE(e){let t=new ot({check:"custom"});return t._zod.check=e,t}function Iv(e,t){return Mf(Rv,e??(()=>!0),t)}function UE(e,t={}){return Df(Rv,e,t)}function FE(e){let t=VE(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(te.issue(n,r.value,t._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),r.issues.push(te.issue(i))}},e(r.value,r)));return t}function Jf(e,t){return Gf(Ov(e),t)}Jt(ov());var Hf="2025-11-25";var jv=[Hf,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Tn="io.modelcontextprotocol/related-task",uc="2.0",Be=Iv(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Nv=$e([x(),ue().int()]),Mv=x(),eZ=Tt({ttl:ue().optional(),pollInterval:ue().optional()}),GE=O({ttl:ue().optional()}),BE=O({taskId:x()}),Kf=Tt({progressToken:Nv.optional(),[Tn]:BE.optional()}),Ht=O({_meta:Kf.optional()}),_s=Ht.extend({task:GE.optional()}),Dv=e=>_s.safeParse(e).success,st=O({method:x(),params:Ht.loose().optional()}),nr=O({_meta:Kf.optional()}),ir=O({method:x(),params:nr.loose().optional()}),at=Tt({_meta:Kf.optional()}),dc=$e([x(),ue().int()]),Zv=O({jsonrpc:I(uc),id:dc,...st.shape}).strict(),Qf=e=>Zv.safeParse(e).success,qv=O({jsonrpc:I(uc),...ir.shape}).strict(),Lv=e=>qv.safeParse(e).success,Xf=O({jsonrpc:I(uc),id:dc,result:at}).strict(),ys=e=>Xf.safeParse(e).success;var M;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(M||(M={}));var Yf=O({jsonrpc:I(uc),id:dc.optional(),error:O({code:ue().int(),message:x(),data:Ce().optional()})}).strict();var Vv=e=>Yf.safeParse(e).success;var Uv=$e([Zv,qv,Xf,Yf]),tZ=$e([Xf,Yf]),fc=at.strict(),JE=nr.extend({requestId:dc.optional(),reason:x().optional()}),mc=ir.extend({method:I("notifications/cancelled"),params:JE}),WE=O({src:x(),mimeType:x().optional(),sizes:re(x()).optional(),theme:Nt(["light","dark"]).optional()}),vs=O({icons:re(WE).optional()}),ro=O({name:x(),title:x().optional()}),Fv=ro.extend({...ro.shape,...vs.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),HE=cc(O({applyDefaults:Xe().optional()}),ke(x(),Ce())),KE=Jf(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,cc(O({form:HE.optional(),url:Be.optional()}),ke(x(),Ce()).optional())),QE=Tt({list:Be.optional(),cancel:Be.optional(),requests:Tt({sampling:Tt({createMessage:Be.optional()}).optional(),elicitation:Tt({create:Be.optional()}).optional()}).optional()}),XE=Tt({list:Be.optional(),cancel:Be.optional(),requests:Tt({tools:Tt({call:Be.optional()}).optional()}).optional()}),YE=O({experimental:ke(x(),Be).optional(),sampling:O({context:Be.optional(),tools:Be.optional()}).optional(),elicitation:KE.optional(),roots:O({listChanged:Xe().optional()}).optional(),tasks:QE.optional(),extensions:ke(x(),Be).optional()}),eA=Ht.extend({protocolVersion:x(),capabilities:YE,clientInfo:Fv}),em=st.extend({method:I("initialize"),params:eA});var tA=O({experimental:ke(x(),Be).optional(),logging:Be.optional(),completions:Be.optional(),prompts:O({listChanged:Xe().optional()}).optional(),resources:O({subscribe:Xe().optional(),listChanged:Xe().optional()}).optional(),tools:O({listChanged:Xe().optional()}).optional(),tasks:XE.optional(),extensions:ke(x(),Be).optional()}),rA=at.extend({protocolVersion:x(),capabilities:tA,serverInfo:Fv,instructions:x().optional()}),tm=ir.extend({method:I("notifications/initialized"),params:nr.optional()});var pc=st.extend({method:I("ping"),params:Ht.optional()}),nA=O({progress:ue(),total:Re(ue()),message:Re(x())}),iA=O({...nr.shape,...nA.shape,progressToken:Nv}),hc=ir.extend({method:I("notifications/progress"),params:iA}),oA=Ht.extend({cursor:Mv.optional()}),bs=st.extend({params:oA.optional()}),ws=at.extend({nextCursor:Mv.optional()}),sA=Nt(["working","input_required","completed","failed","cancelled"]),xs=O({taskId:x(),status:sA,ttl:$e([ue(),zv()]),createdAt:x(),lastUpdatedAt:x(),pollInterval:Re(ue()),statusMessage:Re(x())}),no=at.extend({task:xs}),aA=nr.merge(xs),ks=ir.extend({method:I("notifications/tasks/status"),params:aA}),gc=st.extend({method:I("tasks/get"),params:Ht.extend({taskId:x()})}),_c=at.merge(xs),yc=st.extend({method:I("tasks/result"),params:Ht.extend({taskId:x()})}),rZ=at.loose(),vc=bs.extend({method:I("tasks/list")}),bc=ws.extend({tasks:re(xs)}),wc=st.extend({method:I("tasks/cancel"),params:Ht.extend({taskId:x()})}),Gv=at.merge(xs),Bv=O({uri:x(),mimeType:Re(x()),_meta:ke(x(),Ce()).optional()}),Jv=Bv.extend({text:x()}),rm=x().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Wv=Bv.extend({blob:rm}),Ss=Nt(["user","assistant"]),io=O({audience:re(Ss).optional(),priority:ue().min(0).max(1).optional(),lastModified:hs.datetime({offset:!0}).optional()}),Hv=O({...ro.shape,...vs.shape,uri:x(),description:Re(x()),mimeType:Re(x()),size:Re(ue()),annotations:io.optional(),_meta:Re(Tt({}))}),cA=O({...ro.shape,...vs.shape,uriTemplate:x(),description:Re(x()),mimeType:Re(x()),annotations:io.optional(),_meta:Re(Tt({}))}),oo=bs.extend({method:I("resources/list")}),lA=ws.extend({resources:re(Hv)}),so=bs.extend({method:I("resources/templates/list")}),uA=ws.extend({resourceTemplates:re(cA)}),nm=Ht.extend({uri:x()}),dA=nm,xc=st.extend({method:I("resources/read"),params:dA}),fA=at.extend({contents:re($e([Jv,Wv]))}),mA=ir.extend({method:I("notifications/resources/list_changed"),params:nr.optional()}),pA=nm,hA=st.extend({method:I("resources/subscribe"),params:pA}),gA=nm,_A=st.extend({method:I("resources/unsubscribe"),params:gA}),yA=nr.extend({uri:x()}),vA=ir.extend({method:I("notifications/resources/updated"),params:yA}),bA=O({name:x(),description:Re(x()),required:Re(Xe())}),wA=O({...ro.shape,...vs.shape,description:Re(x()),arguments:Re(re(bA)),_meta:Re(Tt({}))}),kc=bs.extend({method:I("prompts/list")}),xA=ws.extend({prompts:re(wA)}),kA=Ht.extend({name:x(),arguments:ke(x(),x()).optional()}),Sc=st.extend({method:I("prompts/get"),params:kA}),im=O({type:I("text"),text:x(),annotations:io.optional(),_meta:ke(x(),Ce()).optional()}),om=O({type:I("image"),data:rm,mimeType:x(),annotations:io.optional(),_meta:ke(x(),Ce()).optional()}),sm=O({type:I("audio"),data:rm,mimeType:x(),annotations:io.optional(),_meta:ke(x(),Ce()).optional()}),SA=O({type:I("tool_use"),name:x(),id:x(),input:ke(x(),Ce()),_meta:ke(x(),Ce()).optional()}),$A=O({type:I("resource"),resource:$e([Jv,Wv]),annotations:io.optional(),_meta:ke(x(),Ce()).optional()}),TA=Hv.extend({type:I("resource_link")}),am=$e([im,om,sm,TA,$A]),zA=O({role:Ss,content:am}),EA=at.extend({description:x().optional(),messages:re(zA)}),AA=ir.extend({method:I("notifications/prompts/list_changed"),params:nr.optional()}),OA=O({title:x().optional(),readOnlyHint:Xe().optional(),destructiveHint:Xe().optional(),idempotentHint:Xe().optional(),openWorldHint:Xe().optional()}),PA=O({taskSupport:Nt(["required","optional","forbidden"]).optional()}),Kv=O({...ro.shape,...vs.shape,description:x().optional(),inputSchema:O({type:I("object"),properties:ke(x(),Be).optional(),required:re(x()).optional()}).catchall(Ce()),outputSchema:O({type:I("object"),properties:ke(x(),Be).optional(),required:re(x()).optional()}).catchall(Ce()).optional(),annotations:OA.optional(),execution:PA.optional(),_meta:ke(x(),Ce()).optional()}),$c=bs.extend({method:I("tools/list")}),CA=ws.extend({tools:re(Kv)}),Tc=at.extend({content:re(am).default([]),structuredContent:ke(x(),Ce()).optional(),isError:Xe().optional()}),nZ=Tc.or(at.extend({toolResult:Ce()})),RA=_s.extend({name:x(),arguments:ke(x(),Ce()).optional()}),ao=st.extend({method:I("tools/call"),params:RA}),IA=ir.extend({method:I("notifications/tools/list_changed"),params:nr.optional()}),iZ=O({autoRefresh:Xe().default(!0),debounceMs:ue().int().nonnegative().default(300)}),$s=Nt(["debug","info","notice","warning","error","critical","alert","emergency"]),jA=Ht.extend({level:$s}),cm=st.extend({method:I("logging/setLevel"),params:jA}),NA=nr.extend({level:$s,logger:x().optional(),data:Ce()}),MA=ir.extend({method:I("notifications/message"),params:NA}),DA=O({name:x().optional()}),ZA=O({hints:re(DA).optional(),costPriority:ue().min(0).max(1).optional(),speedPriority:ue().min(0).max(1).optional(),intelligencePriority:ue().min(0).max(1).optional()}),qA=O({mode:Nt(["auto","required","none"]).optional()}),LA=O({type:I("tool_result"),toolUseId:x().describe("The unique identifier for the corresponding tool call."),content:re(am).default([]),structuredContent:O({}).loose().optional(),isError:Xe().optional(),_meta:ke(x(),Ce()).optional()}),VA=Bf("type",[im,om,sm]),lc=Bf("type",[im,om,sm,SA,LA]),UA=O({role:Ss,content:$e([lc,re(lc)]),_meta:ke(x(),Ce()).optional()}),FA=_s.extend({messages:re(UA),modelPreferences:ZA.optional(),systemPrompt:x().optional(),includeContext:Nt(["none","thisServer","allServers"]).optional(),temperature:ue().optional(),maxTokens:ue().int(),stopSequences:re(x()).optional(),metadata:Be.optional(),tools:re(Kv).optional(),toolChoice:qA.optional()}),GA=st.extend({method:I("sampling/createMessage"),params:FA}),Ts=at.extend({model:x(),stopReason:Re(Nt(["endTurn","stopSequence","maxTokens"]).or(x())),role:Ss,content:VA}),lm=at.extend({model:x(),stopReason:Re(Nt(["endTurn","stopSequence","maxTokens","toolUse"]).or(x())),role:Ss,content:$e([lc,re(lc)])}),BA=O({type:I("boolean"),title:x().optional(),description:x().optional(),default:Xe().optional()}),JA=O({type:I("string"),title:x().optional(),description:x().optional(),minLength:ue().optional(),maxLength:ue().optional(),format:Nt(["email","uri","date","date-time"]).optional(),default:x().optional()}),WA=O({type:Nt(["number","integer"]),title:x().optional(),description:x().optional(),minimum:ue().optional(),maximum:ue().optional(),default:ue().optional()}),HA=O({type:I("string"),title:x().optional(),description:x().optional(),enum:re(x()),default:x().optional()}),KA=O({type:I("string"),title:x().optional(),description:x().optional(),oneOf:re(O({const:x(),title:x()})),default:x().optional()}),QA=O({type:I("string"),title:x().optional(),description:x().optional(),enum:re(x()),enumNames:re(x()).optional(),default:x().optional()}),XA=$e([HA,KA]),YA=O({type:I("array"),title:x().optional(),description:x().optional(),minItems:ue().optional(),maxItems:ue().optional(),items:O({type:I("string"),enum:re(x())}),default:re(x()).optional()}),eO=O({type:I("array"),title:x().optional(),description:x().optional(),minItems:ue().optional(),maxItems:ue().optional(),items:O({anyOf:re(O({const:x(),title:x()}))}),default:re(x()).optional()}),tO=$e([YA,eO]),rO=$e([QA,XA,tO]),nO=$e([rO,BA,JA,WA]),iO=_s.extend({mode:I("form").optional(),message:x(),requestedSchema:O({type:I("object"),properties:ke(x(),nO),required:re(x()).optional()})}),oO=_s.extend({mode:I("url"),message:x(),elicitationId:x(),url:x().url()}),sO=$e([iO,oO]),aO=st.extend({method:I("elicitation/create"),params:sO}),cO=nr.extend({elicitationId:x()}),lO=ir.extend({method:I("notifications/elicitation/complete"),params:cO}),co=at.extend({action:Nt(["accept","decline","cancel"]),content:Jf(e=>e===null?void 0:e,ke(x(),$e([x(),ue(),Xe(),re(x())])).optional())}),uO=O({type:I("ref/resource"),uri:x()});var dO=O({type:I("ref/prompt"),name:x()}),fO=Ht.extend({ref:$e([dO,uO]),argument:O({name:x(),value:x()}),context:O({arguments:ke(x(),x()).optional()}).optional()}),zc=st.extend({method:I("completion/complete"),params:fO});function Qv(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Xv(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var mO=at.extend({completion:Tt({values:re(x()).max(100),total:Re(ue().int()),hasMore:Re(Xe())})}),pO=O({uri:x().startsWith("file://"),name:x().optional(),_meta:ke(x(),Ce()).optional()}),hO=st.extend({method:I("roots/list"),params:Ht.optional()}),um=at.extend({roots:re(pO)}),gO=ir.extend({method:I("notifications/roots/list_changed"),params:nr.optional()}),oZ=$e([pc,em,zc,cm,Sc,kc,oo,so,xc,hA,_A,ao,$c,gc,yc,vc,wc]),sZ=$e([mc,hc,tm,gO,ks]),aZ=$e([fc,Ts,lm,co,um,_c,bc,no]),cZ=$e([pc,GA,aO,hO,gc,yc,vc,wc]),lZ=$e([mc,hc,MA,vA,mA,IA,AA,ks,lO]),uZ=$e([fc,rA,mO,EA,xA,lA,uA,fA,Tc,CA,_c,bc,no]),C=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===M.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new Wf(i.elicitations,r)}return new e(t,r,n)}},Wf=class extends C{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(M.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};var vO=k("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");fe.init(e,t),e.def=t,e.parse=(r,n)=>rd(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>pi(e,r,n),e.parseAsync=async(r,n)=>id(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>hi(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>Wt(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e))});var bO=k("ZodMiniObject",(e,t)=>{Xa.init(e,t),vO.init(e,t),te.defineLazy(e,"shape",()=>t.shape)});function dm(e,t){let r={type:"object",get shape(){return te.assignProp(this,"shape",{...e}),this.shape},...te.normalizeParams(t)};return new bO(r)}function or(e){return!!e._zod}function yi(e){let t=Object.values(e);if(t.length===0)return dm({});let r=t.every(or),n=t.every(i=>!or(i));if(r)return dm(e);if(n)return gu(e);throw new Error("Mixed Zod versions detected in object shape.")}function zn(e,t){return or(e)?pi(e,t):e.safeParse(t)}async function Ec(e,t){return or(e)?await hi(e,t):await e.safeParseAsync(t)}function En(e){if(!e)return;let t;if(or(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function lo(e){if(e){if(typeof e=="object"){let t=e,r=e;if(!t._def&&!r._zod){let n=Object.values(e);if(n.length>0&&n.every(i=>typeof i=="object"&&i!==null&&(i._def!==void 0||i._zod!==void 0||typeof i.parse=="function")))return yi(e)}}if(or(e)){let r=e._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Ac(e){if(e&&typeof e=="object"){if("message"in e&&typeof e.message=="string")return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t=="object"&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function Yv(e){return e.description}function eb(e){if(or(e))return e._zod?.def?.type==="optional";let t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function Oc(e){if(or(e)){let o=e._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}function An(e){return e==="completed"||e==="failed"||e==="cancelled"}var rb=Symbol("Let zodToJsonSchema decide on which parser to use");var tb={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},nb=e=>typeof e=="string"?{...tb,name:e}:{...tb,...e};var ib=e=>{let t=nb(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function fm(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function ne(e,t,r,n,i){e[t]=r,fm(e,t,n,i)}var Pc=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function Ie(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Pc(t,e.currentPath):t.join("/")}}function ob(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==T.ZodAny&&(r.items=V(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&ne(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&ne(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(ne(r,"minItems",e.exactLength.value,e.exactLength.message,t),ne(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function sb(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?ne(r,"minimum",n.value,n.message,t):ne(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ne(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?ne(r,"maximum",n.value,n.message,t):ne(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ne(r,"maximum",n.value,n.message,t));break;case"multipleOf":ne(r,"multipleOf",n.value,n.message,t);break}return r}function ab(){return{type:"boolean"}}function Cc(e,t){return V(e.type._def,t)}var cb=(e,t)=>V(e.innerType._def,t);function mm(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,o)=>mm(e,t,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return xO(e,t)}}var xO=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":ne(r,"minimum",n.value,n.message,t);break;case"max":ne(r,"maximum",n.value,n.message,t);break}return r};function lb(e,t){return{...V(e.innerType._def,t),default:e.defaultValue()}}function ub(e,t){return t.effectStrategy==="input"?V(e.schema._def,t):Ie(t)}function db(e){return{type:"string",enum:Array.from(e.values)}}var kO=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function fb(e,t){let r=[V(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),V(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(o=>{if(kO(o))i.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...l}=o;s=l}else n=void 0;i.push(s)}}),i.length?{allOf:i,...n}:void 0}function mb(e,t){let r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var pm,gr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(pm===void 0&&(pm=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),pm),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Rc(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":ne(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":ne(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":_r(r,"email",n.message,t);break;case"format:idn-email":_r(r,"idn-email",n.message,t);break;case"pattern:zod":zt(r,gr.email,n.message,t);break}break;case"url":_r(r,"uri",n.message,t);break;case"uuid":_r(r,"uuid",n.message,t);break;case"regex":zt(r,n.regex,n.message,t);break;case"cuid":zt(r,gr.cuid,n.message,t);break;case"cuid2":zt(r,gr.cuid2,n.message,t);break;case"startsWith":zt(r,RegExp(`^${hm(n.value,t)}`),n.message,t);break;case"endsWith":zt(r,RegExp(`${hm(n.value,t)}$`),n.message,t);break;case"datetime":_r(r,"date-time",n.message,t);break;case"date":_r(r,"date",n.message,t);break;case"time":_r(r,"time",n.message,t);break;case"duration":_r(r,"duration",n.message,t);break;case"length":ne(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),ne(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{zt(r,RegExp(hm(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&_r(r,"ipv4",n.message,t),n.version!=="v4"&&_r(r,"ipv6",n.message,t);break}case"base64url":zt(r,gr.base64url,n.message,t);break;case"jwt":zt(r,gr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&zt(r,gr.ipv4Cidr,n.message,t),n.version!=="v4"&&zt(r,gr.ipv6Cidr,n.message,t);break}case"emoji":zt(r,gr.emoji(),n.message,t);break;case"ulid":{zt(r,gr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{_r(r,"binary",n.message,t);break}case"contentEncoding:base64":{ne(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{zt(r,gr.base64,n.message,t);break}}break}case"nanoid":zt(r,gr.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function hm(e,t){return t.patternStrategy==="escape"?$O(e):e}var SO=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function $O(e){let t="";for(let r=0;r<e.length;r++)SO.has(e[r])||(t+="\\"),t+=e[r];return t}function _r(e,t,r,n){e.format||e.anyOf?.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ne(e,"format",t,r,n)}function zt(e,t,r,n){e.pattern||e.allOf?.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:pb(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ne(e,"pattern",pb(t,n),r,n)}function pb(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source,i="",o=!1,s=!1,a=!1;for(let l=0;l<n.length;l++){if(o){i+=n[l],o=!1;continue}if(r.i){if(s){if(n[l].match(/[a-z]/)){a?(i+=n[l],i+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(i+=n[l],a=!0):i+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){i+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){i+=`(^|(?<=[\r
317
- ]))`;continue}else if(n[l]==="$"){i+=`($|(?=[\r
318
- ]))`;continue}}if(r.s&&n[l]==="."){i+=s?`${n[l]}\r
319
- `:`[${n[l]}\r
320
- ]`;continue}i+=n[l],n[l]==="\\"?o=!0:s&&n[l]==="]"?s=!1:!s&&n[l]==="["&&(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Ic(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===T.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,i)=>({...n,[i]:V(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",i]})??Ie(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:V(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===T.ZodString&&e.keyType._def.checks?.length){let{type:n,...i}=Rc(e.keyType._def,t);return{...r,propertyNames:i}}else{if(e.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===T.ZodBranded&&e.keyType._def.type._def.typeName===T.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...i}=Cc(e.keyType._def,t);return{...r,propertyNames:i}}}return r}function hb(e,t){if(t.mapStrategy==="record")return Ic(e,t);let r=V(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ie(t),n=V(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ie(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function gb(e){let t=e.values,n=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),i=Array.from(new Set(n.map(o=>typeof o)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function _b(e){return e.target==="openAi"?void 0:{not:Ie({...e,currentPath:[...e.currentPath,"not"]})}}function yb(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var zs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function bb(e,t){if(t.target==="openApi3")return vb(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in zs&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,o)=>{let s=zs[o._def.typeName];return s&&!i.includes(s)?[...i,s]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((i,o)=>{let s=typeof o._def.value;switch(s){case"string":case"number":case"boolean":return[...i,s];case"bigint":return[...i,"integer"];case"object":if(o._def.value===null)return[...i,"null"];default:return i}},[]);if(n.length===r.length){let i=n.filter((o,s,a)=>a.indexOf(o)===s);return{type:i.length>1?i:i[0],enum:r.reduce((o,s)=>o.includes(s._def.value)?o:[...o,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(o=>!n.includes(o))],[])};return vb(e,t)}var vb=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,i)=>V(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function wb(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:zs[e.innerType._def.typeName],nullable:!0}:{type:[zs[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=V(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=V(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function xb(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",fm(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?ne(r,"minimum",n.value,n.message,t):ne(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ne(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?ne(r,"maximum",n.value,n.message,t):ne(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ne(r,"maximum",n.value,n.message,t));break;case"multipleOf":ne(r,"multipleOf",n.value,n.message,t);break}return r}function kb(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},i=[],o=e.shape();for(let a in o){let l=o[a];if(l===void 0||l._def===void 0)continue;let c=zO(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);let u=V(l._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,c||i.push(a))}i.length&&(n.required=i);let s=TO(e,t);return s!==void 0&&(n.additionalProperties=s),n}function TO(e,t){if(e.catchall._def.typeName!=="ZodNever")return V(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function zO(e){try{return e.isOptional()}catch{return!0}}var Sb=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return V(e.innerType._def,t);let r=V(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ie(t)},r]}:Ie(t)};var $b=(e,t)=>{if(t.pipeStrategy==="input")return V(e.in._def,t);if(t.pipeStrategy==="output")return V(e.out._def,t);let r=V(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=V(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function Tb(e,t){return V(e.type._def,t)}function zb(e,t){let n={type:"array",uniqueItems:!0,items:V(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ne(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ne(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function Eb(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>V(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:V(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>V(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Ab(e){return{not:Ie(e)}}function Ob(e){return Ie(e)}var Pb=(e,t)=>V(e.innerType._def,t);var Cb=(e,t,r)=>{switch(t){case T.ZodString:return Rc(e,r);case T.ZodNumber:return xb(e,r);case T.ZodObject:return kb(e,r);case T.ZodBigInt:return sb(e,r);case T.ZodBoolean:return ab();case T.ZodDate:return mm(e,r);case T.ZodUndefined:return Ab(r);case T.ZodNull:return yb(r);case T.ZodArray:return ob(e,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return bb(e,r);case T.ZodIntersection:return fb(e,r);case T.ZodTuple:return Eb(e,r);case T.ZodRecord:return Ic(e,r);case T.ZodLiteral:return mb(e,r);case T.ZodEnum:return db(e);case T.ZodNativeEnum:return gb(e);case T.ZodNullable:return wb(e,r);case T.ZodOptional:return Sb(e,r);case T.ZodMap:return hb(e,r);case T.ZodSet:return zb(e,r);case T.ZodLazy:return()=>e.getter()._def;case T.ZodPromise:return Tb(e,r);case T.ZodNaN:case T.ZodNever:return _b(r);case T.ZodEffects:return ub(e,r);case T.ZodAny:return Ie(r);case T.ZodUnknown:return Ob(r);case T.ZodDefault:return lb(e,r);case T.ZodBranded:return Cc(e,r);case T.ZodReadonly:return Pb(e,r);case T.ZodCatch:return cb(e,r);case T.ZodPipeline:return $b(e,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(n=>{})(t)}};function V(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==rb)return a}if(n&&!r){let a=EO(n,t);if(a!==void 0)return a}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let o=Cb(e,e.typeName,t),s=typeof o=="function"?V(o(),t):o;if(s&&AO(e,t,s),t.postProcess){let a=t.postProcess(s,e,t);return i.jsonSchema=s,a}return i.jsonSchema=s,s}var EO=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Pc(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ie(t)):t.$refStrategy==="seen"?Ie(t):void 0}},AO=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var gm=(e,t)=>{let r=ib(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[c,u])=>({...l,[c]:V(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Ie(r)}),{}):void 0,i=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=V(e._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??Ie(r),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(o.title=s),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=i===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function OO(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function _m(e,t){return or(e)?Zf(e,{target:OO(t?.target),io:t?.pipeStrategy??"input"}):gm(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function ym(e){let r=En(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Oc(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function vm(e,t){let r=zn(e,t);if(!r.success)throw r.error;return r.data}var PO=6e4,jc=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(mc,r=>{this._oncancel(r)}),this.setNotificationHandler(hc,r=>{this._onprogress(r)}),this.setRequestHandler(pc,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(gc,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new C(M.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(yc,async(r,n)=>{let i=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let l=a.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),a.type==="response")u(l);else{let d=l,h=new C(d.error.code,d.error.message,d.error.data);u(h)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(o,n.sessionId);if(!s)throw new C(M.InvalidParams,`Task not found: ${o}`);if(!An(s.status))return await this._waitForTaskUpdate(o,n.signal),await i();if(An(s.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Tn]:{taskId:o}}}}return await i()};return await i()}),this.setRequestHandler(vc,async(r,n)=>{try{let{tasks:i,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:o,_meta:{}}}catch(i){throw new C(M.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(wc,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new C(M.InvalidParams,`Task not found: ${r.params.taskId}`);if(An(i.status))throw new C(M.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(M.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(i){throw i instanceof C?i:new C(M.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,i,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),C.fromError(M.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let i=this._transport?.onmessage;this._transport.onmessage=(o,s)=>{i?.(o,s),ys(o)||Vv(o)?this._onresponse(o):Qf(o)?this._onrequest(o,s):Lv(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=C.fromError(M.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,i=this._transport,o=t.params?._meta?.[Tn]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:M.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},i?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):i?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=Dv(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,i?.sessionId):void 0,c={signal:s.signal,sessionId:i?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};o&&(d.relatedTask={taskId:o}),await this.notification(u,d)},sendRequest:async(u,d,h)=>{if(s.signal.aborted)throw new C(M.ConnectionClosed,"Request was cancelled");let p={...h,relatedRequestId:t.id};o&&!p.relatedTask&&(p.relatedTask={taskId:o});let m=p.relatedTask?.taskId??o;return m&&l&&await l.updateTaskStatus(m,"input_required"),await this.request(u,d,p)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:o,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)},async u=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:M.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,i=Number(r),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(i),a=this._timeoutInfo.get(i);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(l){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),s(l);return}o(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ys(t))n(t);else{let s=new C(t.error.code,t.error.message,t.error.data);n(s)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(ys(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),ys(t))i(t);else{let s=C.fromError(t.error.code,t.error.message,t.error.data);i(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof C?s:new C(M.InternalError,String(s))}}return}let o;try{let s=await this.request(t,no,n);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new C(M.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},An(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new C(M.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new C(M.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof C?s:new C(M.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s,task:a,relatedTask:l}=n??{};return new Promise((c,u)=>{let d=v=>{u(v)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(v){d(v);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),a&&(p.params={...p.params,task:a}),l&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Tn]:l}});let m=v=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(v)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(w=>this._onerror(new Error(`Failed to send cancellation: ${w}`)));let b=v instanceof C?v:new C(M.RequestTimeout,String(v));u(b)};this._responseHandlers.set(h,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return u(v);try{let b=zn(r,v.result);b.success?c(b.data):u(b.error)}catch(b){u(b)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let f=n?.timeout??PO,g=()=>m(C.fromError(M.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(h,f,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=l?.taskId;if(y){let v=b=>{let w=this._responseHandlers.get(h);w?w(b):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,v),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(h),u(b)})}else this._transport.send(p,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(v=>{this._cleanupTimeout(h),u(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},_c,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},bc,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Gv,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Tn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Tn]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Tn]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=ym(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,o)=>{let s=vm(t,i);return Promise.resolve(r(s,o))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=ym(t);this._notificationHandlers.set(n,i=>{let o=vm(t,i);return Promise.resolve(r(o))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,i)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let i of n)if(i.type==="request"&&Qf(i.message)){let o=i.message.id,s=this._requestResolvers.get(o);s?(s(new C(M.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(t);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,o)=>{if(r.aborted){o(new C(M.InvalidRequest,"Request cancelled"));return}let s=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(s),o(new C(M.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!t)throw new Error("No request provided");return await n.createTask(i,t.id,{method:t.method,params:t.params},r)},getTask:async i=>{let o=await n.getTask(i,r);if(!o)throw new C(M.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(i,o,s)=>{await n.storeTaskResult(i,o,s,r);let a=await n.getTask(i,r);if(a){let l=ks.parse({method:"notifications/tasks/status",params:a});await this.notification(l),An(a.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,o,s)=>{let a=await n.getTask(i,r);if(!a)throw new C(M.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(An(a.status))throw new C(M.InvalidParams,`Cannot update task "${i}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,o,s,r);let l=await n.getTask(i,r);if(l){let c=ks.parse({method:"notifications/tasks/status",params:l});await this.notification(c),An(l.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function Rb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ib(e,t){let r={...e};for(let n in t){let i=n,o=t[i];if(o===void 0)continue;let s=r[i];Rb(s)&&Rb(o)?r[i]={...s,...o}:r[i]=o}return r}var bx=vh(ih(),1),wx=vh(vx(),1);function wj(){let e=new bx.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,wx.default)(e),e}var yl=class{constructor(t){this._ajv=t??wj()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var vl=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let i=t.messages[t.messages.length-1],o=Array.isArray(i.content)?i.content:[i.content],s=o.some(u=>u.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],c=l.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(l.filter(h=>h.type==="tool_use").map(h=>h.id)),d=new Set(o.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(u.size!==d.size||![...u].every(h=>d.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},Ts,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),i=t.mode??"form";switch(i){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=i==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:o},co,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function xx(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function kx(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var bl=class extends jc{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map($s.options.map((n,i)=>[n,i])),this.isMessageIgnored=(n,i)=>{let o=this._loggingLevels.get(i);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new yl,this.setRequestHandler(em,n=>this._oninitialize(n)),this.setNotificationHandler(tm,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(cm,async(n,i)=>{let o=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=$s.safeParse(s);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new vl(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ib(this._capabilities,t)}setRequestHandler(t,r){let i=En(t)?.method;if(!i)throw new Error("Schema is missing a method literal");let o;if(or(i)){let a=i;o=a._zod?.def?.value??a.value}else{let a=i;o=a._def?.value??a.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(l,c)=>{let u=zn(ao,l);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new C(M.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=u.data,h=await Promise.resolve(r(l,c));if(d.task){let m=zn(no,h);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new C(M.InvalidParams,`Invalid task creation result: ${f}`)}return m.data}let p=zn(Tc,h);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new C(M.InvalidParams,`Invalid tools/call result: ${m}`)}return p.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){kx(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&xx(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:jv.includes(r)?r:Hf,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},fc)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],i=Array.isArray(n.content)?n.content:[n.content],o=i.some(c=>c.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],l=a.some(c=>c.type==="tool_use");if(o){if(i.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let c=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(i.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(c.size!==u.size||![...c].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},lm,r):this.request({method:"sampling/createMessage",params:t},Ts,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let i=t;return this.request({method:"elicitation/create",params:i},co,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let i=t.mode==="form"?t:{...t,mode:"form"},o=await this.request({method:"elicitation/create",params:i},co,r);if(o.action==="accept"&&o.content&&i.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(i.requestedSchema)(o.content);if(!a.valid)throw new C(M.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof C?s:new C(M.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return o}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},um,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var $x=Symbol.for("mcp.completable");function fh(e){return!!e&&typeof e=="object"&&$x in e}function Tx(e){return e[$x]?.complete}var Sx;(function(e){e.Completable="McpCompletable"})(Sx||(Sx={}));var xj=/^[A-Za-z0-9._-]{1,128}$/;function kj(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!xj.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,i,o)=>o.indexOf(n)===i);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Sj(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function mh(e){let t=kj(e);return Sj(e,t.warnings),t.isValid}var wl=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let i={taskSupport:"required",...r.execution};if(i.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,i,r._meta,n)}};var xl=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new bl(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new wl(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Dn($c)),this.server.assertCanSetRequestHandler(Dn(ao)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler($c,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let i=lo(r.inputSchema);return i?_m(i,{strictUnions:!0,pipeStrategy:"input"}):$j})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let i=lo(r.outputSchema);i&&(n.outputSchema=_m(i,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(ao,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new C(M.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new C(M.InvalidParams,`Tool ${t.params.name} disabled`);let i=!!t.params.task,o=n.execution?.taskSupport,s="createTask"in n.handler;if((o==="required"||o==="optional")&&!s)throw new C(M.InternalError,`Tool ${t.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!i)throw new C(M.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!i&&s)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),l=await this.executeToolHandler(n,a,r);return i||await this.validateToolOutput(n,l,t.params.name),l}catch(n){if(n instanceof C&&n.code===M.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;let o=lo(t.inputSchema)??t.inputSchema,s=await Ec(o,r);if(!s.success){let a="error"in s?s.error:"Unknown error",l=Ac(a);throw new C(M.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new C(M.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let i=lo(t.outputSchema),o=await Ec(i,r.structuredContent);if(!o.success){let s="error"in o?o.error:"Unknown error",a=Ac(s);throw new C(M.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let i=t.handler;if("createTask"in i){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(t.inputSchema){let a=i;return await Promise.resolve(a.createTask(r,s))}else{let a=i;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=i;return await Promise.resolve(s(r,n))}else{let s=i;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let i=await this.validateToolInput(t,r.params.arguments,r.params.name),o=t.handler,s={...n,taskStore:n.taskStore},a=i?await Promise.resolve(o.createTask(i,s)):await Promise.resolve(o.createTask(s)),l=a.task.taskId,c=a.task,u=c.pollInterval??5e3;for(;c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled";){await new Promise(h=>setTimeout(h,u));let d=await n.taskStore.getTask(l);if(!d)throw new C(M.InternalError,`Task ${l} not found during polling`);c=d}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Dn(zc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(zc,async t=>{switch(t.params.ref.type){case"ref/prompt":return Qv(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return Xv(t),this.handleResourceCompletion(t,t.params.ref);default:throw new C(M.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new C(M.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new C(M.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return na;let o=En(n.argsSchema)?.[t.params.argument.name];if(!fh(o))return na;let s=Tx(o);if(!s)return na;let a=await s(t.params.argument.value,t.params.context);return Ex(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return na;throw new C(M.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let i=n.resourceTemplate.completeCallback(t.params.argument.name);if(!i)return na;let o=await i(t.params.argument.value,t.params.context);return Ex(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Dn(oo)),this.server.assertCanSetRequestHandler(Dn(so)),this.server.assertCanSetRequestHandler(Dn(xc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(oo,async(t,r)=>{let n=Object.entries(this._registeredResources).filter(([o,s])=>s.enabled).map(([o,s])=>({uri:o,name:s.name,...s.metadata})),i=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let s=await o.resourceTemplate.listCallback(r);for(let a of s.resources)i.push({...o.metadata,...a})}return{resources:[...n,...i]}}),this.server.setRequestHandler(so,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(xc,async(t,r)=>{let n=new URL(t.params.uri),i=this._registeredResources[n.toString()];if(i){if(!i.enabled)throw new C(M.InvalidParams,`Resource ${n} disabled`);return i.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let s=o.resourceTemplate.uriTemplate.match(n.toString());if(s)return o.readCallback(n,s,r)}throw new C(M.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Dn(kc)),this.server.assertCanSetRequestHandler(Dn(Sc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(kc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?Tj(r.argsSchema):void 0}))})),this.server.setRequestHandler(Sc,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new C(M.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new C(M.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let i=lo(n.argsSchema),o=await Ec(i,t.params.arguments);if(!o.success){let l="error"in o?o.error:"Unknown error",c=Ac(l);throw new C(M.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${c}`)}let s=o.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let i=n.callback;return await Promise.resolve(i(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let i;typeof n[0]=="object"&&(i=n.shift());let o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,void 0,r,i,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,i,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,i){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(t,n.title,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let o=this._createRegisteredResourceTemplate(t,n.title,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(t,r,n,i,o){let s={name:t,title:r,metadata:i,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(t,r,n,i,o){let s={resourceTemplate:n,title:r,metadata:i,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==t&&(delete this._registeredResourceTemplates[t],c.name&&(this._registeredResourceTemplates[c.name]=s)),typeof c.title<"u"&&(s.title=c.title),typeof c.template<"u"&&(s.resourceTemplate=c.template),typeof c.metadata<"u"&&(s.metadata=c.metadata),typeof c.callback<"u"&&(s.readCallback=c.callback),typeof c.enabled<"u"&&(s.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(c=>!!n.completeCallback(c))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,i,o){let s={title:r,description:n,argsSchema:i===void 0?void 0:yi(i),callback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=yi(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,i&&Object.values(i).some(l=>{let c=l instanceof Ct?l._def?.innerType:l;return fh(c)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,i,o,s,a,l,c){mh(t);let u={title:r,description:n,inputSchema:zx(i),outputSchema:zx(o),annotations:s,execution:a,_meta:l,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&mh(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=yi(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=yi(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,i,o,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];if(ph(l))i=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!ph(r[0])&&(s=r.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(c=>typeof c=="object"&&c!==null))throw new Error(`Tool ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,i,o,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:i,description:o,inputSchema:s,outputSchema:a,annotations:l,_meta:c}=r;return this._createRegisteredTool(t,i,o,s,a,l,{taskSupport:"forbidden"},c,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let i;r.length>1&&(i=r.shift());let o=r[0],s=this._createRegisteredPrompt(t,void 0,n,i,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:i,description:o,argsSchema:s}=r,a=this._createRegisteredPrompt(t,i,o,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var $j={type:"object",properties:{}};function Ax(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function Ox(e){return"_def"in e||"_zod"in e||Ax(e)}function ph(e){return typeof e!="object"||e===null||Ox(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Ax)}function zx(e){if(e){if(ph(e))return yi(e);if(!Ox(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function Tj(e){let t=En(e);return t?Object.entries(t).map(([r,n])=>{let i=Yv(n),o=eb(n);return{name:r,description:i,required:!o}}):[]}function Dn(e){let r=En(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Oc(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Ex(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var na={completion:{values:[],hasMore:!1}};import Cx from"node:process";var kl=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
321
- `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),Ej(r)}clear(){this._buffer=void 0}};function Ej(e){return Uv.parse(JSON.parse(e))}function Px(e){return JSON.stringify(e)+`
322
- `}var Sl=class{constructor(t=Cx.stdin,r=Cx.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new kl,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=Px(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function Oj(e){let t={};t.listChanged=!1;let r={};r.resources=t,e.server.registerCapabilities(r),e.server.setRequestHandler(oo,()=>{let n={};return n.resources=[],n}),e.server.setRequestHandler(so,()=>{let n={};return n.resourceTemplates=[],n})}function Pj(e){return{registerTool:(t,r,n,i)=>{e.tool(t,r,n,i)}}}function Cj(e){return(t,r)=>e.server.elicitInput(t,{timeout:r})}async function hh(e){let t=e.delegationAuthFilePath;if(t!==void 0){let n=e.explicitToken,i=e.authFilePath;if(n!==void 0)return{TAG:"Error",_0:"--delegation-auth-file cannot be combined with --token or --auth-file"};if(i!==void 0)return{TAG:"Error",_0:"--delegation-auth-file cannot be combined with --token or --auth-file"};let o=Eg(t,Date.now());return o.TAG==="Ok"?{TAG:"Ok",_0:{accessToken:o._0.accessToken,mode:"PersonalAgentDelegation"}}:{TAG:"Error",_0:o._0.summary}}let r=await Xg(e.serviceUrl,e.explicitToken,e.authFilePath,e.workspaceSlug,e.channelSlug,void 0);return r.TAG==="Ok"?{TAG:"Ok",_0:{accessToken:r._0,mode:"LocalRunner"}}:{TAG:"Error",_0:r._0.summary}}function gh(e,t){let r=Me(e,"token");return{serviceUrl:t,explicitToken:r!==void 0?r:process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:Me(e,"auth-file"),delegationAuthFilePath:Me(e,"delegation-auth-file"),workspaceSlug:Me(e,"workspace"),channelSlug:Me(e,"channel")}}async function Rj(e){let t=ua(e);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};let r=t._0;if(Ri(r,"help"))return Ln(ma()),{TAG:"Ok",_0:void 0};let n=da(r,"api-url");if(n.TAG!=="Ok")return{TAG:"Error",_0:n._0};let i=n._0,o=await hh(gh(r,i));if(o.TAG!=="Ok")return{TAG:"Error",_0:o._0};let s=o._0,a=fa(Me(r,"mode")),l=Pl(Me(r,"tool-scope"));if(a.TAG!=="Ok")return{TAG:"Error",_0:a._0};let c=a._0;if(l.TAG!=="Ok")return{TAG:"Error",_0:l._0};let u=Me(r,"owner-username"),d=u!==void 0?u:process.env.LINZUMI_MCP_OWNER_USERNAME,h=Me(r,"cwd"),p=h!==void 0?h:process.cwd(),m=Me(r,"thread-id"),f=m!==void 0?m:process.env[m_],g=Vu({serviceUrl:i,accessToken:s.accessToken,authMode:s.mode,operatingMode:c});if(g.TAG!=="Ok")return{TAG:"Error",_0:g._0};let y=new xl({name:"linzumi",version:"0.1.0"});return Oj(y),H_(Pj(y),{client:g._0,toolScope:l._0,operatingMode:c,cwd:p,serviceUrl:i,defaultThreadId:f,ownerUsername:d,agentSession:Ri(r,"agent-session"),documentSurfaces:K_(s.accessToken),multiAgentJobs:Ri(r,"multi-agent-jobs"),devServices:j_(process.env),askUserQuestion:Ri(r,"ask-user-question-tool")?Cj(y):void 0}),await y.connect(new Sl),{TAG:"Ok",_0:void 0}}async function Ij(e){let t=ua(e);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};let r=t._0,n=da(r,"api-url");if(n.TAG!=="Ok")return{TAG:"Error",_0:n._0};let i=n._0,o=Me(r,"format"),s=o!==void 0?o:"codex",a=fa(Me(r,"mode"));if(a.TAG!=="Ok")return{TAG:"Error",_0:a._0};let l;if(Ri(r,"include-token")){let h=await hh(gh(r,i));l=h.TAG==="Ok"?{TAG:"Ok",_0:h._0.accessToken}:{TAG:"Error",_0:h._0}}else l={TAG:"Ok",_0:void 0};if(l.TAG!=="Ok")return{TAG:"Error",_0:l._0};let c=Pl(Me(r,"tool-scope"));if(c.TAG!=="Ok")return{TAG:"Error",_0:c._0};let u=Me(r,"owner-username"),d=D_({command:Me(r,"command"),serviceUrl:i,accessToken:l._0,delegationAuthFilePath:Me(r,"delegation-auth-file"),ownerUsername:u!==void 0?u:process.env.LINZUMI_MCP_OWNER_USERNAME,operatingMode:a._0,toolScope:c._0});switch(s){case"claude-code":return Ln(Z_(d)),{TAG:"Ok",_0:void 0};case"codex":return Ln(q_(d)),{TAG:"Ok",_0:void 0};default:return{TAG:"Error",_0:"--format must be codex or claude-code"}}}async function jj(e){let t=ua(e);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};let r=t._0,n=da(r,"api-url");if(n.TAG!=="Ok")return{TAG:"Error",_0:n._0};let i=n._0,o=await hh(gh(r,i));if(o.TAG!=="Ok")return{TAG:"Error",_0:o._0};let s=o._0,a=s.mode,l;if(a==="LocalRunner"){let c=await Vi(i,s.accessToken,Me(r,"workspace"),Me(r,"channel"),void 0);if(c.TAG==="Ok")switch(c._0){case"Usable":l={TAG:"Ok",_0:void 0};break;case"Rejected":case"NotFound":l={TAG:"Error",_0:"Linzumi MCP auth validation failed"};break}else l={TAG:"Error",_0:c._0.summary}}else{let c=fa(Me(r,"mode"));if(c.TAG==="Ok"){let u=Vu({serviceUrl:i,accessToken:s.accessToken,authMode:s.mode,operatingMode:c._0});if(u.TAG==="Ok")try{await u._0.validateAuth(),l={TAG:"Ok",_0:void 0}}catch(d){let h=ee(d);l={TAG:"Error",_0:fn(h)}}else l={TAG:"Error",_0:u._0}}else l={TAG:"Error",_0:c._0}}return l.TAG!=="Ok"?{TAG:"Error",_0:l._0}:(Ln(`Linzumi MCP auth OK
323
- `),{TAG:"Ok",_0:void 0})}async function Rx(e){let t=e.slice(1),r=e[0];if(r!==void 0)switch(r){case"--help":case"-h":return Ln(ma()),{TAG:"Ok",_0:void 0};case"config":return await Ij(t);case"doctor":return await jj(t);case"server":return await Rj(t);default:return{TAG:"Error",_0:"unknown linzumi mcp command: "+r}}else return Ln(ma()),{TAG:"Ok",_0:void 0}}async function Mj(e){let t;try{t=await Rx(Ph(e))}catch(r){let n=ee(r);return Po("linzumi mcp server failed: "+fn(n)+`
324
- `),Rl(1)}if(t.TAG!=="Ok")return Po("linzumi mcp server failed: "+t._0+`
325
- `),Rl(1)}var Ix=process.argv[1],Dj=Ix!==void 0?import.meta.url===jx.pathToFileURL(Ix).href:!1;Dj&&Mj(process.argv.slice(2));export{Dj as invokedDirectly,Mj as runMcpServerEntry};
347
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(t===l[0]){s(l);continue}if(n.external){let m=n.external.registry.get(l[0])?.id;if(t!==l[0]&&m){s(l);continue}}if(this.metadataRegistry.get(l[0])?.id){s(l);continue}if(d.cycle){s(l);continue}if(d.count>1&&n.reused==="ref"){s(l);continue}}let a=(l,d)=>{let h=this.seen.get(l),m=h.def??h.schema,p={...m};if(h.ref===null)return;let f=h.ref;if(h.ref=null,f){a(f,d);let g=this.seen.get(f).schema;g.$ref&&d.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(g)):(Object.assign(m,g),Object.assign(m,p))}h.isParent||this.override({zodSchema:l,jsonSchema:m,path:h.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(t)?.id;if(!l)throw new Error("Schema is missing an `id` property");u.$id=n.external.uri(l)}Object.assign(u,i.def);let c=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(c[d.defId]=d.def)}n.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?u.$defs=c:u.definitions=c);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}};function Pm(e,t){if(e instanceof js){let n=new Lc(t),i={};for(let a of e._idmap.entries()){let[u,c]=a;n.process(c)}let o={},s={registry:e,uri:t?.uri,defs:i};for(let a of e._idmap.entries()){let[u,c]=a;o[u]=n.emit(c,{...t,external:s})}if(Object.keys(i).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[a]:i}}return{schemas:o}}let r=new Lc(t);return r.process(e),r.emit(e,t)}function rt(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let i=e._zod.def;switch(i.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return rt(i.element,r);case"object":{for(let o in i.shape)if(rt(i.shape[o],r))return!0;return!1}case"union":{for(let o of i.options)if(rt(o,r))return!0;return!1}case"intersection":return rt(i.left,r)||rt(i.right,r);case"tuple":{for(let o of i.items)if(rt(o,r))return!0;return!!(i.rest&&rt(i.rest,r))}case"record":return rt(i.keyType,r)||rt(i.valueType,r);case"map":return rt(i.keyType,r)||rt(i.valueType,r);case"set":return rt(i.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return rt(i.innerType,r);case"lazy":return rt(i.getter(),r);case"default":return rt(i.innerType,r);case"prefault":return rt(i.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return rt(i.in,r)||rt(i.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${i.type}`)}var Ds={};au(Ds,{ZodISODate:()=>Ib,ZodISODateTime:()=>Rb,ZodISODuration:()=>Nb,ZodISOTime:()=>jb,date:()=>Rm,datetime:()=>Cm,duration:()=>jm,time:()=>Im});var Rb=k("ZodISODateTime",(e,t)=>{bb.init(e,t),Me.init(e,t)});function Cm(e){return Eb(Rb,e)}var Ib=k("ZodISODate",(e,t)=>{wb.init(e,t),Me.init(e,t)});function Rm(e){return zb(Ib,e)}var jb=k("ZodISOTime",(e,t)=>{xb.init(e,t),Me.init(e,t)});function Im(e){return Ob(jb,e)}var Nb=k("ZodISODuration",(e,t)=>{kb.init(e,t),Me.init(e,t)});function jm(e){return Ab(Nb,e)}var Mb=(e,t)=>{Ec.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Bd(e,r)},flatten:{value:r=>Vd(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},BL=k("ZodError",Mb),Zs=k("ZodError",Mb,{Parent:Error});var Db=Jd(Zs),Zb=Hd(Zs),Lb=Qd(Zs),qb=Xd(Zs);var Je=k("ZodType",(e,t)=>(Se.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>er(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>Db(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Lb(e,r,n),e.parseAsync=async(r,n)=>Zb(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>qb(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(MA(r,n)),e.superRefine=r=>e.check(DA(r)),e.overwrite=r=>e.check(Ri(r)),e.optional=()=>Ze(e),e.nullable=()=>Gb(e),e.nullish=()=>Ze(Gb(e)),e.nonoptional=r=>AA(e,r),e.array=()=>le(e),e.or=r=>Ce([e,r]),e.and=r=>Fc(e,r),e.transform=r=>Mm(e,Kb(r)),e.default=r=>EA(e,r),e.prefault=r=>OA(e,r),e.catch=r=>CA(e,r),e.pipe=r=>Mm(e,r),e.readonly=()=>jA(e),e.describe=r=>{let n=e.clone();return Nn.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Nn.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Nn.get(e);let n=e.clone();return Nn.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Vb=k("_ZodString",(e,t)=>{Is.init(e,t),Je.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(vm(...n)),e.includes=(...n)=>e.check(xm(...n)),e.startsWith=(...n)=>e.check(km(...n)),e.endsWith=(...n)=>e.check(Sm(...n)),e.min=(...n)=>e.check(So(...n)),e.max=(...n)=>e.check(Dc(...n)),e.length=(...n)=>e.check(Zc(...n)),e.nonempty=(...n)=>e.check(So(1,...n)),e.lowercase=n=>e.check(bm(n)),e.uppercase=n=>e.check(wm(n)),e.trim=()=>e.check($m()),e.normalize=(...n)=>e.check(Tm(...n)),e.toLowerCase=()=>e.check(Em()),e.toUpperCase=()=>e.check(zm())}),HO=k("ZodString",(e,t)=>{Is.init(e,t),Vb.init(e,t),e.email=r=>e.check(Bf(KO,r)),e.url=r=>e.check(Qf(QO,r)),e.jwt=r=>e.check(fm(fA,r)),e.emoji=r=>e.check(Xf(XO,r)),e.guid=r=>e.check(Ic(Fb,r)),e.uuid=r=>e.check(Jf(qc,r)),e.uuidv4=r=>e.check(Wf(qc,r)),e.uuidv6=r=>e.check(Hf(qc,r)),e.uuidv7=r=>e.check(Kf(qc,r)),e.nanoid=r=>e.check(Yf(YO,r)),e.guid=r=>e.check(Ic(Fb,r)),e.cuid=r=>e.check(em(eA,r)),e.cuid2=r=>e.check(tm(tA,r)),e.ulid=r=>e.check(rm(rA,r)),e.base64=r=>e.check(lm(lA,r)),e.base64url=r=>e.check(um(uA,r)),e.xid=r=>e.check(nm(nA,r)),e.ksuid=r=>e.check(im(iA,r)),e.ipv4=r=>e.check(om(oA,r)),e.ipv6=r=>e.check(sm(sA,r)),e.cidrv4=r=>e.check(am(aA,r)),e.cidrv6=r=>e.check(cm(cA,r)),e.e164=r=>e.check(dm(dA,r)),e.datetime=r=>e.check(Cm(r)),e.date=r=>e.check(Rm(r)),e.time=r=>e.check(Im(r)),e.duration=r=>e.check(jm(r))});function x(e){return Vf(HO,e)}var Me=k("ZodStringFormat",(e,t)=>{Oe.init(e,t),Vb.init(e,t)}),KO=k("ZodEmail",(e,t)=>{af.init(e,t),Me.init(e,t)});var Fb=k("ZodGUID",(e,t)=>{of.init(e,t),Me.init(e,t)});var qc=k("ZodUUID",(e,t)=>{sf.init(e,t),Me.init(e,t)});var QO=k("ZodURL",(e,t)=>{cf.init(e,t),Me.init(e,t)});var XO=k("ZodEmoji",(e,t)=>{lf.init(e,t),Me.init(e,t)});var YO=k("ZodNanoID",(e,t)=>{uf.init(e,t),Me.init(e,t)});var eA=k("ZodCUID",(e,t)=>{df.init(e,t),Me.init(e,t)});var tA=k("ZodCUID2",(e,t)=>{ff.init(e,t),Me.init(e,t)});var rA=k("ZodULID",(e,t)=>{mf.init(e,t),Me.init(e,t)});var nA=k("ZodXID",(e,t)=>{pf.init(e,t),Me.init(e,t)});var iA=k("ZodKSUID",(e,t)=>{hf.init(e,t),Me.init(e,t)});var oA=k("ZodIPv4",(e,t)=>{gf.init(e,t),Me.init(e,t)});var sA=k("ZodIPv6",(e,t)=>{_f.init(e,t),Me.init(e,t)});var aA=k("ZodCIDRv4",(e,t)=>{yf.init(e,t),Me.init(e,t)});var cA=k("ZodCIDRv6",(e,t)=>{vf.init(e,t),Me.init(e,t)});var lA=k("ZodBase64",(e,t)=>{bf.init(e,t),Me.init(e,t)});var uA=k("ZodBase64URL",(e,t)=>{wf.init(e,t),Me.init(e,t)});var dA=k("ZodE164",(e,t)=>{xf.init(e,t),Me.init(e,t)});var fA=k("ZodJWT",(e,t)=>{kf.init(e,t),Me.init(e,t)});var Bb=k("ZodNumber",(e,t)=>{Pc.init(e,t),Je.init(e,t),e.gt=(n,i)=>e.check(Nc(n,i)),e.gte=(n,i)=>e.check(Ms(n,i)),e.min=(n,i)=>e.check(Ms(n,i)),e.lt=(n,i)=>e.check(jc(n,i)),e.lte=(n,i)=>e.check(Ns(n,i)),e.max=(n,i)=>e.check(Ns(n,i)),e.int=n=>e.check(Ub(n)),e.safe=n=>e.check(Ub(n)),e.positive=n=>e.check(Nc(0,n)),e.nonnegative=n=>e.check(Ms(0,n)),e.negative=n=>e.check(jc(0,n)),e.nonpositive=n=>e.check(Ns(0,n)),e.multipleOf=(n,i)=>e.check(Mc(n,i)),e.step=(n,i)=>e.check(Mc(n,i)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function we(e){return mm(Bb,e)}var mA=k("ZodNumberFormat",(e,t)=>{Sf.init(e,t),Bb.init(e,t)});function Ub(e){return pm(mA,e)}var pA=k("ZodBoolean",(e,t)=>{Tf.init(e,t),Je.init(e,t)});function ct(e){return hm(pA,e)}var hA=k("ZodNull",(e,t)=>{$f.init(e,t),Je.init(e,t)});function Jb(e){return gm(hA,e)}var gA=k("ZodUnknown",(e,t)=>{Ef.init(e,t),Je.init(e,t)});function De(){return _m(gA)}var _A=k("ZodNever",(e,t)=>{zf.init(e,t),Je.init(e,t)});function yA(e){return ym(_A,e)}var vA=k("ZodArray",(e,t)=>{Of.init(e,t),Je.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(So(r,n)),e.nonempty=r=>e.check(So(1,r)),e.max=(r,n)=>e.check(Dc(r,n)),e.length=(r,n)=>e.check(Zc(r,n)),e.unwrap=()=>e.element});function le(e,t){return Pb(vA,e,t)}var Wb=k("ZodObject",(e,t)=>{Cc.init(e,t),Je.init(e,t),ae.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Ft(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:De()}),e.loose=()=>e.clone({...e._zod.def,catchall:De()}),e.strict=()=>e.clone({...e._zod.def,catchall:yA()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>ae.extend(e,r),e.merge=r=>ae.merge(e,r),e.pick=r=>ae.pick(e,r),e.omit=r=>ae.omit(e,r),e.partial=(...r)=>ae.partial(Qb,e,r[0]),e.required=(...r)=>ae.required(Xb,e,r[0])});function P(e,t){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...e}),this.shape},...ae.normalizeParams(t)};return new Wb(r)}function Rt(e,t){return new Wb({type:"object",get shape(){return ae.assignProp(this,"shape",{...e}),this.shape},catchall:De(),...ae.normalizeParams(t)})}var Hb=k("ZodUnion",(e,t)=>{Rc.init(e,t),Je.init(e,t),e.options=t.options});function Ce(e,t){return new Hb({type:"union",options:e,...ae.normalizeParams(t)})}var bA=k("ZodDiscriminatedUnion",(e,t)=>{Hb.init(e,t),Af.init(e,t)});function Dm(e,t,r){return new bA({type:"union",options:t,discriminator:e,...ae.normalizeParams(r)})}var wA=k("ZodIntersection",(e,t)=>{Pf.init(e,t),Je.init(e,t)});function Fc(e,t){return new wA({type:"intersection",left:e,right:t})}var xA=k("ZodRecord",(e,t)=>{Cf.init(e,t),Je.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function Ae(e,t,r){return new xA({type:"record",keyType:e,valueType:t,...ae.normalizeParams(r)})}var Nm=k("ZodEnum",(e,t)=>{Rf.init(e,t),Je.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,i)=>{let o={};for(let s of n)if(r.has(s))o[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Nm({...t,checks:[],...ae.normalizeParams(i),entries:o})},e.exclude=(n,i)=>{let o={...t.entries};for(let s of n)if(r.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new Nm({...t,checks:[],...ae.normalizeParams(i),entries:o})}});function Ft(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Nm({type:"enum",entries:r,...ae.normalizeParams(t)})}var kA=k("ZodLiteral",(e,t)=>{If.init(e,t),Je.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Z(e,t){return new kA({type:"literal",values:Array.isArray(e)?e:[e],...ae.normalizeParams(t)})}var SA=k("ZodTransform",(e,t)=>{jf.init(e,t),Je.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(ae.issue(o,r.value,t));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(ae.issue(s))}};let i=t.transform(r.value,r);return i instanceof Promise?i.then(o=>(r.value=o,r)):(r.value=i,r)}});function Kb(e){return new SA({type:"transform",transform:e})}var Qb=k("ZodOptional",(e,t)=>{Nf.init(e,t),Je.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ze(e){return new Qb({type:"optional",innerType:e})}var TA=k("ZodNullable",(e,t)=>{Mf.init(e,t),Je.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Gb(e){return new TA({type:"nullable",innerType:e})}var $A=k("ZodDefault",(e,t)=>{Df.init(e,t),Je.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function EA(e,t){return new $A({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var zA=k("ZodPrefault",(e,t)=>{Zf.init(e,t),Je.init(e,t),e.unwrap=()=>e._zod.def.innerType});function OA(e,t){return new zA({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Xb=k("ZodNonOptional",(e,t)=>{Lf.init(e,t),Je.init(e,t),e.unwrap=()=>e._zod.def.innerType});function AA(e,t){return new Xb({type:"nonoptional",innerType:e,...ae.normalizeParams(t)})}var PA=k("ZodCatch",(e,t)=>{qf.init(e,t),Je.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function CA(e,t){return new PA({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var RA=k("ZodPipe",(e,t)=>{Ff.init(e,t),Je.init(e,t),e.in=t.in,e.out=t.out});function Mm(e,t){return new RA({type:"pipe",in:e,out:t})}var IA=k("ZodReadonly",(e,t)=>{Uf.init(e,t),Je.init(e,t)});function jA(e){return new IA({type:"readonly",innerType:e})}var Yb=k("ZodCustom",(e,t)=>{Gf.init(e,t),Je.init(e,t)});function NA(e){let t=new pt({check:"custom"});return t._zod.check=e,t}function ew(e,t){return Om(Yb,e??(()=>!0),t)}function MA(e,t={}){return Am(Yb,e,t)}function DA(e){let t=NA(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ae.issue(n,r.value,t._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),r.issues.push(ae.issue(i))}},e(r.value,r)));return t}function Zm(e,t){return Mm(Kb(e),t)}Yt(Tb());var qm="2025-11-25";var tw=[qm,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Mn="io.modelcontextprotocol/related-task",Gc="2.0",nt=ew(e=>e!==null&&(typeof e=="object"||typeof e=="function")),rw=Ce([x(),we().int()]),nw=x(),sq=Rt({ttl:we().optional(),pollInterval:we().optional()}),ZA=P({ttl:we().optional()}),LA=P({taskId:x()}),Fm=Rt({progressToken:rw.optional(),[Mn]:LA.optional()}),tr=P({_meta:Fm.optional()}),Ls=tr.extend({task:ZA.optional()}),iw=e=>Ls.safeParse(e).success,ht=P({method:x(),params:tr.loose().optional()}),cr=P({_meta:Fm.optional()}),lr=P({method:x(),params:cr.loose().optional()}),gt=Rt({_meta:Fm.optional()}),Vc=Ce([x(),we().int()]),ow=P({jsonrpc:Z(Gc),id:Vc,...ht.shape}).strict(),Um=e=>ow.safeParse(e).success,sw=P({jsonrpc:Z(Gc),...lr.shape}).strict(),aw=e=>sw.safeParse(e).success,Gm=P({jsonrpc:Z(Gc),id:Vc,result:gt}).strict(),qs=e=>Gm.safeParse(e).success;var U;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(U||(U={}));var Vm=P({jsonrpc:Z(Gc),id:Vc.optional(),error:P({code:we().int(),message:x(),data:De().optional()})}).strict();var cw=e=>Vm.safeParse(e).success;var lw=Ce([ow,sw,Gm,Vm]),aq=Ce([Gm,Vm]),Bc=gt.strict(),qA=cr.extend({requestId:Vc.optional(),reason:x().optional()}),Jc=lr.extend({method:Z("notifications/cancelled"),params:qA}),FA=P({src:x(),mimeType:x().optional(),sizes:le(x()).optional(),theme:Ft(["light","dark"]).optional()}),Fs=P({icons:le(FA).optional()}),To=P({name:x(),title:x().optional()}),uw=To.extend({...To.shape,...Fs.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),UA=Fc(P({applyDefaults:ct().optional()}),Ae(x(),De())),GA=Zm(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Fc(P({form:UA.optional(),url:nt.optional()}),Ae(x(),De()).optional())),VA=Rt({list:nt.optional(),cancel:nt.optional(),requests:Rt({sampling:Rt({createMessage:nt.optional()}).optional(),elicitation:Rt({create:nt.optional()}).optional()}).optional()}),BA=Rt({list:nt.optional(),cancel:nt.optional(),requests:Rt({tools:Rt({call:nt.optional()}).optional()}).optional()}),JA=P({experimental:Ae(x(),nt).optional(),sampling:P({context:nt.optional(),tools:nt.optional()}).optional(),elicitation:GA.optional(),roots:P({listChanged:ct().optional()}).optional(),tasks:VA.optional(),extensions:Ae(x(),nt).optional()}),WA=tr.extend({protocolVersion:x(),capabilities:JA,clientInfo:uw}),Bm=ht.extend({method:Z("initialize"),params:WA});var HA=P({experimental:Ae(x(),nt).optional(),logging:nt.optional(),completions:nt.optional(),prompts:P({listChanged:ct().optional()}).optional(),resources:P({subscribe:ct().optional(),listChanged:ct().optional()}).optional(),tools:P({listChanged:ct().optional()}).optional(),tasks:BA.optional(),extensions:Ae(x(),nt).optional()}),KA=gt.extend({protocolVersion:x(),capabilities:HA,serverInfo:uw,instructions:x().optional()}),Jm=lr.extend({method:Z("notifications/initialized"),params:cr.optional()});var Wc=ht.extend({method:Z("ping"),params:tr.optional()}),QA=P({progress:we(),total:Ze(we()),message:Ze(x())}),XA=P({...cr.shape,...QA.shape,progressToken:rw}),Hc=lr.extend({method:Z("notifications/progress"),params:XA}),YA=tr.extend({cursor:nw.optional()}),Us=ht.extend({params:YA.optional()}),Gs=gt.extend({nextCursor:nw.optional()}),eP=Ft(["working","input_required","completed","failed","cancelled"]),Vs=P({taskId:x(),status:eP,ttl:Ce([we(),Jb()]),createdAt:x(),lastUpdatedAt:x(),pollInterval:Ze(we()),statusMessage:Ze(x())}),$o=gt.extend({task:Vs}),tP=cr.merge(Vs),Bs=lr.extend({method:Z("notifications/tasks/status"),params:tP}),Kc=ht.extend({method:Z("tasks/get"),params:tr.extend({taskId:x()})}),Qc=gt.merge(Vs),Xc=ht.extend({method:Z("tasks/result"),params:tr.extend({taskId:x()})}),cq=gt.loose(),Yc=Us.extend({method:Z("tasks/list")}),el=Gs.extend({tasks:le(Vs)}),tl=ht.extend({method:Z("tasks/cancel"),params:tr.extend({taskId:x()})}),dw=gt.merge(Vs),fw=P({uri:x(),mimeType:Ze(x()),_meta:Ae(x(),De()).optional()}),mw=fw.extend({text:x()}),Wm=x().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),pw=fw.extend({blob:Wm}),Js=Ft(["user","assistant"]),Eo=P({audience:le(Js).optional(),priority:we().min(0).max(1).optional(),lastModified:Ds.datetime({offset:!0}).optional()}),hw=P({...To.shape,...Fs.shape,uri:x(),description:Ze(x()),mimeType:Ze(x()),size:Ze(we()),annotations:Eo.optional(),_meta:Ze(Rt({}))}),rP=P({...To.shape,...Fs.shape,uriTemplate:x(),description:Ze(x()),mimeType:Ze(x()),annotations:Eo.optional(),_meta:Ze(Rt({}))}),zo=Us.extend({method:Z("resources/list")}),nP=Gs.extend({resources:le(hw)}),Oo=Us.extend({method:Z("resources/templates/list")}),iP=Gs.extend({resourceTemplates:le(rP)}),Hm=tr.extend({uri:x()}),oP=Hm,rl=ht.extend({method:Z("resources/read"),params:oP}),sP=gt.extend({contents:le(Ce([mw,pw]))}),aP=lr.extend({method:Z("notifications/resources/list_changed"),params:cr.optional()}),cP=Hm,lP=ht.extend({method:Z("resources/subscribe"),params:cP}),uP=Hm,dP=ht.extend({method:Z("resources/unsubscribe"),params:uP}),fP=cr.extend({uri:x()}),mP=lr.extend({method:Z("notifications/resources/updated"),params:fP}),pP=P({name:x(),description:Ze(x()),required:Ze(ct())}),hP=P({...To.shape,...Fs.shape,description:Ze(x()),arguments:Ze(le(pP)),_meta:Ze(Rt({}))}),nl=Us.extend({method:Z("prompts/list")}),gP=Gs.extend({prompts:le(hP)}),_P=tr.extend({name:x(),arguments:Ae(x(),x()).optional()}),il=ht.extend({method:Z("prompts/get"),params:_P}),Km=P({type:Z("text"),text:x(),annotations:Eo.optional(),_meta:Ae(x(),De()).optional()}),Qm=P({type:Z("image"),data:Wm,mimeType:x(),annotations:Eo.optional(),_meta:Ae(x(),De()).optional()}),Xm=P({type:Z("audio"),data:Wm,mimeType:x(),annotations:Eo.optional(),_meta:Ae(x(),De()).optional()}),yP=P({type:Z("tool_use"),name:x(),id:x(),input:Ae(x(),De()),_meta:Ae(x(),De()).optional()}),vP=P({type:Z("resource"),resource:Ce([mw,pw]),annotations:Eo.optional(),_meta:Ae(x(),De()).optional()}),bP=hw.extend({type:Z("resource_link")}),Ym=Ce([Km,Qm,Xm,bP,vP]),wP=P({role:Js,content:Ym}),xP=gt.extend({description:x().optional(),messages:le(wP)}),kP=lr.extend({method:Z("notifications/prompts/list_changed"),params:cr.optional()}),SP=P({title:x().optional(),readOnlyHint:ct().optional(),destructiveHint:ct().optional(),idempotentHint:ct().optional(),openWorldHint:ct().optional()}),TP=P({taskSupport:Ft(["required","optional","forbidden"]).optional()}),gw=P({...To.shape,...Fs.shape,description:x().optional(),inputSchema:P({type:Z("object"),properties:Ae(x(),nt).optional(),required:le(x()).optional()}).catchall(De()),outputSchema:P({type:Z("object"),properties:Ae(x(),nt).optional(),required:le(x()).optional()}).catchall(De()).optional(),annotations:SP.optional(),execution:TP.optional(),_meta:Ae(x(),De()).optional()}),ol=Us.extend({method:Z("tools/list")}),$P=Gs.extend({tools:le(gw)}),sl=gt.extend({content:le(Ym).default([]),structuredContent:Ae(x(),De()).optional(),isError:ct().optional()}),lq=sl.or(gt.extend({toolResult:De()})),EP=Ls.extend({name:x(),arguments:Ae(x(),De()).optional()}),Ao=ht.extend({method:Z("tools/call"),params:EP}),zP=lr.extend({method:Z("notifications/tools/list_changed"),params:cr.optional()}),uq=P({autoRefresh:ct().default(!0),debounceMs:we().int().nonnegative().default(300)}),Ws=Ft(["debug","info","notice","warning","error","critical","alert","emergency"]),OP=tr.extend({level:Ws}),ep=ht.extend({method:Z("logging/setLevel"),params:OP}),AP=cr.extend({level:Ws,logger:x().optional(),data:De()}),PP=lr.extend({method:Z("notifications/message"),params:AP}),CP=P({name:x().optional()}),RP=P({hints:le(CP).optional(),costPriority:we().min(0).max(1).optional(),speedPriority:we().min(0).max(1).optional(),intelligencePriority:we().min(0).max(1).optional()}),IP=P({mode:Ft(["auto","required","none"]).optional()}),jP=P({type:Z("tool_result"),toolUseId:x().describe("The unique identifier for the corresponding tool call."),content:le(Ym).default([]),structuredContent:P({}).loose().optional(),isError:ct().optional(),_meta:Ae(x(),De()).optional()}),NP=Dm("type",[Km,Qm,Xm]),Uc=Dm("type",[Km,Qm,Xm,yP,jP]),MP=P({role:Js,content:Ce([Uc,le(Uc)]),_meta:Ae(x(),De()).optional()}),DP=Ls.extend({messages:le(MP),modelPreferences:RP.optional(),systemPrompt:x().optional(),includeContext:Ft(["none","thisServer","allServers"]).optional(),temperature:we().optional(),maxTokens:we().int(),stopSequences:le(x()).optional(),metadata:nt.optional(),tools:le(gw).optional(),toolChoice:IP.optional()}),ZP=ht.extend({method:Z("sampling/createMessage"),params:DP}),Hs=gt.extend({model:x(),stopReason:Ze(Ft(["endTurn","stopSequence","maxTokens"]).or(x())),role:Js,content:NP}),tp=gt.extend({model:x(),stopReason:Ze(Ft(["endTurn","stopSequence","maxTokens","toolUse"]).or(x())),role:Js,content:Ce([Uc,le(Uc)])}),LP=P({type:Z("boolean"),title:x().optional(),description:x().optional(),default:ct().optional()}),qP=P({type:Z("string"),title:x().optional(),description:x().optional(),minLength:we().optional(),maxLength:we().optional(),format:Ft(["email","uri","date","date-time"]).optional(),default:x().optional()}),FP=P({type:Ft(["number","integer"]),title:x().optional(),description:x().optional(),minimum:we().optional(),maximum:we().optional(),default:we().optional()}),UP=P({type:Z("string"),title:x().optional(),description:x().optional(),enum:le(x()),default:x().optional()}),GP=P({type:Z("string"),title:x().optional(),description:x().optional(),oneOf:le(P({const:x(),title:x()})),default:x().optional()}),VP=P({type:Z("string"),title:x().optional(),description:x().optional(),enum:le(x()),enumNames:le(x()).optional(),default:x().optional()}),BP=Ce([UP,GP]),JP=P({type:Z("array"),title:x().optional(),description:x().optional(),minItems:we().optional(),maxItems:we().optional(),items:P({type:Z("string"),enum:le(x())}),default:le(x()).optional()}),WP=P({type:Z("array"),title:x().optional(),description:x().optional(),minItems:we().optional(),maxItems:we().optional(),items:P({anyOf:le(P({const:x(),title:x()}))}),default:le(x()).optional()}),HP=Ce([JP,WP]),KP=Ce([VP,BP,HP]),QP=Ce([KP,LP,qP,FP]),XP=Ls.extend({mode:Z("form").optional(),message:x(),requestedSchema:P({type:Z("object"),properties:Ae(x(),QP),required:le(x()).optional()})}),YP=Ls.extend({mode:Z("url"),message:x(),elicitationId:x(),url:x().url()}),eC=Ce([XP,YP]),tC=ht.extend({method:Z("elicitation/create"),params:eC}),rC=cr.extend({elicitationId:x()}),nC=lr.extend({method:Z("notifications/elicitation/complete"),params:rC}),Po=gt.extend({action:Ft(["accept","decline","cancel"]),content:Zm(e=>e===null?void 0:e,Ae(x(),Ce([x(),we(),ct(),le(x())])).optional())}),iC=P({type:Z("ref/resource"),uri:x()});var oC=P({type:Z("ref/prompt"),name:x()}),sC=tr.extend({ref:Ce([oC,iC]),argument:P({name:x(),value:x()}),context:P({arguments:Ae(x(),x()).optional()}).optional()}),al=ht.extend({method:Z("completion/complete"),params:sC});function _w(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function yw(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var aC=gt.extend({completion:Rt({values:le(x()).max(100),total:Ze(we().int()),hasMore:Ze(ct())})}),cC=P({uri:x().startsWith("file://"),name:x().optional(),_meta:Ae(x(),De()).optional()}),lC=ht.extend({method:Z("roots/list"),params:tr.optional()}),rp=gt.extend({roots:le(cC)}),uC=lr.extend({method:Z("notifications/roots/list_changed"),params:cr.optional()}),dq=Ce([Wc,Bm,al,ep,il,nl,zo,Oo,rl,lP,dP,Ao,ol,Kc,Xc,Yc,tl]),fq=Ce([Jc,Hc,Jm,uC,Bs]),mq=Ce([Bc,Hs,tp,Po,rp,Qc,el,$o]),pq=Ce([Wc,ZP,tC,lC,Kc,Xc,Yc,tl]),hq=Ce([Jc,Hc,PP,mP,aP,zP,kP,Bs,nC]),gq=Ce([Bc,KA,aC,xP,gP,nP,iP,sP,sl,$P,Qc,el,$o]),D=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===U.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new Lm(i.elicitations,r)}return new e(t,r,n)}},Lm=class extends D{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(U.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};var mC=k("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Se.init(e,t),e.def=t,e.parse=(r,n)=>Wd(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Pi(e,r,n),e.parseAsync=async(r,n)=>Kd(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Ci(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>er(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e))});var pC=k("ZodMiniObject",(e,t)=>{Cc.init(e,t),mC.init(e,t),ae.defineLazy(e,"shape",()=>t.shape)});function np(e,t){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...e}),this.shape},...ae.normalizeParams(t)};return new pC(r)}function ur(e){return!!e._zod}function ji(e){let t=Object.values(e);if(t.length===0)return np({});let r=t.every(ur),n=t.every(i=>!ur(i));if(r)return np(e);if(n)return Qu(e);throw new Error("Mixed Zod versions detected in object shape.")}function Dn(e,t){return ur(e)?Pi(e,t):e.safeParse(t)}async function cl(e,t){return ur(e)?await Ci(e,t):await e.safeParseAsync(t)}function Zn(e){if(!e)return;let t;if(ur(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Co(e){if(e){if(typeof e=="object"){let t=e,r=e;if(!t._def&&!r._zod){let n=Object.values(e);if(n.length>0&&n.every(i=>typeof i=="object"&&i!==null&&(i._def!==void 0||i._zod!==void 0||typeof i.parse=="function")))return ji(e)}}if(ur(e)){let r=e._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function ll(e){if(e&&typeof e=="object"){if("message"in e&&typeof e.message=="string")return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t=="object"&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function vw(e){return e.description}function bw(e){if(ur(e))return e._zod?.def?.type==="optional";let t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function ul(e){if(ur(e)){let o=e._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}function Ln(e){return e==="completed"||e==="failed"||e==="cancelled"}var xw=Symbol("Let zodToJsonSchema decide on which parser to use");var ww={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},kw=e=>typeof e=="string"?{...ww,name:e}:{...ww,...e};var Sw=e=>{let t=kw(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function ip(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function ue(e,t,r,n,i){e[t]=r,ip(e,t,n,i)}var dl=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function Le(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?dl(t,e.currentPath):t.join("/")}}function Tw(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==E.ZodAny&&(r.items=W(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&ue(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&ue(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(ue(r,"minItems",e.exactLength.value,e.exactLength.message,t),ue(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function $w(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?ue(r,"minimum",n.value,n.message,t):ue(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ue(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?ue(r,"maximum",n.value,n.message,t):ue(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ue(r,"maximum",n.value,n.message,t));break;case"multipleOf":ue(r,"multipleOf",n.value,n.message,t);break}return r}function Ew(){return{type:"boolean"}}function fl(e,t){return W(e.type._def,t)}var zw=(e,t)=>W(e.innerType._def,t);function op(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,o)=>op(e,t,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return gC(e,t)}}var gC=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":ue(r,"minimum",n.value,n.message,t);break;case"max":ue(r,"maximum",n.value,n.message,t);break}return r};function Ow(e,t){return{...W(e.innerType._def,t),default:e.defaultValue()}}function Aw(e,t){return t.effectStrategy==="input"?W(e.schema._def,t):Le(t)}function Pw(e){return{type:"string",enum:Array.from(e.values)}}var _C=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function Cw(e,t){let r=[W(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),W(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(o=>{if(_C(o))i.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...u}=o;s=u}else n=void 0;i.push(s)}}),i.length?{allOf:i,...n}:void 0}function Rw(e,t){let r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var sp,kr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(sp===void 0&&(sp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),sp),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function ml(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":ue(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":ue(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Sr(r,"email",n.message,t);break;case"format:idn-email":Sr(r,"idn-email",n.message,t);break;case"pattern:zod":It(r,kr.email,n.message,t);break}break;case"url":Sr(r,"uri",n.message,t);break;case"uuid":Sr(r,"uuid",n.message,t);break;case"regex":It(r,n.regex,n.message,t);break;case"cuid":It(r,kr.cuid,n.message,t);break;case"cuid2":It(r,kr.cuid2,n.message,t);break;case"startsWith":It(r,RegExp(`^${ap(n.value,t)}`),n.message,t);break;case"endsWith":It(r,RegExp(`${ap(n.value,t)}$`),n.message,t);break;case"datetime":Sr(r,"date-time",n.message,t);break;case"date":Sr(r,"date",n.message,t);break;case"time":Sr(r,"time",n.message,t);break;case"duration":Sr(r,"duration",n.message,t);break;case"length":ue(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),ue(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{It(r,RegExp(ap(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Sr(r,"ipv4",n.message,t),n.version!=="v4"&&Sr(r,"ipv6",n.message,t);break}case"base64url":It(r,kr.base64url,n.message,t);break;case"jwt":It(r,kr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&It(r,kr.ipv4Cidr,n.message,t),n.version!=="v4"&&It(r,kr.ipv6Cidr,n.message,t);break}case"emoji":It(r,kr.emoji(),n.message,t);break;case"ulid":{It(r,kr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Sr(r,"binary",n.message,t);break}case"contentEncoding:base64":{ue(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{It(r,kr.base64,n.message,t);break}}break}case"nanoid":It(r,kr.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ap(e,t){return t.patternStrategy==="escape"?vC(e):e}var yC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function vC(e){let t="";for(let r=0;r<e.length;r++)yC.has(e[r])||(t+="\\"),t+=e[r];return t}function Sr(e,t,r,n){e.format||e.anyOf?.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ue(e,"format",t,r,n)}function It(e,t,r,n){e.pattern||e.allOf?.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Iw(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ue(e,"pattern",Iw(t,n),r,n)}function Iw(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source,i="",o=!1,s=!1,a=!1;for(let u=0;u<n.length;u++){if(o){i+=n[u],o=!1;continue}if(r.i){if(s){if(n[u].match(/[a-z]/)){a?(i+=n[u],i+=`${n[u-2]}-${n[u]}`.toUpperCase(),a=!1):n[u+1]==="-"&&n[u+2]?.match(/[a-z]/)?(i+=n[u],a=!0):i+=`${n[u]}${n[u].toUpperCase()}`;continue}}else if(n[u].match(/[a-z]/)){i+=`[${n[u]}${n[u].toUpperCase()}]`;continue}}if(r.m){if(n[u]==="^"){i+=`(^|(?<=[\r
348
+ ]))`;continue}else if(n[u]==="$"){i+=`($|(?=[\r
349
+ ]))`;continue}}if(r.s&&n[u]==="."){i+=s?`${n[u]}\r
350
+ `:`[${n[u]}\r
351
+ ]`;continue}i+=n[u],n[u]==="\\"?o=!0:s&&n[u]==="]"?s=!1:!s&&n[u]==="["&&(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function pl(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===E.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,i)=>({...n,[i]:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",i]})??Le(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===E.ZodString&&e.keyType._def.checks?.length){let{type:n,...i}=ml(e.keyType._def,t);return{...r,propertyNames:i}}else{if(e.keyType?._def.typeName===E.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===E.ZodBranded&&e.keyType._def.type._def.typeName===E.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...i}=fl(e.keyType._def,t);return{...r,propertyNames:i}}}return r}function jw(e,t){if(t.mapStrategy==="record")return pl(e,t);let r=W(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Le(t),n=W(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Le(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Nw(e){let t=e.values,n=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),i=Array.from(new Set(n.map(o=>typeof o)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function Mw(e){return e.target==="openAi"?void 0:{not:Le({...e,currentPath:[...e.currentPath,"not"]})}}function Dw(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ks={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Lw(e,t){if(t.target==="openApi3")return Zw(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Ks&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,o)=>{let s=Ks[o._def.typeName];return s&&!i.includes(s)?[...i,s]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((i,o)=>{let s=typeof o._def.value;switch(s){case"string":case"number":case"boolean":return[...i,s];case"bigint":return[...i,"integer"];case"object":if(o._def.value===null)return[...i,"null"];default:return i}},[]);if(n.length===r.length){let i=n.filter((o,s,a)=>a.indexOf(o)===s);return{type:i.length>1?i:i[0],enum:r.reduce((o,s)=>o.includes(s._def.value)?o:[...o,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(o=>!n.includes(o))],[])};return Zw(e,t)}var Zw=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,i)=>W(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function qw(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Ks[e.innerType._def.typeName],nullable:!0}:{type:[Ks[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=W(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=W(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Fw(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",ip(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?ue(r,"minimum",n.value,n.message,t):ue(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ue(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?ue(r,"maximum",n.value,n.message,t):ue(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ue(r,"maximum",n.value,n.message,t));break;case"multipleOf":ue(r,"multipleOf",n.value,n.message,t);break}return r}function Uw(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},i=[],o=e.shape();for(let a in o){let u=o[a];if(u===void 0||u._def===void 0)continue;let c=wC(u);c&&r&&(u._def.typeName==="ZodOptional"&&(u=u._def.innerType),u.isNullable()||(u=u.nullable()),c=!1);let l=W(u._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,c||i.push(a))}i.length&&(n.required=i);let s=bC(e,t);return s!==void 0&&(n.additionalProperties=s),n}function bC(e,t){if(e.catchall._def.typeName!=="ZodNever")return W(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function wC(e){try{return e.isOptional()}catch{return!0}}var Gw=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return W(e.innerType._def,t);let r=W(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Le(t)},r]}:Le(t)};var Vw=(e,t)=>{if(t.pipeStrategy==="input")return W(e.in._def,t);if(t.pipeStrategy==="output")return W(e.out._def,t);let r=W(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=W(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function Bw(e,t){return W(e.type._def,t)}function Jw(e,t){let n={type:"array",uniqueItems:!0,items:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ue(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ue(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function Ww(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>W(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:W(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>W(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Hw(e){return{not:Le(e)}}function Kw(e){return Le(e)}var Qw=(e,t)=>W(e.innerType._def,t);var Xw=(e,t,r)=>{switch(t){case E.ZodString:return ml(e,r);case E.ZodNumber:return Fw(e,r);case E.ZodObject:return Uw(e,r);case E.ZodBigInt:return $w(e,r);case E.ZodBoolean:return Ew();case E.ZodDate:return op(e,r);case E.ZodUndefined:return Hw(r);case E.ZodNull:return Dw(r);case E.ZodArray:return Tw(e,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return Lw(e,r);case E.ZodIntersection:return Cw(e,r);case E.ZodTuple:return Ww(e,r);case E.ZodRecord:return pl(e,r);case E.ZodLiteral:return Rw(e,r);case E.ZodEnum:return Pw(e);case E.ZodNativeEnum:return Nw(e);case E.ZodNullable:return qw(e,r);case E.ZodOptional:return Gw(e,r);case E.ZodMap:return jw(e,r);case E.ZodSet:return Jw(e,r);case E.ZodLazy:return()=>e.getter()._def;case E.ZodPromise:return Bw(e,r);case E.ZodNaN:case E.ZodNever:return Mw(r);case E.ZodEffects:return Aw(e,r);case E.ZodAny:return Le(r);case E.ZodUnknown:return Kw(r);case E.ZodDefault:return Ow(e,r);case E.ZodBranded:return fl(e,r);case E.ZodReadonly:return Qw(e,r);case E.ZodCatch:return zw(e,r);case E.ZodPipeline:return Vw(e,r);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(n=>{})(t)}};function W(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==xw)return a}if(n&&!r){let a=xC(n,t);if(a!==void 0)return a}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let o=Xw(e,e.typeName,t),s=typeof o=="function"?W(o(),t):o;if(s&&kC(e,t,s),t.postProcess){let a=t.postProcess(s,e,t);return i.jsonSchema=s,a}return i.jsonSchema=s,s}var xC=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:dl(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Le(t)):t.$refStrategy==="seen"?Le(t):void 0}},kC=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var cp=(e,t)=>{let r=Sw(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((u,[c,l])=>({...u,[c]:W(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Le(r)}),{}):void 0,i=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=W(e._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??Le(r),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(o.title=s),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=i===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function SC(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function lp(e,t){return ur(e)?Pm(e,{target:SC(t?.target),io:t?.pipeStrategy??"input"}):cp(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function up(e){let r=Zn(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ul(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function dp(e,t){let r=Dn(e,t);if(!r.success)throw r.error;return r.data}var TC=6e4,hl=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Jc,r=>{this._oncancel(r)}),this.setNotificationHandler(Hc,r=>{this._onprogress(r)}),this.setRequestHandler(Wc,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Kc,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new D(U.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(Xc,async(r,n)=>{let i=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let u=a.message,c=u.id,l=this._requestResolvers.get(c);if(l)if(this._requestResolvers.delete(c),a.type==="response")l(u);else{let d=u,h=new D(d.error.code,d.error.message,d.error.data);l(h)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(o,n.sessionId);if(!s)throw new D(U.InvalidParams,`Task not found: ${o}`);if(!Ln(s.status))return await this._waitForTaskUpdate(o,n.signal),await i();if(Ln(s.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Mn]:{taskId:o}}}}return await i()};return await i()}),this.setRequestHandler(Yc,async(r,n)=>{try{let{tasks:i,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:o,_meta:{}}}catch(i){throw new D(U.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(tl,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new D(U.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ln(i.status))throw new D(U.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new D(U.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(i){throw i instanceof D?i:new D(U.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,i,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),D.fromError(U.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let i=this._transport?.onmessage;this._transport.onmessage=(o,s)=>{i?.(o,s),qs(o)||cw(o)?this._onresponse(o):Um(o)?this._onrequest(o,s):aw(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=D.fromError(U.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,i=this._transport,o=t.params?._meta?.[Mn]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:U.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},i?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):i?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=iw(t.params)?t.params.task:void 0,u=this._taskStore?this.requestTaskStore(t,i?.sessionId):void 0,c={signal:s.signal,sessionId:i?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};o&&(d.relatedTask={taskId:o}),await this.notification(l,d)},sendRequest:async(l,d,h)=>{if(s.signal.aborted)throw new D(U.ConnectionClosed,"Request was cancelled");let m={...h,relatedRequestId:t.id};o&&!m.relatedTask&&(m.relatedTask={taskId:o});let p=m.relatedTask?.taskId??o;return p&&u&&await u.updateTaskStatus(p,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:o,taskStore:u,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async l=>{if(s.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)},async l=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:U.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,i=Number(r),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(i),a=this._timeoutInfo.get(i);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(u){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),s(u);return}o(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),qs(t))n(t);else{let s=new D(t.error.code,t.error.message,t.error.data);n(s)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(qs(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),qs(t))i(t);else{let s=D.fromError(t.error.code,t.error.message,t.error.data);i(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof D?s:new D(U.InternalError,String(s))}}return}let o;try{let s=await this.request(t,$o,n);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new D(U.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},Ln(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new D(U.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new D(U.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let u=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,u)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof D?s:new D(U.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s,task:a,relatedTask:u}=n??{};return new Promise((c,l)=>{let d=v=>{l(v)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(v){d(v);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),a&&(m.params={...m.params,task:a}),u&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Mn]:u}});let p=v=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(v)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(w=>this._onerror(new Error(`Failed to send cancellation: ${w}`)));let b=v instanceof D?v:new D(U.RequestTimeout,String(v));l(b)};this._responseHandlers.set(h,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let b=Dn(r,v.result);b.success?c(b.data):l(b.error)}catch(b){l(b)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let f=n?.timeout??TC,g=()=>p(D.fromError(U.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(h,f,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=u?.taskId;if(y){let v=b=>{let w=this._responseHandlers.get(h);w?w(b):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,v),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(h),l(b)})}else this._transport.send(m,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(v=>{this._cleanupTimeout(h),l(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Qc,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},el,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},dw,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Mn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Mn]:r.relatedTask}}}),this._transport?.send(a,r).catch(u=>this._onerror(u))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Mn]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=up(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,o)=>{let s=dp(t,i);return Promise.resolve(r(s,o))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=up(t);this._notificationHandlers.set(n,i=>{let o=dp(t,i);return Promise.resolve(r(o))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,i)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let i of n)if(i.type==="request"&&Um(i.message)){let o=i.message.id,s=this._requestResolvers.get(o);s?(s(new D(U.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(t);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,o)=>{if(r.aborted){o(new D(U.InvalidRequest,"Request cancelled"));return}let s=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(s),o(new D(U.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!t)throw new Error("No request provided");return await n.createTask(i,t.id,{method:t.method,params:t.params},r)},getTask:async i=>{let o=await n.getTask(i,r);if(!o)throw new D(U.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(i,o,s)=>{await n.storeTaskResult(i,o,s,r);let a=await n.getTask(i,r);if(a){let u=Bs.parse({method:"notifications/tasks/status",params:a});await this.notification(u),Ln(a.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,o,s)=>{let a=await n.getTask(i,r);if(!a)throw new D(U.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(Ln(a.status))throw new D(U.InvalidParams,`Cannot update task "${i}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,o,s,r);let u=await n.getTask(i,r);if(u){let c=Bs.parse({method:"notifications/tasks/status",params:u});await this.notification(c),Ln(u.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function Yw(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function e0(e,t){let r={...e};for(let n in t){let i=n,o=t[i];if(o===void 0)continue;let s=r[i];Yw(s)&&Yw(o)?r[i]={...s,...o}:r[i]=o}return r}var Lk=cu(Kh(),1),qk=cu(Zk(),1);function hM(){let e=new Lk.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,qk.default)(e),e}var Xl=class{constructor(t){this._ajv=t??hM()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Yl=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let i=t.messages[t.messages.length-1],o=Array.isArray(i.content)?i.content:[i.content],s=o.some(l=>l.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,u=a?Array.isArray(a.content)?a.content:[a.content]:[],c=u.some(l=>l.type==="tool_use");if(s){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(u.filter(h=>h.type==="tool_use").map(h=>h.id)),d=new Set(o.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(l.size!==d.size||![...l].every(h=>d.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},Hs,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),i=t.mode??"form";switch(i){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=i==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:o},Po,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function Fk(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Uk(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var eu=class extends hl{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ws.options.map((n,i)=>[n,i])),this.isMessageIgnored=(n,i)=>{let o=this._loggingLevels.get(i);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Xl,this.setRequestHandler(Bm,n=>this._oninitialize(n)),this.setNotificationHandler(Jm,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ep,async(n,i)=>{let o=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=Ws.safeParse(s);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Yl(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=e0(this._capabilities,t)}setRequestHandler(t,r){let i=Zn(t)?.method;if(!i)throw new Error("Schema is missing a method literal");let o;if(ur(i)){let a=i;o=a._zod?.def?.value??a.value}else{let a=i;o=a._def?.value??a.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(u,c)=>{let l=Dn(Ao,u);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new D(U.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,h=await Promise.resolve(r(u,c));if(d.task){let p=Dn($o,h);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new D(U.InvalidParams,`Invalid task creation result: ${f}`)}return p.data}let m=Dn(sl,h);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new D(U.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){Uk(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Fk(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:tw.includes(r)?r:qm,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Bc)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],i=Array.isArray(n.content)?n.content:[n.content],o=i.some(c=>c.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],u=a.some(c=>c.type==="tool_use");if(o){if(i.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let c=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(i.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(c.size!==l.size||![...c].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},tp,r):this.request({method:"sampling/createMessage",params:t},Hs,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let i=t;return this.request({method:"elicitation/create",params:i},Po,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let i=t.mode==="form"?t:{...t,mode:"form"},o=await this.request({method:"elicitation/create",params:i},Po,r);if(o.action==="accept"&&o.content&&i.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(i.requestedSchema)(o.content);if(!a.valid)throw new D(U.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof D?s:new D(U.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return o}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},rp,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Vk=Symbol.for("mcp.completable");function ig(e){return!!e&&typeof e=="object"&&Vk in e}function Bk(e){return e[Vk]?.complete}var Gk;(function(e){e.Completable="McpCompletable"})(Gk||(Gk={}));var gM=/^[A-Za-z0-9._-]{1,128}$/;function _M(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!gM.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,i,o)=>o.indexOf(n)===i);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function yM(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function og(e){let t=_M(e);return yM(e,t.warnings),t.isValid}var tu=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let i={taskSupport:"required",...r.execution};if(i.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,i,r._meta,n)}};var ru=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new eu(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new tu(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Hn(ol)),this.server.assertCanSetRequestHandler(Hn(Ao)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ol,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let i=Co(r.inputSchema);return i?lp(i,{strictUnions:!0,pipeStrategy:"input"}):vM})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let i=Co(r.outputSchema);i&&(n.outputSchema=lp(i,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ao,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new D(U.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new D(U.InvalidParams,`Tool ${t.params.name} disabled`);let i=!!t.params.task,o=n.execution?.taskSupport,s="createTask"in n.handler;if((o==="required"||o==="optional")&&!s)throw new D(U.InternalError,`Tool ${t.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!i)throw new D(U.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!i&&s)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),u=await this.executeToolHandler(n,a,r);return i||await this.validateToolOutput(n,u,t.params.name),u}catch(n){if(n instanceof D&&n.code===U.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;let o=Co(t.inputSchema)??t.inputSchema,s=await cl(o,r);if(!s.success){let a="error"in s?s.error:"Unknown error",u=ll(a);throw new D(U.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${u}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new D(U.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let i=Co(t.outputSchema),o=await cl(i,r.structuredContent);if(!o.success){let s="error"in o?o.error:"Unknown error",a=ll(s);throw new D(U.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let i=t.handler;if("createTask"in i){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(t.inputSchema){let a=i;return await Promise.resolve(a.createTask(r,s))}else{let a=i;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=i;return await Promise.resolve(s(r,n))}else{let s=i;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let i=await this.validateToolInput(t,r.params.arguments,r.params.name),o=t.handler,s={...n,taskStore:n.taskStore},a=i?await Promise.resolve(o.createTask(i,s)):await Promise.resolve(o.createTask(s)),u=a.task.taskId,c=a.task,l=c.pollInterval??5e3;for(;c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled";){await new Promise(h=>setTimeout(h,l));let d=await n.taskStore.getTask(u);if(!d)throw new D(U.InternalError,`Task ${u} not found during polling`);c=d}return await n.taskStore.getTaskResult(u)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Hn(al)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(al,async t=>{switch(t.params.ref.type){case"ref/prompt":return _w(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return yw(t),this.handleResourceCompletion(t,t.params.ref);default:throw new D(U.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new D(U.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new D(U.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return $a;let o=Zn(n.argsSchema)?.[t.params.argument.name];if(!ig(o))return $a;let s=Bk(o);if(!s)return $a;let a=await s(t.params.argument.value,t.params.context);return Wk(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return $a;throw new D(U.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let i=n.resourceTemplate.completeCallback(t.params.argument.name);if(!i)return $a;let o=await i(t.params.argument.value,t.params.context);return Wk(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Hn(zo)),this.server.assertCanSetRequestHandler(Hn(Oo)),this.server.assertCanSetRequestHandler(Hn(rl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(zo,async(t,r)=>{let n=Object.entries(this._registeredResources).filter(([o,s])=>s.enabled).map(([o,s])=>({uri:o,name:s.name,...s.metadata})),i=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let s=await o.resourceTemplate.listCallback(r);for(let a of s.resources)i.push({...o.metadata,...a})}return{resources:[...n,...i]}}),this.server.setRequestHandler(Oo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(rl,async(t,r)=>{let n=new URL(t.params.uri),i=this._registeredResources[n.toString()];if(i){if(!i.enabled)throw new D(U.InvalidParams,`Resource ${n} disabled`);return i.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let s=o.resourceTemplate.uriTemplate.match(n.toString());if(s)return o.readCallback(n,s,r)}throw new D(U.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Hn(nl)),this.server.assertCanSetRequestHandler(Hn(il)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(nl,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?bM(r.argsSchema):void 0}))})),this.server.setRequestHandler(il,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new D(U.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new D(U.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let i=Co(n.argsSchema),o=await cl(i,t.params.arguments);if(!o.success){let u="error"in o?o.error:"Unknown error",c=ll(u);throw new D(U.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${c}`)}let s=o.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let i=n.callback;return await Promise.resolve(i(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let i;typeof n[0]=="object"&&(i=n.shift());let o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,void 0,r,i,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,i,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,i){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(t,n.title,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let o=this._createRegisteredResourceTemplate(t,n.title,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(t,r,n,i,o){let s={name:t,title:r,metadata:i,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(t,r,n,i,o){let s={resourceTemplate:n,title:r,metadata:i,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==t&&(delete this._registeredResourceTemplates[t],c.name&&(this._registeredResourceTemplates[c.name]=s)),typeof c.title<"u"&&(s.title=c.title),typeof c.template<"u"&&(s.resourceTemplate=c.template),typeof c.metadata<"u"&&(s.metadata=c.metadata),typeof c.callback<"u"&&(s.readCallback=c.callback),typeof c.enabled<"u"&&(s.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(c=>!!n.completeCallback(c))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,i,o){let s={title:r,description:n,argsSchema:i===void 0?void 0:ji(i),callback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=ji(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,i&&Object.values(i).some(u=>{let c=u instanceof Zt?u._def?.innerType:u;return ig(c)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,i,o,s,a,u,c){og(t);let l={title:r,description:n,inputSchema:Jk(i),outputSchema:Jk(o),annotations:s,execution:a,_meta:u,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&og(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=ji(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=ji(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,i,o,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let u=r[0];if(sg(u))i=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!sg(r[0])&&(s=r.shift());else if(typeof u=="object"&&u!==null){if(Object.values(u).some(c=>typeof c=="object"&&c!==null))throw new Error(`Tool ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,i,o,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:i,description:o,inputSchema:s,outputSchema:a,annotations:u,_meta:c}=r;return this._createRegisteredTool(t,i,o,s,a,u,{taskSupport:"forbidden"},c,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let i;r.length>1&&(i=r.shift());let o=r[0],s=this._createRegisteredPrompt(t,void 0,n,i,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:i,description:o,argsSchema:s}=r,a=this._createRegisteredPrompt(t,i,o,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var vM={type:"object",properties:{}};function Hk(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function Kk(e){return"_def"in e||"_zod"in e||Hk(e)}function sg(e){return typeof e!="object"||e===null||Kk(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Hk)}function Jk(e){if(e){if(sg(e))return ji(e);if(!Kk(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function bM(e){let t=Zn(e);return t?Object.entries(t).map(([r,n])=>{let i=vw(n),o=bw(n);return{name:r,description:i,required:!o}}):[]}function Hn(e){let r=Zn(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ul(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Wk(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var $a={completion:{values:[],hasMore:!1}};import Xk from"node:process";var nu=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
352
+ `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),xM(r)}clear(){this._buffer=void 0}};function xM(e){return lw.parse(JSON.parse(e))}function Qk(e){return JSON.stringify(e)+`
353
+ `}var iu=class{constructor(t=Xk.stdin,r=Xk.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new nu,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=Qk(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function SM(e){let t={};t.listChanged=!1;let r={};r.resources=t,e.server.registerCapabilities(r),e.server.setRequestHandler(zo,()=>{let n={};return n.resources=[],n}),e.server.setRequestHandler(Oo,()=>{let n={};return n.resourceTemplates=[],n})}function TM(e){return{registerTool:(t,r,n,i)=>{e.tool(t,r,n,i)}}}function $M(e){return(t,r)=>e.server.elicitInput(t,{timeout:r})}async function ag(e){let t=e.delegationAuthFilePath;if(t!==void 0){let n=e.explicitToken,i=e.authFilePath;if(n!==void 0)return{TAG:"Error",_0:"--delegation-auth-file cannot be combined with --token or --auth-file"};if(i!==void 0)return{TAG:"Error",_0:"--delegation-auth-file cannot be combined with --token or --auth-file"};let o=v_(t,Date.now());return o.TAG==="Ok"?{TAG:"Ok",_0:{accessToken:o._0.accessToken,mode:"PersonalAgentDelegation"}}:{TAG:"Error",_0:o._0.summary}}let r=await U_(e.serviceUrl,e.explicitToken,e.authFilePath,e.workspaceSlug,e.channelSlug,void 0);return r.TAG==="Ok"?{TAG:"Ok",_0:{accessToken:r._0,mode:"LocalRunner"}}:{TAG:"Error",_0:r._0.summary}}function cg(e,t){let r=We(e,"token");return{serviceUrl:t,explicitToken:r!==void 0?r:process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:We(e,"auth-file"),delegationAuthFilePath:We(e,"delegation-auth-file"),workspaceSlug:We(e,"workspace"),channelSlug:We(e,"channel")}}async function EM(e){let t=Ra(e);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};let r=t._0;if(Hi(r,"help"))return Xn(Na()),{TAG:"Ok",_0:void 0};let n=Ia(r,"api-url");if(n.TAG!=="Ok")return{TAG:"Error",_0:n._0};let i=n._0,o=await ag(cg(r,i));if(o.TAG!=="Ok")return{TAG:"Error",_0:o._0};let s=o._0,a=ja(We(r,"mode")),u=fu(We(r,"tool-scope"));if(a.TAG!=="Ok")return{TAG:"Error",_0:a._0};let c=a._0;if(u.TAG!=="Ok")return{TAG:"Error",_0:u._0};let l=We(r,"owner-username"),d=l!==void 0?l:process.env.LINZUMI_MCP_OWNER_USERNAME,h=We(r,"cwd"),m=h!==void 0?h:process.cwd(),p=We(r,"thread-id"),f=p!==void 0?p:process.env[iy],g=Id({serviceUrl:i,accessToken:s.accessToken,authMode:s.mode,operatingMode:c});if(g.TAG!=="Ok")return{TAG:"Error",_0:g._0};let y=new ru({name:"linzumi",version:"0.1.0"});return SM(y),hv(TM(y),{client:g._0,toolScope:u._0,operatingMode:c,cwd:m,serviceUrl:i,defaultThreadId:f,ownerUsername:d,agentSession:Hi(r,"agent-session"),documentSurfaces:gv(s.accessToken),multiAgentJobs:Hi(r,"multi-agent-jobs"),devServices:tv(process.env),askUserQuestion:Hi(r,"ask-user-question-tool")?$M(y):void 0}),await y.connect(new iu),{TAG:"Ok",_0:void 0}}async function zM(e){let t=Ra(e);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};let r=t._0,n=Ia(r,"api-url");if(n.TAG!=="Ok")return{TAG:"Error",_0:n._0};let i=n._0,o=We(r,"format"),s=o!==void 0?o:"codex",a=ja(We(r,"mode"));if(a.TAG!=="Ok")return{TAG:"Error",_0:a._0};let u;if(Hi(r,"include-token")){let h=await ag(cg(r,i));u=h.TAG==="Ok"?{TAG:"Ok",_0:h._0.accessToken}:{TAG:"Error",_0:h._0}}else u={TAG:"Ok",_0:void 0};if(u.TAG!=="Ok")return{TAG:"Error",_0:u._0};let c=fu(We(r,"tool-scope"));if(c.TAG!=="Ok")return{TAG:"Error",_0:c._0};let l=We(r,"owner-username"),d=iv({command:We(r,"command"),serviceUrl:i,accessToken:u._0,delegationAuthFilePath:We(r,"delegation-auth-file"),ownerUsername:l!==void 0?l:process.env.LINZUMI_MCP_OWNER_USERNAME,operatingMode:a._0,toolScope:c._0});switch(s){case"claude-code":return Xn(ov(d)),{TAG:"Ok",_0:void 0};case"codex":return Xn(sv(d)),{TAG:"Ok",_0:void 0};default:return{TAG:"Error",_0:"--format must be codex or claude-code"}}}async function OM(e){let t=Ra(e);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};let r=t._0,n=Ia(r,"api-url");if(n.TAG!=="Ok")return{TAG:"Error",_0:n._0};let i=n._0,o=await ag(cg(r,i));if(o.TAG!=="Ok")return{TAG:"Error",_0:o._0};let s=o._0,a=s.mode,u;if(a==="LocalRunner"){let c=await io(i,s.accessToken,We(r,"workspace"),We(r,"channel"),void 0);if(c.TAG==="Ok")switch(c._0){case"Usable":u={TAG:"Ok",_0:void 0};break;case"Rejected":case"NotFound":u={TAG:"Error",_0:"Linzumi MCP auth validation failed"};break}else u={TAG:"Error",_0:c._0.summary}}else{let c=ja(We(r,"mode"));if(c.TAG==="Ok"){let l=Id({serviceUrl:i,accessToken:s.accessToken,authMode:s.mode,operatingMode:c._0});if(l.TAG==="Ok")try{await l._0.validateAuth(),u={TAG:"Ok",_0:void 0}}catch(d){let h=X(d);u={TAG:"Error",_0:wn(h)}}else u={TAG:"Error",_0:l._0}}else u={TAG:"Error",_0:c._0}}return u.TAG!=="Ok"?{TAG:"Error",_0:u._0}:(Xn(`Linzumi MCP auth OK
354
+ `),{TAG:"Ok",_0:void 0})}async function Yk(e){let t=e.slice(1),r=e[0];if(r!==void 0)switch(r){case"--help":case"-h":return Xn(Na()),{TAG:"Ok",_0:void 0};case"config":return await zM(t);case"doctor":return await OM(t);case"server":return await EM(t);default:return{TAG:"Error",_0:"unknown linzumi mcp command: "+r}}else return Xn(Na()),{TAG:"Ok",_0:void 0}}async function PM(e){let t;try{t=await Yk(xg(e))}catch(r){let n=X(r);return Yo("linzumi mcp server failed: "+wn(n)+`
355
+ `),pu(1)}if(t.TAG!=="Ok")return Yo("linzumi mcp server failed: "+t._0+`
356
+ `),pu(1)}var eS=process.argv[1],CM=eS!==void 0?import.meta.url===tS.pathToFileURL(eS).href:!1;CM&&PM(process.argv.slice(2));export{CM as invokedDirectly,PM as runMcpServerEntry};