@linzumi/cli 1.0.120 → 1.0.122
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/impl-res/crossHarnessFailover.mjs +14 -0
- package/dist/impl-res/index.js +366 -0
- package/dist/impl-res/mcp-server.mjs +325 -0
- package/dist/impl-ts/assets/linzumi-logo.svg +1 -0
- package/dist/impl-ts/cloud-supervisor.mjs +18 -0
- package/dist/impl-ts/crossHarnessFailover.mjs +14 -0
- package/dist/impl-ts/index.js +2394 -0
- package/dist/impl-ts/mcp-server.mjs +424 -0
- package/dist/index.js +3 -2393
- package/package.json +1 -1
- package/scripts/build-differential-entry-impl-res.mjs +64 -0
- package/scripts/build-differential-entry.mjs +2 -2
- package/scripts/build.mjs +120 -10
- package/scripts/check-package-size-budget.mjs +186 -0
- package/dist/crossHarnessFailover.mjs +0 -6
- /package/dist/{assets → impl-res/assets}/linzumi-logo.svg +0 -0
- /package/dist/{cloud-supervisor.mjs → impl-res/cloud-supervisor.mjs} +0 -0
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
const require = createRequire(import.meta.url);
|
|
3
|
+
var nv=Object.create;var Ei=Object.defineProperty;var ov=Object.getOwnPropertyDescriptor;var sv=Object.getOwnPropertyNames;var iv=Object.getPrototypeOf,av=Object.prototype.hasOwnProperty;var z=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ii=(e,t)=>{for(var r in t)Ei(e,r,{get:t[r],enumerable:!0})},cv=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of sv(t))!av.call(e,o)&&o!==r&&Ei(e,o,{get:()=>t[o],enumerable:!(n=ov(t,o))||n.enumerable});return e};var Dl=(e,t,r)=>(r=e!=null?nv(iv(e)):{},cv(t||!e||!e.__esModule?Ei(r,"default",{value:e,enumerable:!0}):r,e));var eo=z(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.regexpCode=Q.getEsmExportName=Q.getProperty=Q.safeStringify=Q.stringify=Q.strConcat=Q.addCodeArg=Q.str=Q._=Q.nil=Q._Code=Q.Name=Q.IDENTIFIER=Q._CodeOrName=void 0;var Yn=class{};Q._CodeOrName=Yn;Q.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Pr=class extends Yn{constructor(t){if(super(),!Q.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}}};Q.Name=Pr;var tt=class extends Yn{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 Pr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Q._Code=tt;Q.nil=new tt("");function Mf(e,...t){let r=[e[0]],n=0;for(;n<t.length;)mu(r,t[n]),r.push(e[++n]);return new tt(r)}Q._=Mf;var pu=new tt("+");function Nf(e,...t){let r=[Qn(e[0])],n=0;for(;n<t.length;)r.push(pu),mu(r,t[n]),r.push(pu,Qn(e[++n]));return i0(r),new tt(r)}Q.str=Nf;function mu(e,t){t instanceof tt?e.push(...t._items):t instanceof Pr?e.push(t):e.push(u0(t))}Q.addCodeArg=mu;function i0(e){let t=1;for(;t<e.length-1;){if(e[t]===pu){let r=a0(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function a0(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Pr||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 Pr))return`"${e}${t.slice(1)}`}function c0(e,t){return t.emptyStr()?e:e.emptyStr()?t:Nf`${e}${t}`}Q.strConcat=c0;function u0(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Qn(Array.isArray(e)?e.join(","):e)}function d0(e){return new tt(Qn(e))}Q.stringify=d0;function Qn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Q.safeStringify=Qn;function l0(e){return typeof e=="string"&&Q.IDENTIFIER.test(e)?new tt(`.${e}`):Mf`[${e}]`}Q.getProperty=l0;function p0(e){if(typeof e=="string"&&Q.IDENTIFIER.test(e))return new tt(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Q.getEsmExportName=p0;function m0(e){return new tt(e.toString())}Q.regexpCode=m0});var gu=z(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.ValueScope=qe.ValueScopeName=qe.Scope=qe.varKinds=qe.UsedValueState=void 0;var Ue=eo(),fu=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Cs;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Cs||(qe.UsedValueState=Cs={}));qe.varKinds={const:new Ue.Name("const"),let:new Ue.Name("let"),var:new Ue.Name("var")};var As=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ue.Name?t:this.name(t)}name(t){return new Ue.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}}};qe.Scope=As;var Ms=class extends Ue.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ue._)`.${new Ue.Name(r)}[${n}]`}};qe.ValueScopeName=Ms;var f0=(0,Ue._)`\n`,hu=class extends As{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?f0:Ue.nil}}get(){return this._scope}name(t){return new Ms(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 o=this.toName(t),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let d=a.get(i);if(d)return d}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}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,Ue._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(t,r,n={},o){let s=Ue.nil;for(let i in t){let a=t[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Cs.Started);let d=r(u);if(d){let l=this.opts.es5?qe.varKinds.var:qe.varKinds.const;s=(0,Ue._)`${s}${l} ${u} = ${d};${this.opts._n}`}else if(d=o?.(u))s=(0,Ue._)`${s}${d}${this.opts._n}`;else throw new fu(u);c.set(u,Cs.Completed)})}return s}};qe.ValueScope=hu});var F=z(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.or=V.and=V.not=V.CodeGen=V.operators=V.varKinds=V.ValueScopeName=V.ValueScope=V.Scope=V.Name=V.regexpCode=V.stringify=V.getProperty=V.nil=V.strConcat=V.str=V._=void 0;var X=eo(),ut=gu(),Gt=eo();Object.defineProperty(V,"_",{enumerable:!0,get:function(){return Gt._}});Object.defineProperty(V,"str",{enumerable:!0,get:function(){return Gt.str}});Object.defineProperty(V,"strConcat",{enumerable:!0,get:function(){return Gt.strConcat}});Object.defineProperty(V,"nil",{enumerable:!0,get:function(){return Gt.nil}});Object.defineProperty(V,"getProperty",{enumerable:!0,get:function(){return Gt.getProperty}});Object.defineProperty(V,"stringify",{enumerable:!0,get:function(){return Gt.stringify}});Object.defineProperty(V,"regexpCode",{enumerable:!0,get:function(){return Gt.regexpCode}});Object.defineProperty(V,"Name",{enumerable:!0,get:function(){return Gt.Name}});var Zs=gu();Object.defineProperty(V,"Scope",{enumerable:!0,get:function(){return Zs.Scope}});Object.defineProperty(V,"ValueScope",{enumerable:!0,get:function(){return Zs.ValueScope}});Object.defineProperty(V,"ValueScopeName",{enumerable:!0,get:function(){return Zs.ValueScopeName}});Object.defineProperty(V,"varKinds",{enumerable:!0,get:function(){return Zs.varKinds}});V.operators={GT:new X._Code(">"),GTE:new X._Code(">="),LT:new X._Code("<"),LTE:new X._Code("<="),EQ:new X._Code("==="),NEQ:new X._Code("!=="),NOT:new X._Code("!"),OR:new X._Code("||"),AND:new X._Code("&&"),ADD:new X._Code("+")};var jt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},yu=class extends jt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?ut.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=an(this.rhs,t,r)),this}get names(){return this.rhs instanceof X._CodeOrName?this.rhs.names:{}}},Ns=class extends jt{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 X.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=an(this.rhs,t,r),this}get names(){let t=this.lhs instanceof X.Name?{}:{...this.lhs.names};return Ds(t,this.rhs)}},_u=class extends Ns{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},vu=class extends jt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},bu=class extends jt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},wu=class extends jt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},ku=class extends jt{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=an(this.code,t,r),this}get names(){return this.code instanceof X._CodeOrName?this.code.names:{}}},to=class extends jt{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,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(t,r)||(h0(t,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Er(t,r.names),{})}},Ct=class extends to{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},xu=class extends to{},sn=class extends Ct{};sn.kind="else";var Tr=class e extends Ct{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 sn(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Lf(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=an(this.condition,t,r),this}get names(){let t=super.names;return Ds(t,this.condition),this.else&&Er(t,this.else.names),t}};Tr.kind="if";var Rr=class extends Ct{};Rr.kind="for";var Su=class extends Rr{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=an(this.iteration,t,r),this}get names(){return Er(super.names,this.iteration.names)}},$u=class extends Rr{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?ut.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(t)}get names(){let t=Ds(super.names,this.from);return Ds(t,this.to)}},Ls=class extends Rr{constructor(t,r,n,o){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=o}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=an(this.iterable,t,r),this}get names(){return Er(super.names,this.iterable.names)}},ro=class extends Ct{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)}};ro.kind="func";var no=class extends to{render(t){return"return "+super.render(t)}};no.kind="return";var zu=class extends Ct{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,o;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(o=this.finally)===null||o===void 0||o.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Er(t,this.catch.names),this.finally&&Er(t,this.finally.names),t}},oo=class extends Ct{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};oo.kind="catch";var so=class extends Ct{render(t){return"finally"+super.render(t)}};so.kind="finally";var Pu=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
4
|
+
`:""},this._extScope=t,this._scope=new ut.Scope({parent:t}),this._nodes=[new xu]}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,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new yu(t,s,n)),s}const(t,r,n){return this._def(ut.varKinds.const,t,r,n)}let(t,r,n){return this._def(ut.varKinds.let,t,r,n)}var(t,r,n){return this._def(ut.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Ns(t,r,n))}add(t,r){return this._leafNode(new _u(t,V.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==X.nil&&this._leafNode(new ku(t)),this}object(...t){let r=["{"];for(let[n,o]of t)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,X.addCodeArg)(r,o));return r.push("}"),new X._Code(r)}if(t,r,n){if(this._blockNode(new Tr(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 Tr(t))}else(){return this._elseNode(new sn)}endIf(){return this._endBlockNode(Tr,sn)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Su(t),r)}forRange(t,r,n,o,s=this.opts.es5?ut.varKinds.var:ut.varKinds.let){let i=this._scope.toName(t);return this._for(new $u(s,i,r,n),()=>o(i))}forOf(t,r,n,o=ut.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let i=r instanceof X.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,X._)`${i}.length`,a=>{this.var(s,(0,X._)`${i}[${a}]`),n(s)})}return this._for(new Ls("of",o,s,r),()=>n(s))}forIn(t,r,n,o=this.opts.es5?ut.varKinds.var:ut.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,X._)`Object.keys(${r})`,n);let s=this._scope.toName(t);return this._for(new Ls("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Rr)}label(t){return this._leafNode(new vu(t))}break(t){return this._leafNode(new bu(t))}return(t){let r=new no;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(no)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new zu;if(this._blockNode(o),this.code(t),r){let s=this.name("e");this._currNode=o.catch=new oo(s),r(s)}return n&&(this._currNode=o.finally=new so,this.code(n)),this._endBlockNode(oo,so)}throw(t){return this._leafNode(new wu(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=X.nil,n,o){return this._blockNode(new ro(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ro)}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 Tr))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}};V.CodeGen=Pu;function Er(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Ds(e,t){return t instanceof X._CodeOrName?Er(e,t.names):e}function an(e,t,r){if(e instanceof X.Name)return n(e);if(!o(e))return e;return new X._Code(e._items.reduce((s,i)=>(i instanceof X.Name&&(i=n(i)),i instanceof X._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||t[s.str]!==1?s:(delete t[s.str],i)}function o(s){return s instanceof X._Code&&s._items.some(i=>i instanceof X.Name&&t[i.str]===1&&r[i.str]!==void 0)}}function h0(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Lf(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,X._)`!${Tu(e)}`}V.not=Lf;var g0=Df(V.operators.AND);function y0(...e){return e.reduce(g0)}V.and=y0;var _0=Df(V.operators.OR);function v0(...e){return e.reduce(_0)}V.or=v0;function Df(e){return(t,r)=>t===X.nil?r:r===X.nil?t:(0,X._)`${Tu(t)} ${e} ${Tu(r)}`}function Tu(e){return e instanceof X.Name?e:(0,X._)`(${e})`}});var ee=z(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.checkStrictMode=B.getErrorPath=B.Type=B.useFunc=B.setEvaluated=B.evaluatedPropsToName=B.mergeEvaluated=B.eachItem=B.unescapeJsonPointer=B.escapeJsonPointer=B.escapeFragment=B.unescapeFragment=B.schemaRefOrVal=B.schemaHasRulesButRef=B.schemaHasRules=B.checkUnknownRules=B.alwaysValidSchema=B.toHash=void 0;var se=F(),b0=eo();function w0(e){let t={};for(let r of e)t[r]=!0;return t}B.toHash=w0;function k0(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(qf(e,t),!Jf(t,e.self.RULES.all))}B.alwaysValidSchema=k0;function qf(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let s in t)o[s]||Bf(e,`unknown keyword: "${s}"`)}B.checkUnknownRules=qf;function Jf(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}B.schemaHasRules=Jf;function x0(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}B.schemaHasRulesButRef=x0;function S0({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,se._)`${r}`}return(0,se._)`${e}${t}${(0,se.getProperty)(n)}`}B.schemaRefOrVal=S0;function $0(e){return Ff(decodeURIComponent(e))}B.unescapeFragment=$0;function z0(e){return encodeURIComponent(Eu(e))}B.escapeFragment=z0;function Eu(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}B.escapeJsonPointer=Eu;function Ff(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}B.unescapeJsonPointer=Ff;function P0(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}B.eachItem=P0;function Zf({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof se.Name?(s instanceof se.Name?e(o,s,i):t(o,s,i),i):s instanceof se.Name?(t(o,i,s),s):r(s,i);return a===se.Name&&!(c instanceof se.Name)?n(o,c):c}}B.mergeEvaluated={props:Zf({mergeNames:(e,t,r)=>e.if((0,se._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,se._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,se._)`${r} || {}`).code((0,se._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,se._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,se._)`${r} || {}`),Iu(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Vf}),items:Zf({mergeNames:(e,t,r)=>e.if((0,se._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,se._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,se._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,se._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Vf(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,se._)`{}`);return t!==void 0&&Iu(e,r,t),r}B.evaluatedPropsToName=Vf;function Iu(e,t,r){Object.keys(r).forEach(n=>e.assign((0,se._)`${t}${(0,se.getProperty)(n)}`,!0))}B.setEvaluated=Iu;var Uf={};function T0(e,t){return e.scopeValue("func",{ref:t,code:Uf[t.code]||(Uf[t.code]=new b0._Code(t.code))})}B.useFunc=T0;var Ru;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Ru||(B.Type=Ru={}));function R0(e,t,r){if(e instanceof se.Name){let n=t===Ru.Num;return r?n?(0,se._)`"[" + ${e} + "]"`:(0,se._)`"['" + ${e} + "']"`:n?(0,se._)`"/" + ${e}`:(0,se._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,se.getProperty)(e).toString():"/"+Eu(e)}B.getErrorPath=R0;function Bf(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}B.checkStrictMode=Bf});var At=z(Ou=>{"use strict";Object.defineProperty(Ou,"__esModule",{value:!0});var Re=F(),E0={data:new Re.Name("data"),valCxt:new Re.Name("valCxt"),instancePath:new Re.Name("instancePath"),parentData:new Re.Name("parentData"),parentDataProperty:new Re.Name("parentDataProperty"),rootData:new Re.Name("rootData"),dynamicAnchors:new Re.Name("dynamicAnchors"),vErrors:new Re.Name("vErrors"),errors:new Re.Name("errors"),this:new Re.Name("this"),self:new Re.Name("self"),scope:new Re.Name("scope"),json:new Re.Name("json"),jsonPos:new Re.Name("jsonPos"),jsonLen:new Re.Name("jsonLen"),jsonPart:new Re.Name("jsonPart")};Ou.default=E0});var io=z(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.extendErrors=Ee.resetErrorsCount=Ee.reportExtraError=Ee.reportError=Ee.keyword$DataError=Ee.keywordError=void 0;var Y=F(),Us=ee(),Ae=At();Ee.keywordError={message:({keyword:e})=>(0,Y.str)`must pass "${e}" keyword validation`};Ee.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,Y.str)`"${e}" keyword must be ${t} ($data)`:(0,Y.str)`"${e}" keyword is invalid ($data)`};function I0(e,t=Ee.keywordError,r,n){let{it:o}=e,{gen:s,compositeRule:i,allErrors:a}=o,c=Gf(e,t,r);n??(i||a)?Hf(s,c):Wf(o,(0,Y._)`[${c}]`)}Ee.reportError=I0;function O0(e,t=Ee.keywordError,r){let{it:n}=e,{gen:o,compositeRule:s,allErrors:i}=n,a=Gf(e,t,r);Hf(o,a),s||i||Wf(n,Ae.default.vErrors)}Ee.reportExtraError=O0;function j0(e,t){e.assign(Ae.default.errors,t),e.if((0,Y._)`${Ae.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Y._)`${Ae.default.vErrors}.length`,t),()=>e.assign(Ae.default.vErrors,null)))}Ee.resetErrorsCount=j0;function C0({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=e.name("err");e.forRange("i",o,Ae.default.errors,a=>{e.const(i,(0,Y._)`${Ae.default.vErrors}[${a}]`),e.if((0,Y._)`${i}.instancePath === undefined`,()=>e.assign((0,Y._)`${i}.instancePath`,(0,Y.strConcat)(Ae.default.instancePath,s.errorPath))),e.assign((0,Y._)`${i}.schemaPath`,(0,Y.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,Y._)`${i}.schema`,r),e.assign((0,Y._)`${i}.data`,n))})}Ee.extendErrors=C0;function Hf(e,t){let r=e.const("err",t);e.if((0,Y._)`${Ae.default.vErrors} === null`,()=>e.assign(Ae.default.vErrors,(0,Y._)`[${r}]`),(0,Y._)`${Ae.default.vErrors}.push(${r})`),e.code((0,Y._)`${Ae.default.errors}++`)}function Wf(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,Y._)`new ${e.ValidationError}(${t})`):(r.assign((0,Y._)`${n}.errors`,t),r.return(!1))}var Ir={keyword:new Y.Name("keyword"),schemaPath:new Y.Name("schemaPath"),params:new Y.Name("params"),propertyName:new Y.Name("propertyName"),message:new Y.Name("message"),schema:new Y.Name("schema"),parentSchema:new Y.Name("parentSchema")};function Gf(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Y._)`{}`:A0(e,t,r)}function A0(e,t,r={}){let{gen:n,it:o}=e,s=[M0(o,r),N0(e,r)];return L0(e,t,s),n.object(...s)}function M0({errorPath:e},{instancePath:t}){let r=t?(0,Y.str)`${e}${(0,Us.getErrorPath)(t,Us.Type.Str)}`:e;return[Ae.default.instancePath,(0,Y.strConcat)(Ae.default.instancePath,r)]}function N0({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,Y.str)`${t}/${e}`;return r&&(o=(0,Y.str)`${o}${(0,Us.getErrorPath)(r,Us.Type.Str)}`),[Ir.schemaPath,o]}function L0(e,{params:t,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=e,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([Ir.keyword,o],[Ir.params,typeof t=="function"?t(e):t||(0,Y._)`{}`]),c.messages&&n.push([Ir.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Ir.schema,i],[Ir.parentSchema,(0,Y._)`${d}${l}`],[Ae.default.data,s]),u&&n.push([Ir.propertyName,u])}});var Xf=z(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.boolOrEmptySchema=cn.topBoolOrEmptySchema=void 0;var D0=io(),Z0=F(),U0=At(),q0={message:"boolean schema is false"};function J0(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Kf(e,!1):typeof r=="object"&&r.$async===!0?t.return(U0.default.data):(t.assign((0,Z0._)`${n}.errors`,null),t.return(!0))}cn.topBoolOrEmptySchema=J0;function F0(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Kf(e)):r.var(t,!0)}cn.boolOrEmptySchema=F0;function Kf(e,t){let{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,D0.reportError)(o,q0,void 0,t)}});var ju=z(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.getRules=un.isJSONType=void 0;var V0=["string","number","integer","boolean","null","object","array"],B0=new Set(V0);function H0(e){return typeof e=="string"&&B0.has(e)}un.isJSONType=H0;function W0(){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:{}}}un.getRules=W0});var Cu=z(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.shouldUseRule=Kt.shouldUseGroup=Kt.schemaHasRulesForType=void 0;function G0({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Yf(e,n)}Kt.schemaHasRulesForType=G0;function Yf(e,t){return t.rules.some(r=>Qf(e,r))}Kt.shouldUseGroup=Yf;function Qf(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))}Kt.shouldUseRule=Qf});var ao=z(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.reportTypeError=Ie.checkDataTypes=Ie.checkDataType=Ie.coerceAndCheckDataType=Ie.getJSONTypes=Ie.getSchemaTypes=Ie.DataType=void 0;var K0=ju(),X0=Cu(),Y0=io(),q=F(),eh=ee(),dn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(dn||(Ie.DataType=dn={}));function Q0(e){let t=th(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}Ie.getSchemaTypes=Q0;function th(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(K0.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Ie.getJSONTypes=th;function eS(e,t){let{gen:r,data:n,opts:o}=e,s=tS(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,X0.schemaHasRulesForType)(e,t[0]));if(i){let a=Mu(t,n,o.strictNumbers,dn.Wrong);r.if(a,()=>{s.length?rS(e,t,s):Nu(e)})}return i}Ie.coerceAndCheckDataType=eS;var rh=new Set(["string","number","integer","boolean","null"]);function tS(e,t){return t?e.filter(r=>rh.has(r)||t==="array"&&r==="array"):[]}function rS(e,t,r){let{gen:n,data:o,opts:s}=e,i=n.let("dataType",(0,q._)`typeof ${o}`),a=n.let("coerced",(0,q._)`undefined`);s.coerceTypes==="array"&&n.if((0,q._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,q._)`${o}[0]`).assign(i,(0,q._)`typeof ${o}`).if(Mu(t,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,q._)`${a} !== undefined`);for(let u of r)(rh.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Nu(e),n.endIf(),n.if((0,q._)`${a} !== undefined`,()=>{n.assign(o,a),nS(e,a)});function c(u){switch(u){case"string":n.elseIf((0,q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,q._)`"" + ${o}`).elseIf((0,q._)`${o} === null`).assign(a,(0,q._)`""`);return;case"number":n.elseIf((0,q._)`${i} == "boolean" || ${o} === null
|
|
5
|
+
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,q._)`+${o}`);return;case"integer":n.elseIf((0,q._)`${i} === "boolean" || ${o} === null
|
|
6
|
+
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,q._)`+${o}`);return;case"boolean":n.elseIf((0,q._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,q._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,q._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,q._)`${i} === "string" || ${i} === "number"
|
|
7
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,q._)`[${o}]`)}}}function nS({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,q._)`${t} !== undefined`,()=>e.assign((0,q._)`${t}[${r}]`,n))}function Au(e,t,r,n=dn.Correct){let o=n===dn.Correct?q.operators.EQ:q.operators.NEQ,s;switch(e){case"null":return(0,q._)`${t} ${o} null`;case"array":s=(0,q._)`Array.isArray(${t})`;break;case"object":s=(0,q._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,q._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,q._)`typeof ${t} ${o} ${e}`}return n===dn.Correct?s:(0,q.not)(s);function i(a=q.nil){return(0,q.and)((0,q._)`typeof ${t} == "number"`,a,r?(0,q._)`isFinite(${t})`:q.nil)}}Ie.checkDataType=Au;function Mu(e,t,r,n){if(e.length===1)return Au(e[0],t,r,n);let o,s=(0,eh.toHash)(e);if(s.array&&s.object){let i=(0,q._)`typeof ${t} != "object"`;o=s.null?i:(0,q._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=q.nil;s.number&&delete s.integer;for(let i in s)o=(0,q.and)(o,Au(i,t,r,n));return o}Ie.checkDataTypes=Mu;var oS={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,q._)`{type: ${e}}`:(0,q._)`{type: ${t}}`};function Nu(e){let t=sS(e);(0,Y0.reportError)(t,oS)}Ie.reportTypeError=Nu;function sS(e){let{gen:t,data:r,schema:n}=e,o=(0,eh.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var oh=z(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.assignDefaults=void 0;var ln=F(),iS=ee();function aS(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)nh(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,s)=>nh(e,s,o.default))}qs.assignDefaults=aS;function nh(e,t,r){let{gen:n,compositeRule:o,data:s,opts:i}=e;if(r===void 0)return;let a=(0,ln._)`${s}${(0,ln.getProperty)(t)}`;if(o){(0,iS.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,ln._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,ln._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,ln._)`${a} = ${(0,ln.stringify)(r)}`)}});var rt=z(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.validateUnion=oe.validateArray=oe.usePattern=oe.callValidateCode=oe.schemaProperties=oe.allSchemaProperties=oe.noPropertyInData=oe.propertyInData=oe.isOwnProperty=oe.hasPropFunc=oe.reportMissingProp=oe.checkMissingProp=oe.checkReportMissingProp=void 0;var de=F(),Lu=ee(),Xt=At(),cS=ee();function uS(e,t){let{gen:r,data:n,it:o}=e;r.if(Zu(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,de._)`${t}`},!0),e.error()})}oe.checkReportMissingProp=uS;function dS({gen:e,data:t,it:{opts:r}},n,o){return(0,de.or)(...n.map(s=>(0,de.and)(Zu(e,t,s,r.ownProperties),(0,de._)`${o} = ${s}`)))}oe.checkMissingProp=dS;function lS(e,t){e.setParams({missingProperty:t},!0),e.error()}oe.reportMissingProp=lS;function sh(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,de._)`Object.prototype.hasOwnProperty`})}oe.hasPropFunc=sh;function Du(e,t,r){return(0,de._)`${sh(e)}.call(${t}, ${r})`}oe.isOwnProperty=Du;function pS(e,t,r,n){let o=(0,de._)`${t}${(0,de.getProperty)(r)} !== undefined`;return n?(0,de._)`${o} && ${Du(e,t,r)}`:o}oe.propertyInData=pS;function Zu(e,t,r,n){let o=(0,de._)`${t}${(0,de.getProperty)(r)} === undefined`;return n?(0,de.or)(o,(0,de.not)(Du(e,t,r))):o}oe.noPropertyInData=Zu;function ih(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}oe.allSchemaProperties=ih;function mS(e,t){return ih(t).filter(r=>!(0,Lu.alwaysValidSchema)(e,t[r]))}oe.schemaProperties=mS;function fS({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let d=u?(0,de._)`${e}, ${t}, ${n}${o}`:t,l=[[Xt.default.instancePath,(0,de.strConcat)(Xt.default.instancePath,s)],[Xt.default.parentData,i.parentData],[Xt.default.parentDataProperty,i.parentDataProperty],[Xt.default.rootData,Xt.default.rootData]];i.opts.dynamicRef&&l.push([Xt.default.dynamicAnchors,Xt.default.dynamicAnchors]);let p=(0,de._)`${d}, ${r.object(...l)}`;return c!==de.nil?(0,de._)`${a}.call(${c}, ${p})`:(0,de._)`${a}(${p})`}oe.callValidateCode=fS;var hS=(0,de._)`new RegExp`;function gS({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(r,n);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,de._)`${o.code==="new RegExp"?hS:(0,cS.useFunc)(e,o)}(${r}, ${n})`})}oe.usePattern=gS;function yS(e){let{gen:t,data:r,keyword:n,it:o}=e,s=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){let c=t.const("len",(0,de._)`${r}.length`);t.forRange("i",0,c,u=>{e.subschema({keyword:n,dataProp:u,dataPropType:Lu.Type.Num},s),t.if((0,de.not)(s),a)})}}oe.validateArray=yS;function _S(e){let{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Lu.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,u)=>{let d=e.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);t.assign(i,(0,de._)`${i} || ${a}`),e.mergeValidEvaluated(d,a)||t.if((0,de.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}oe.validateUnion=_S});var uh=z(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.validateKeywordUsage=vt.validSchemaType=vt.funcKeywordCode=vt.macroKeywordCode=void 0;var Me=F(),Or=At(),vS=rt(),bS=io();function wS(e,t){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),c=ch(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");e.subschema({schema:a,schemaPath:Me.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}vt.macroKeywordCode=wS;function kS(e,t){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=e;SS(c,t);let u=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,d=ch(n,o,u),l=n.let("valid");e.block$data(l,p),e.ok((r=t.valid)!==null&&r!==void 0?r:l);function p(){if(t.errors===!1)g(),t.modifying&&ah(e),y(()=>e.error());else{let b=t.async?h():f();t.modifying&&ah(e),y(()=>xS(e,b))}}function h(){let b=n.let("ruleErrs",null);return n.try(()=>g((0,Me._)`await `),w=>n.assign(l,!1).if((0,Me._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(b,(0,Me._)`${w}.errors`),()=>n.throw(w))),b}function f(){let b=(0,Me._)`${d}.errors`;return n.assign(b,null),g(Me.nil),b}function g(b=t.async?(0,Me._)`await `:Me.nil){let w=c.opts.passContext?Or.default.this:Or.default.self,k=!("compile"in t&&!a||t.schema===!1);n.assign(l,(0,Me._)`${b}${(0,vS.callValidateCode)(e,d,w,k)}`,t.modifying)}function y(b){var w;n.if((0,Me.not)((w=t.valid)!==null&&w!==void 0?w:l),b)}}vt.funcKeywordCode=kS;function ah(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Me._)`${n.parentData}[${n.parentDataProperty}]`))}function xS(e,t){let{gen:r}=e;r.if((0,Me._)`Array.isArray(${t})`,()=>{r.assign(Or.default.vErrors,(0,Me._)`${Or.default.vErrors} === null ? ${t} : ${Or.default.vErrors}.concat(${t})`).assign(Or.default.errors,(0,Me._)`${Or.default.vErrors}.length`),(0,bS.extendErrors)(e)},()=>e.error())}function SS({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function ch(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,Me.stringify)(r)})}function $S(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")}vt.validSchemaType=$S;function zS({schema:e,opts:t,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}vt.validateKeywordUsage=zS});var lh=z(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.extendSubschemaMode=Yt.extendSubschemaData=Yt.getSubschema=void 0;var bt=F(),dh=ee();function PS(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){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,bt._)`${e.schemaPath}${(0,bt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,bt._)`${e.schemaPath}${(0,bt.getProperty)(t)}${(0,bt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,dh.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Yt.getSubschema=PS;function TS(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==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:u,dataPathArr:d,opts:l}=t,p=a.let("data",(0,bt._)`${t.data}${(0,bt.getProperty)(r)}`,!0);c(p),e.errorPath=(0,bt.str)`${u}${(0,dh.getErrorPath)(r,n,l.jsPropertySyntax)}`,e.parentDataProperty=(0,bt._)`${r}`,e.dataPathArr=[...d,e.parentDataProperty]}if(o!==void 0){let u=o instanceof bt.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function c(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}Yt.extendSubschemaData=TS;function RS(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r}Yt.extendSubschemaMode=RS});var Uu=z((Z2,ph)=>{"use strict";ph.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,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r}});var fh=z((U2,mh)=>{"use strict";var Qt=mh.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Js(t,n,o,e,"",e)};Qt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Qt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Qt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Qt.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 Js(e,t,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,s,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in Qt.arrayKeywords)for(var p=0;p<l.length;p++)Js(e,t,r,l[p],o+"/"+d+"/"+p,s,o,d,n,p)}else if(d in Qt.propsKeywords){if(l&&typeof l=="object")for(var h in l)Js(e,t,r,l[h],o+"/"+d+"/"+ES(h),s,o,d,n,h)}else(d in Qt.keywords||e.allKeys&&!(d in Qt.skipKeywords))&&Js(e,t,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function ES(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var co=z(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.getSchemaRefs=Je.resolveUrl=Je.normalizeId=Je._getFullPath=Je.getFullPath=Je.inlineRef=void 0;var IS=ee(),OS=Uu(),jS=fh(),CS=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function AS(e,t=!0){return typeof e=="boolean"?!0:t===!0?!qu(e):t?hh(e)<=t:!1}Je.inlineRef=AS;var MS=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function qu(e){for(let t in e){if(MS.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(qu)||typeof r=="object"&&qu(r))return!0}return!1}function hh(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!CS.has(r)&&(typeof e[r]=="object"&&(0,IS.eachItem)(e[r],n=>t+=hh(n)),t===1/0))return 1/0}return t}function gh(e,t="",r){r!==!1&&(t=pn(t));let n=e.parse(t);return yh(e,n)}Je.getFullPath=gh;function yh(e,t){return e.serialize(t).split("#")[0]+"#"}Je._getFullPath=yh;var NS=/#\/?$/;function pn(e){return e?e.replace(NS,""):""}Je.normalizeId=pn;function LS(e,t,r){return r=pn(r),e.resolve(t,r)}Je.resolveUrl=LS;var DS=/^[a-z_][-a-z0-9._]*$/i;function ZS(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=pn(e[r]||t),s={"":o},i=gh(n,o,!1),a={},c=new Set;return jS(e,{allKeys:!0},(l,p,h,f)=>{if(f===void 0)return;let g=i+p,y=s[f];typeof l[r]=="string"&&(y=b.call(this,l[r])),w.call(this,l.$anchor),w.call(this,l.$dynamicAnchor),s[p]=y;function b(k){let R=this.opts.uriResolver.resolve;if(k=pn(y?R(y,k):k),c.has(k))throw d(k);c.add(k);let M=this.refs[k];return typeof M=="string"&&(M=this.refs[M]),typeof M=="object"?u(l,M.schema,k):k!==pn(g)&&(k[0]==="#"?(u(l,a[k],k),a[k]=l):this.refs[k]=g),k}function w(k){if(typeof k=="string"){if(!DS.test(k))throw new Error(`invalid anchor "${k}"`);b.call(this,`#${k}`)}}}),a;function u(l,p,h){if(p!==void 0&&!OS(l,p))throw d(h)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Je.getSchemaRefs=ZS});var po=z(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.getData=er.KeywordCxt=er.validateFunctionCode=void 0;var kh=Xf(),_h=ao(),Fu=Cu(),Fs=ao(),US=oh(),lo=uh(),Ju=lh(),C=F(),Z=At(),qS=co(),Mt=ee(),uo=io();function JS(e){if($h(e)&&(zh(e),Sh(e))){BS(e);return}xh(e,()=>(0,kh.topBoolOrEmptySchema)(e))}er.validateFunctionCode=JS;function xh({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},s){o.code.es5?e.func(t,(0,C._)`${Z.default.data}, ${Z.default.valCxt}`,n.$async,()=>{e.code((0,C._)`"use strict"; ${vh(r,o)}`),VS(e,o),e.code(s)}):e.func(t,(0,C._)`${Z.default.data}, ${FS(o)}`,n.$async,()=>e.code(vh(r,o)).code(s))}function FS(e){return(0,C._)`{${Z.default.instancePath}="", ${Z.default.parentData}, ${Z.default.parentDataProperty}, ${Z.default.rootData}=${Z.default.data}${e.dynamicRef?(0,C._)`, ${Z.default.dynamicAnchors}={}`:C.nil}}={}`}function VS(e,t){e.if(Z.default.valCxt,()=>{e.var(Z.default.instancePath,(0,C._)`${Z.default.valCxt}.${Z.default.instancePath}`),e.var(Z.default.parentData,(0,C._)`${Z.default.valCxt}.${Z.default.parentData}`),e.var(Z.default.parentDataProperty,(0,C._)`${Z.default.valCxt}.${Z.default.parentDataProperty}`),e.var(Z.default.rootData,(0,C._)`${Z.default.valCxt}.${Z.default.rootData}`),t.dynamicRef&&e.var(Z.default.dynamicAnchors,(0,C._)`${Z.default.valCxt}.${Z.default.dynamicAnchors}`)},()=>{e.var(Z.default.instancePath,(0,C._)`""`),e.var(Z.default.parentData,(0,C._)`undefined`),e.var(Z.default.parentDataProperty,(0,C._)`undefined`),e.var(Z.default.rootData,Z.default.data),t.dynamicRef&&e.var(Z.default.dynamicAnchors,(0,C._)`{}`)})}function BS(e){let{schema:t,opts:r,gen:n}=e;xh(e,()=>{r.$comment&&t.$comment&&Th(e),XS(e),n.let(Z.default.vErrors,null),n.let(Z.default.errors,0),r.unevaluated&&HS(e),Ph(e),e$(e)})}function HS(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,C._)`${r}.evaluated`),t.if((0,C._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,C._)`${e.evaluated}.props`,(0,C._)`undefined`)),t.if((0,C._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,C._)`${e.evaluated}.items`,(0,C._)`undefined`))}function vh(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,C._)`/*# sourceURL=${r} */`:C.nil}function WS(e,t){if($h(e)&&(zh(e),Sh(e))){GS(e,t);return}(0,kh.boolOrEmptySchema)(e,t)}function Sh({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 $h(e){return typeof e.schema!="boolean"}function GS(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&Th(e),YS(e),QS(e);let s=n.const("_errs",Z.default.errors);Ph(e,s),n.var(t,(0,C._)`${s} === ${Z.default.errors}`)}function zh(e){(0,Mt.checkUnknownRules)(e),KS(e)}function Ph(e,t){if(e.opts.jtd)return bh(e,[],!1,t);let r=(0,_h.getSchemaTypes)(e.schema),n=(0,_h.coerceAndCheckDataType)(e,r);bh(e,r,!n,t)}function KS(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Mt.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function XS(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Mt.checkStrictMode)(e,"default is ignored in the schema root")}function YS(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,qS.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function QS(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function Th({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)e.code((0,C._)`${Z.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,C.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,C._)`${Z.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function e$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=e;r.$async?t.if((0,C._)`${Z.default.errors} === 0`,()=>t.return(Z.default.data),()=>t.throw((0,C._)`new ${o}(${Z.default.vErrors})`)):(t.assign((0,C._)`${n}.errors`,Z.default.vErrors),s.unevaluated&&t$(e),t.return((0,C._)`${Z.default.errors} === 0`))}function t$({gen:e,evaluated:t,props:r,items:n}){r instanceof C.Name&&e.assign((0,C._)`${t}.props`,r),n instanceof C.Name&&e.assign((0,C._)`${t}.items`,n)}function bh(e,t,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=e,{RULES:d}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Mt.schemaHasRulesButRef)(s,d))){o.block(()=>Eh(e,"$ref",d.all.$ref.definition));return}c.jtd||r$(e,t),o.block(()=>{for(let p of d.rules)l(p);l(d.post)});function l(p){(0,Fu.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Fs.checkDataType)(p.type,i,c.strictNumbers)),wh(e,p),t.length===1&&t[0]===p.type&&r&&(o.else(),(0,Fs.reportTypeError)(e)),o.endIf()):wh(e,p),a||o.if((0,C._)`${Z.default.errors} === ${n||0}`))}}function wh(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,US.assignDefaults)(e,t.type),r.block(()=>{for(let s of t.rules)(0,Fu.shouldUseRule)(n,s)&&Eh(e,s.keyword,s.definition,t.type)})}function r$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(n$(e,t),e.opts.allowUnionTypes||o$(e,t),s$(e,e.dataTypes))}function n$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Rh(e.dataTypes,r)||Vu(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),a$(e,t)}}function o$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Vu(e,"use allowUnionTypes to allow union type keyword")}function s$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Fu.shouldUseRule)(e.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>i$(t,i))&&Vu(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function i$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Rh(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function a$(e,t){let r=[];for(let n of e.dataTypes)Rh(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Vu(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Mt.checkStrictMode)(e,t,e.opts.strictTypes)}var Vs=class{constructor(t,r,n){if((0,lo.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,Mt.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",Ih(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,lo.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",Z.default.errors))}result(t,r,n){this.failResult((0,C.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,C.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,C._)`${r} !== undefined && (${(0,C.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?uo.reportExtraError:uo.reportError)(this,this.def.error,r)}$dataError(){(0,uo.reportError)(this,this.def.$dataError||uo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,uo.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=C.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=C.nil,r=C.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,C.or)((0,C._)`${o} === undefined`,r)),t!==C.nil&&n.assign(t,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==C.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,C.or)(i(),a());function i(){if(n.length){if(!(r instanceof C.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,C._)`${(0,Fs.checkDataTypes)(c,r,s.opts.strictNumbers,Fs.DataType.Wrong)}`}return C.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,C._)`!${c}(${r})`}return C.nil}}subschema(t,r){let n=(0,Ju.getSubschema)(this.it,t);(0,Ju.extendSubschemaData)(n,this.it,t),(0,Ju.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return WS(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Mt.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Mt.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,C.Name)),!0}};er.KeywordCxt=Vs;function Eh(e,t,r,n){let o=new Vs(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,lo.funcKeywordCode)(o,r):"macro"in r?(0,lo.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,lo.funcKeywordCode)(o,r)}var c$=/^\/(?:[^~]|~0|~1)*$/,u$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ih(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,s;if(e==="")return Z.default.rootData;if(e[0]==="/"){if(!c$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=Z.default.rootData}else{let u=u$.exec(e);if(!u)throw new Error(`Invalid JSON-pointer: ${e}`);let d=+u[1];if(o=u[2],o==="#"){if(d>=t)throw new Error(c("property/index",d));return n[t-d]}if(d>t)throw new Error(c("data",d));if(s=r[t-d],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,C._)`${s}${(0,C.getProperty)((0,Mt.unescapeJsonPointer)(u))}`,i=(0,C._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${t}`}}er.getData=Ih});var Bs=z(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});var Bu=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Hu.default=Bu});var mo=z(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var Wu=co(),Gu=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Wu.resolveUrl)(t,r,n),this.missingSchema=(0,Wu.normalizeId)((0,Wu.getFullPath)(t,this.missingRef))}};Ku.default=Gu});var Ws=z(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.resolveSchema=nt.getCompilingSchema=nt.resolveRef=nt.compileSchema=nt.SchemaEnv=void 0;var dt=F(),d$=Bs(),jr=At(),lt=co(),Oh=ee(),l$=po(),mn=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,lt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};nt.SchemaEnv=mn;function Yu(e){let t=jh.call(this,e);if(t)return t;let r=(0,lt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new dt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;e.$async&&(a=i.scopeValue("Error",{ref:d$.default,code:(0,dt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");e.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:jr.default.data,parentData:jr.default.parentData,parentDataProperty:jr.default.parentDataProperty,dataNames:[jr.default.data],dataPathArr:[dt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,dt.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:dt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,dt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(e),(0,l$.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(jr.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,e));let h=new Function(`${jr.default.self}`,`${jr.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=e.schema,h.schemaEnv=e,e.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:g}=u;h.evaluated={props:f instanceof dt.Name?void 0:f,items:g instanceof dt.Name?void 0:g,dynamicProps:f instanceof dt.Name,dynamicItems:g instanceof dt.Name},h.source&&(h.source.evaluated=(0,dt.stringify)(h.evaluated))}return e.validate=h,e}catch(l){throw delete e.validate,delete e.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(e)}}nt.compileSchema=Yu;function p$(e,t,r){var n;r=(0,lt.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let s=h$.call(this,e,r);if(s===void 0){let i=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new mn({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[r]=m$.call(this,s)}nt.resolveRef=p$;function m$(e){return(0,lt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Yu.call(this,e)}function jh(e){for(let t of this._compilations)if(f$(t,e))return t}nt.getCompilingSchema=jh;function f$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function h$(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Hs.call(this,e,t)}function Hs(e,t){let r=this.opts.uriResolver.parse(t),n=(0,lt._getFullPath)(this.opts.uriResolver,r),o=(0,lt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Xu.call(this,r,e);let s=(0,lt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Hs.call(this,e,i);return typeof a?.schema!="object"?void 0:Xu.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Yu.call(this,i),s===(0,lt.normalizeId)(t)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,lt.resolveUrl)(this.opts.uriResolver,o,u)),new mn({schema:a,schemaId:c,root:e,baseId:o})}return Xu.call(this,r,i)}}nt.resolveSchema=Hs;var g$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Xu(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Oh.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!g$.has(a)&&u&&(t=(0,lt.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Oh.schemaHasRulesButRef)(r,this.RULES)){let a=(0,lt.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=Hs.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new mn({schema:r,schemaId:i,root:n,baseId:t}),s.schema!==s.root.schema)return s}});var Ch=z((H2,y$)=>{y$.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 ed=z((W2,Lh)=>{"use strict";var _$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Mh=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 Qu(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 v$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ah(e){return e.length=0,!0}function b$(e,t,r){if(e.length){let n=Qu(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function w$(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=b$;for(let c=0;c<e.length;c++){let u=e[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=Ah}else{o.push(u);continue}}return o.length&&(a===Ah?r.zone=o.join(""):i?n.push(o.join("")):n.push(Qu(o))),r.address=n.join(""),r}function Nh(e){if(k$(e,":")<2)return{host:e,isIPV6:!1};let t=w$(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 k$(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function x$(e){let t=e,r=[],n=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(o===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(o===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 S$(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 $$(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Mh(r)){let n=Nh(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}Lh.exports={nonSimpleDomain:v$,recomposeAuthority:$$,normalizeComponentEncoding:S$,removeDotSegments:x$,isIPv4:Mh,isUUID:_$,normalizeIPv6:Nh,stringArrayToHexStripped:Qu}});var Jh=z((G2,qh)=>{"use strict";var{isUUID:z$}=ed(),P$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,T$=["http","https","ws","wss","urn","urn:uuid"];function R$(e){return T$.indexOf(e)!==-1}function td(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 Dh(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Zh(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 E$(e){return e.secure=td(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function I$(e){if((e.port===(td(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 O$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(P$);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let o=`${n}:${t.nid||e.nid}`,s=rd(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function j$(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(),o=`${r}:${t.nid||n}`,s=rd(o);s&&(e=s.serialize(e,t));let i=e,a=e.nss;return i.path=`${n||t.nid}:${a}`,t.skipEscape=!0,i}function C$(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!z$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function A$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Uh={scheme:"http",domainHost:!0,parse:Dh,serialize:Zh},M$={scheme:"https",domainHost:Uh.domainHost,parse:Dh,serialize:Zh},Gs={scheme:"ws",domainHost:!0,parse:E$,serialize:I$},N$={scheme:"wss",domainHost:Gs.domainHost,parse:Gs.parse,serialize:Gs.serialize},L$={scheme:"urn",parse:O$,serialize:j$,skipNormalize:!0},D$={scheme:"urn:uuid",parse:C$,serialize:A$,skipNormalize:!0},Ks={http:Uh,https:M$,ws:Gs,wss:N$,urn:L$,"urn:uuid":D$};Object.setPrototypeOf(Ks,null);function rd(e){return e&&(Ks[e]||Ks[e.toLowerCase()])||void 0}qh.exports={wsIsSecure:td,SCHEMES:Ks,isValidSchemeName:R$,getSchemeHandler:rd}});var Bh=z((K2,Ys)=>{"use strict";var{normalizeIPv6:Z$,removeDotSegments:fo,recomposeAuthority:U$,normalizeComponentEncoding:Xs,isIPv4:q$,nonSimpleDomain:J$}=ed(),{SCHEMES:F$,getSchemeHandler:Fh}=Jh();function V$(e,t){return typeof e=="string"?e=wt(Nt(e,t),t):typeof e=="object"&&(e=Nt(wt(e,t),t)),e}function B$(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Vh(Nt(e,n),Nt(t,n),n,!0);return n.skipEscape=!0,wt(o,n)}function Vh(e,t,r,n){let o={};return n||(e=Nt(wt(e,r),r),t=Nt(wt(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=fo(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=fo(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=fo(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=fo(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function H$(e,t,r){return typeof e=="string"?(e=unescape(e),e=wt(Xs(Nt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=wt(Xs(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=wt(Xs(Nt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=wt(Xs(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function wt(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),o=[],s=Fh(n.scheme||r.scheme);s&&s.serialize&&s.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&&o.push(r.scheme,":");let i=U$(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=fo(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var W$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Nt(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},o=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let s=e.match(W$);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(q$(n.host)===!1){let c=Z$(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!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 i=Fh(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&J$(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}(!i||i&&!i.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)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var nd={SCHEMES:F$,normalize:V$,resolve:B$,resolveComponent:Vh,equal:H$,serialize:wt,parse:Nt};Ys.exports=nd;Ys.exports.default=nd;Ys.exports.fastUri=nd});var Wh=z(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var Hh=Bh();Hh.code='require("ajv/dist/runtime/uri").default';od.default=Hh});var rg=z(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.CodeGen=ze.Name=ze.nil=ze.stringify=ze.str=ze._=ze.KeywordCxt=void 0;var G$=po();Object.defineProperty(ze,"KeywordCxt",{enumerable:!0,get:function(){return G$.KeywordCxt}});var fn=F();Object.defineProperty(ze,"_",{enumerable:!0,get:function(){return fn._}});Object.defineProperty(ze,"str",{enumerable:!0,get:function(){return fn.str}});Object.defineProperty(ze,"stringify",{enumerable:!0,get:function(){return fn.stringify}});Object.defineProperty(ze,"nil",{enumerable:!0,get:function(){return fn.nil}});Object.defineProperty(ze,"Name",{enumerable:!0,get:function(){return fn.Name}});Object.defineProperty(ze,"CodeGen",{enumerable:!0,get:function(){return fn.CodeGen}});var K$=Bs(),Qh=mo(),X$=ju(),ho=Ws(),Y$=F(),go=co(),Qs=ao(),id=ee(),Gh=Ch(),Q$=Wh(),eg=(e,t)=>new RegExp(e,t);eg.code="new RegExp";var ez=["removeAdditional","useDefaults","coerceTypes"],tz=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),rz={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."},nz={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Kh=200;function oz(e){var t,r,n,o,s,i,a,c,u,d,l,p,h,f,g,y,b,w,k,R,M,Oe,Ge,Dr,Ti;let xn=e.strict,Ri=(t=e.code)===null||t===void 0?void 0:t.optimize,Nl=Ri===!0||Ri===void 0?1:Ri||0,Ll=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:eg,rv=(o=e.uriResolver)!==null&&o!==void 0?o:Q$.default;return{strictSchema:(i=(s=e.strictSchema)!==null&&s!==void 0?s:xn)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:xn)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=e.strictTypes)!==null&&u!==void 0?u:xn)!==null&&d!==void 0?d:"log",strictTuples:(p=(l=e.strictTuples)!==null&&l!==void 0?l:xn)!==null&&p!==void 0?p:"log",strictRequired:(f=(h=e.strictRequired)!==null&&h!==void 0?h:xn)!==null&&f!==void 0?f:!1,code:e.code?{...e.code,optimize:Nl,regExp:Ll}:{optimize:Nl,regExp:Ll},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:Kh,loopEnum:(y=e.loopEnum)!==null&&y!==void 0?y:Kh,meta:(b=e.meta)!==null&&b!==void 0?b:!0,messages:(w=e.messages)!==null&&w!==void 0?w:!0,inlineRefs:(k=e.inlineRefs)!==null&&k!==void 0?k:!0,schemaId:(R=e.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(M=e.addUsedSchema)!==null&&M!==void 0?M:!0,validateSchema:(Oe=e.validateSchema)!==null&&Oe!==void 0?Oe:!0,validateFormats:(Ge=e.validateFormats)!==null&&Ge!==void 0?Ge:!0,unicodeRegExp:(Dr=e.unicodeRegExp)!==null&&Dr!==void 0?Dr:!0,int32range:(Ti=e.int32range)!==null&&Ti!==void 0?Ti:!0,uriResolver:rv}}var yo=class{constructor(t={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...oz(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new Y$.ValueScope({scope:{},prefixes:tz,es5:r,lines:n}),this.logger=dz(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,X$.getRules)(),Xh.call(this,rz,t,"NOT SUPPORTED"),Xh.call(this,nz,t,"DEPRECATED","warn"),this._metaOpts=cz.call(this),t.formats&&iz.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&az.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),sz.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=Gh;n==="id"&&(o={...Gh},o.id=o.$id,delete o.$id),r&&t&&this.addMetaSchema(o,o[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 o=n(r);return"$async"in n||(this.errors=n.errors),o}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 o.call(this,t,r);async function o(d,l){await s.call(this,d.$schema);let p=this._addSchema(d,l);return p.validate||i.call(this,p)}async function s(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof Qh.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await s.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(t,r,n,o=this.opts.validateSchema){if(Array.isArray(t)){for(let i of t)this.addSchema(i,void 0,n,o);return this}let s;if(typeof t=="object"){let{schemaId:i}=this.opts;if(s=t[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,go.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,o,!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 o=this.validate(n,t);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(t){let r;for(;typeof(r=Yh.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ho.SchemaEnv({schema:{},schemaId:n});if(r=ho.resolveSchema.call(this,o,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=Yh.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,go.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(pz.call(this,n,r),!r)return(0,id.eachItem)(n,s=>sd.call(this,s)),this;fz.call(this,r);let o={...r,type:(0,Qs.getJSONTypes)(r.type),schemaType:(0,Qs.getJSONTypes)(r.schemaType)};return(0,id.eachItem)(n,o.type.length===0?s=>sd.call(this,s,o):s=>o.type.forEach(i=>sd.call(this,s,o,i))),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 o=n.rules.findIndex(s=>s.keyword===t);o>=0&&n.rules.splice(o,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(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let s=o.split("/").slice(1),i=t;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,d=i[a];u&&d&&(i[a]=tg(d))}}return t}_removeAllSchemas(t,r){for(let n in t){let o=t[n];(!r||r.test(n))&&(typeof o=="string"?delete t[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete t[n]))}}_addSchema(t,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof t=="object")i=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 c=this._cache.get(t);if(c!==void 0)return c;n=(0,go.normalizeId)(i||n);let u=go.getSchemaRefs.call(this,t,n);return c=new ho.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(t,!0),c}_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):ho.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{ho.compileSchema.call(this,t)}finally{this.opts=r}}};yo.ValidationError=K$.default;yo.MissingRefError=Qh.default;ze.default=yo;function Xh(e,t,r,n="error"){for(let o in e){let s=o;s in t&&this.logger[n](`${r}: option ${o}. ${e[s]}`)}}function Yh(e){return e=(0,go.normalizeId)(e),this.schemas[e]||this.refs[e]}function sz(){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 iz(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function az(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 cz(){let e={...this.opts};for(let t of ez)delete e[t];return e}var uz={log(){},warn(){},error(){}};function dz(e){if(e===!1)return uz;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 lz=/^[a-z_$][a-z0-9_$:-]*$/i;function pz(e,t){let{RULES:r}=this;if((0,id.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!lz.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 sd(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Qs.getJSONTypes)(t.type),schemaType:(0,Qs.getJSONTypes)(t.schemaType)}};t.before?mz.call(this,i,a,t.before):i.rules.push(a),s.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function mz(e,t,r){let n=e.rules.findIndex(o=>o.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function fz(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=tg(t)),e.validateSchema=this.compile(t,!0))}var hz={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function tg(e){return{anyOf:[e,hz]}}});var ng=z(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var gz={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ad.default=gz});var ag=z(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.callRef=Cr.getValidate=void 0;var yz=mo(),og=rt(),Fe=F(),hn=At(),sg=Ws(),ei=ee(),_z={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return l();let d=sg.resolveRef.call(c,u,o,r);if(d===void 0)throw new yz.default(n.opts.uriResolver,o,r);if(d instanceof sg.SchemaEnv)return p(d);return h(d);function l(){if(s===u)return ti(e,i,s,s.$async);let f=t.scopeValue("root",{ref:u});return ti(e,(0,Fe._)`${f}.validate`,u,u.$async)}function p(f){let g=ig(e,f);ti(e,g,f,f.$async)}function h(f){let g=t.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,Fe.stringify)(f)}:{ref:f}),y=t.name("valid"),b=e.subschema({schema:f,dataTypes:[],schemaPath:Fe.nil,topSchemaRef:g,errSchemaPath:r},y);e.mergeEvaluated(b),e.ok(y)}}};function ig(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Fe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Cr.getValidate=ig;function ti(e,t,r,n){let{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?hn.default.this:Fe.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,Fe._)`await ${(0,og.callValidateCode)(e,t,u)}`),h(t),i||o.assign(f,!0)},g=>{o.if((0,Fe._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(f,!1)}),e.ok(f)}function l(){e.result((0,og.callValidateCode)(e,t,u),()=>h(t),()=>p(t))}function p(f){let g=(0,Fe._)`${f}.errors`;o.assign(hn.default.vErrors,(0,Fe._)`${hn.default.vErrors} === null ? ${g} : ${hn.default.vErrors}.concat(${g})`),o.assign(hn.default.errors,(0,Fe._)`${hn.default.vErrors}.length`)}function h(f){var g;if(!s.opts.unevaluated)return;let y=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=ei.mergeEvaluated.props(o,y.props,s.props));else{let b=o.var("props",(0,Fe._)`${f}.evaluated.props`);s.props=ei.mergeEvaluated.props(o,b,s.props,Fe.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=ei.mergeEvaluated.items(o,y.items,s.items));else{let b=o.var("items",(0,Fe._)`${f}.evaluated.items`);s.items=ei.mergeEvaluated.items(o,b,s.items,Fe.Name)}}}Cr.callRef=ti;Cr.default=_z});var cg=z(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});var vz=ng(),bz=ag(),wz=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",vz.default,bz.default];cd.default=wz});var ug=z(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var ri=F(),tr=ri.operators,ni={maximum:{okStr:"<=",ok:tr.LTE,fail:tr.GT},minimum:{okStr:">=",ok:tr.GTE,fail:tr.LT},exclusiveMaximum:{okStr:"<",ok:tr.LT,fail:tr.GTE},exclusiveMinimum:{okStr:">",ok:tr.GT,fail:tr.LTE}},kz={message:({keyword:e,schemaCode:t})=>(0,ri.str)`must be ${ni[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,ri._)`{comparison: ${ni[e].okStr}, limit: ${t}}`},xz={keyword:Object.keys(ni),type:"number",schemaType:"number",$data:!0,error:kz,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,ri._)`${r} ${ni[t].fail} ${n} || isNaN(${r})`)}};ud.default=xz});var dg=z(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var _o=F(),Sz={message:({schemaCode:e})=>(0,_o.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,_o._)`{multipleOf: ${e}}`},$z={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Sz,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,_o._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,_o._)`${i} !== parseInt(${i})`;e.fail$data((0,_o._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};dd.default=$z});var pg=z(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});function lg(e){let t=e.length,r=0,n=0,o;for(;n<t;)r++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<t&&(o=e.charCodeAt(n),(o&64512)===56320&&n++);return r}ld.default=lg;lg.code='require("ajv/dist/runtime/ucs2length").default'});var mg=z(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var Ar=F(),zz=ee(),Pz=pg(),Tz={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Ar.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Ar._)`{limit: ${e}}`},Rz={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Tz,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,s=t==="maxLength"?Ar.operators.GT:Ar.operators.LT,i=o.opts.unicode===!1?(0,Ar._)`${r}.length`:(0,Ar._)`${(0,zz.useFunc)(e.gen,Pz.default)}(${r})`;e.fail$data((0,Ar._)`${i} ${s} ${n}`)}};pd.default=Rz});var fg=z(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var Ez=rt(),oi=F(),Iz={message:({schemaCode:e})=>(0,oi.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,oi._)`{pattern: ${e}}`},Oz={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Iz,code(e){let{data:t,$data:r,schema:n,schemaCode:o,it:s}=e,i=s.opts.unicodeRegExp?"u":"",a=r?(0,oi._)`(new RegExp(${o}, ${i}))`:(0,Ez.usePattern)(e,n);e.fail$data((0,oi._)`!${a}.test(${t})`)}};md.default=Oz});var hg=z(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var vo=F(),jz={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,vo.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,vo._)`{limit: ${e}}`},Cz={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:jz,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?vo.operators.GT:vo.operators.LT;e.fail$data((0,vo._)`Object.keys(${r}).length ${o} ${n}`)}};fd.default=Cz});var gg=z(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var bo=rt(),wo=F(),Az=ee(),Mz={message:({params:{missingProperty:e}})=>(0,wo.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,wo._)`{missingProperty: ${e}}`},Nz={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Mz,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let h=e.parentSchema.properties,{definedProperties:f}=e.it;for(let g of r)if(h?.[g]===void 0&&!f.has(g)){let y=i.schemaEnv.baseId+i.errSchemaPath,b=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,Az.checkStrictMode)(i,b,i.opts.strictRequired)}}function u(){if(c||s)e.block$data(wo.nil,l);else for(let h of r)(0,bo.checkReportMissingProp)(e,h)}function d(){let h=t.let("missing");if(c||s){let f=t.let("valid",!0);e.block$data(f,()=>p(h,f)),e.ok(f)}else t.if((0,bo.checkMissingProp)(e,r,h)),(0,bo.reportMissingProp)(e,h),t.else()}function l(){t.forOf("prop",n,h=>{e.setParams({missingProperty:h}),t.if((0,bo.noPropertyInData)(t,o,h,a.ownProperties),()=>e.error())})}function p(h,f){e.setParams({missingProperty:h}),t.forOf(h,n,()=>{t.assign(f,(0,bo.propertyInData)(t,o,h,a.ownProperties)),t.if((0,wo.not)(f),()=>{e.error(),t.break()})},wo.nil)}}};hd.default=Nz});var yg=z(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var ko=F(),Lz={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,ko.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,ko._)`{limit: ${e}}`},Dz={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Lz,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?ko.operators.GT:ko.operators.LT;e.fail$data((0,ko._)`${r}.length ${o} ${n}`)}};gd.default=Dz});var si=z(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var _g=Uu();_g.code='require("ajv/dist/runtime/equal").default';yd.default=_g});var vg=z(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var _d=ao(),Pe=F(),Zz=ee(),Uz=si(),qz={message:({params:{i:e,j:t}})=>(0,Pe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,Pe._)`{i: ${e}, j: ${t}}`},Jz={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:qz,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),u=s.items?(0,_d.getSchemaTypes)(s.items):[];e.block$data(c,d,(0,Pe._)`${i} === false`),e.ok(c);function d(){let f=t.let("i",(0,Pe._)`${r}.length`),g=t.let("j");e.setParams({i:f,j:g}),t.assign(c,!0),t.if((0,Pe._)`${f} > 1`,()=>(l()?p:h)(f,g))}function l(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function p(f,g){let y=t.name("item"),b=(0,_d.checkDataTypes)(u,y,a.opts.strictNumbers,_d.DataType.Wrong),w=t.const("indices",(0,Pe._)`{}`);t.for((0,Pe._)`;${f}--;`,()=>{t.let(y,(0,Pe._)`${r}[${f}]`),t.if(b,(0,Pe._)`continue`),u.length>1&&t.if((0,Pe._)`typeof ${y} == "string"`,(0,Pe._)`${y} += "_"`),t.if((0,Pe._)`typeof ${w}[${y}] == "number"`,()=>{t.assign(g,(0,Pe._)`${w}[${y}]`),e.error(),t.assign(c,!1).break()}).code((0,Pe._)`${w}[${y}] = ${f}`)})}function h(f,g){let y=(0,Zz.useFunc)(t,Uz.default),b=t.name("outer");t.label(b).for((0,Pe._)`;${f}--;`,()=>t.for((0,Pe._)`${g} = ${f}; ${g}--;`,()=>t.if((0,Pe._)`${y}(${r}[${f}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(b)})))}}};vd.default=Jz});var bg=z(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var bd=F(),Fz=ee(),Vz=si(),Bz={message:"must be equal to constant",params:({schemaCode:e})=>(0,bd._)`{allowedValue: ${e}}`},Hz={keyword:"const",$data:!0,error:Bz,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,bd._)`!${(0,Fz.useFunc)(t,Vz.default)}(${r}, ${o})`):e.fail((0,bd._)`${s} !== ${r}`)}};wd.default=Hz});var wg=z(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var xo=F(),Wz=ee(),Gz=si(),Kz={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,xo._)`{allowedValues: ${e}}`},Xz={keyword:"enum",schemaType:"array",$data:!0,error:Kz,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,Wz.useFunc)(t,Gz.default)),d;if(a||n)d=t.let("valid"),e.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let h=t.const("vSchema",s);d=(0,xo.or)(...o.map((f,g)=>p(h,g)))}e.pass(d);function l(){t.assign(d,!1),t.forOf("v",s,h=>t.if((0,xo._)`${u()}(${r}, ${h})`,()=>t.assign(d,!0).break()))}function p(h,f){let g=o[f];return typeof g=="object"&&g!==null?(0,xo._)`${u()}(${r}, ${h}[${f}])`:(0,xo._)`${r} === ${g}`}}};kd.default=Xz});var kg=z(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var Yz=ug(),Qz=dg(),e1=mg(),t1=fg(),r1=hg(),n1=gg(),o1=yg(),s1=vg(),i1=bg(),a1=wg(),c1=[Yz.default,Qz.default,e1.default,t1.default,r1.default,n1.default,o1.default,s1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},i1.default,a1.default];xd.default=c1});var $d=z(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.validateAdditionalItems=void 0;var Mr=F(),Sd=ee(),u1={message:({params:{len:e}})=>(0,Mr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Mr._)`{limit: ${e}}`},d1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:u1,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Sd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}xg(e,n)}};function xg(e,t){let{gen:r,schema:n,data:o,keyword:s,it:i}=e;i.items=!0;let a=r.const("len",(0,Mr._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Mr._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Sd.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Mr._)`${a} <= ${t.length}`);r.if((0,Mr.not)(u),()=>c(u)),e.ok(u)}function c(u){r.forRange("i",t.length,a,d=>{e.subschema({keyword:s,dataProp:d,dataPropType:Sd.Type.Num},u),i.allErrors||r.if((0,Mr.not)(u),()=>r.break())})}}So.validateAdditionalItems=xg;So.default=d1});var zd=z($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.validateTuple=void 0;var Sg=F(),ii=ee(),l1=rt(),p1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return $g(e,"additionalItems",t);r.items=!0,!(0,ii.alwaysValidSchema)(r,t)&&e.ok((0,l1.validateArray)(e))}};function $g(e,t,r=e.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=e;d(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ii.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Sg._)`${s}.length`);r.forEach((l,p)=>{(0,ii.alwaysValidSchema)(a,l)||(n.if((0,Sg._)`${u} > ${p}`,()=>e.subschema({keyword:i,schemaProp:p,dataProp:p},c)),e.ok(c))});function d(l){let{opts:p,errSchemaPath:h}=a,f=r.length,g=f===l.minItems&&(f===l.maxItems||l[t]===!1);if(p.strictTuples&&!g){let y=`"${i}" is ${f}-tuple, but minItems or maxItems/${t} are not specified or different at path "${h}"`;(0,ii.checkStrictMode)(a,y,p.strictTuples)}}}$o.validateTuple=$g;$o.default=p1});var zg=z(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var m1=zd(),f1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,m1.validateTuple)(e,"items")};Pd.default=f1});var Tg=z(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var Pg=F(),h1=ee(),g1=rt(),y1=$d(),_1={message:({params:{len:e}})=>(0,Pg.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Pg._)`{limit: ${e}}`},v1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:_1,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,h1.alwaysValidSchema)(n,t)&&(o?(0,y1.validateAdditionalItems)(e,o):e.ok((0,g1.validateArray)(e)))}};Td.default=v1});var Rg=z(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var ot=F(),ai=ee(),b1={message:({params:{min:e,max:t}})=>t===void 0?(0,ot.str)`must contain at least ${e} valid item(s)`:(0,ot.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,ot._)`{minContains: ${e}}`:(0,ot._)`{minContains: ${e}, maxContains: ${t}}`},w1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:b1,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=t.const("len",(0,ot._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,ai.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ai.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,ai.alwaysValidSchema)(s,r)){let g=(0,ot._)`${d} >= ${i}`;a!==void 0&&(g=(0,ot._)`${g} && ${d} <= ${a}`),e.pass(g);return}s.items=!0;let l=t.name("valid");a===void 0&&i===1?h(l,()=>t.if(l,()=>t.break())):i===0?(t.let(l,!0),a!==void 0&&t.if((0,ot._)`${o}.length > 0`,p)):(t.let(l,!1),p()),e.result(l,()=>e.reset());function p(){let g=t.name("_valid"),y=t.let("count",0);h(g,()=>t.if(g,()=>f(y)))}function h(g,y){t.forRange("i",0,d,b=>{e.subschema({keyword:"contains",dataProp:b,dataPropType:ai.Type.Num,compositeRule:!0},g),y()})}function f(g){t.code((0,ot._)`${g}++`),a===void 0?t.if((0,ot._)`${g} >= ${i}`,()=>t.assign(l,!0).break()):(t.if((0,ot._)`${g} > ${a}`,()=>t.assign(l,!1).break()),i===1?t.assign(l,!0):t.if((0,ot._)`${g} >= ${i}`,()=>t.assign(l,!0)))}}};Rd.default=w1});var Og=z(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.validateSchemaDeps=kt.validatePropertyDeps=kt.error=void 0;var Ed=F(),k1=ee(),zo=rt();kt.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Ed.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Ed._)`{property: ${e},
|
|
8
|
+
missingProperty: ${n},
|
|
9
|
+
depsCount: ${t},
|
|
10
|
+
deps: ${r}}`};var x1={keyword:"dependencies",type:"object",schemaType:"object",error:kt.error,code(e){let[t,r]=S1(e);Eg(e,t),Ig(e,r)}};function S1({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let o=Array.isArray(e[n])?t:r;o[n]=e[n]}return[t,r]}function Eg(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let i in t){let a=t[i];if(a.length===0)continue;let c=(0,zo.propertyInData)(r,n,i,o.opts.ownProperties);e.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,zo.checkReportMissingProp)(e,u)}):(r.if((0,Ed._)`${c} && (${(0,zo.checkMissingProp)(e,a,s)})`),(0,zo.reportMissingProp)(e,s),r.else())}}kt.validatePropertyDeps=Eg;function Ig(e,t=e.schema){let{gen:r,data:n,keyword:o,it:s}=e,i=r.name("valid");for(let a in t)(0,k1.alwaysValidSchema)(s,t[a])||(r.if((0,zo.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},i);e.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),e.ok(i))}kt.validateSchemaDeps=Ig;kt.default=x1});var Cg=z(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var jg=F(),$1=ee(),z1={message:"property name must be valid",params:({params:e})=>(0,jg._)`{propertyName: ${e.propertyName}}`},P1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:z1,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,$1.alwaysValidSchema)(o,r))return;let s=t.name("valid");t.forIn("key",n,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,jg.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Id.default=P1});var jd=z(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});var ci=rt(),pt=F(),T1=At(),ui=ee(),R1={message:"must NOT have additional properties",params:({params:e})=>(0,pt._)`{additionalProperty: ${e.additionalProperty}}`},E1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:R1,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,ui.alwaysValidSchema)(i,r))return;let u=(0,ci.allSchemaProperties)(n.properties),d=(0,ci.allSchemaProperties)(n.patternProperties);l(),e.ok((0,pt._)`${s} === ${T1.default.errors}`);function l(){t.forIn("key",o,y=>{!u.length&&!d.length?f(y):t.if(p(y),()=>f(y))})}function p(y){let b;if(u.length>8){let w=(0,ui.schemaRefOrVal)(i,n.properties,"properties");b=(0,ci.isOwnProperty)(t,w,y)}else u.length?b=(0,pt.or)(...u.map(w=>(0,pt._)`${y} === ${w}`)):b=pt.nil;return d.length&&(b=(0,pt.or)(b,...d.map(w=>(0,pt._)`${(0,ci.usePattern)(e,w)}.test(${y})`))),(0,pt.not)(b)}function h(y){t.code((0,pt._)`delete ${o}[${y}]`)}function f(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(y);return}if(r===!1){e.setParams({additionalProperty:y}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,ui.alwaysValidSchema)(i,r)){let b=t.name("valid");c.removeAdditional==="failing"?(g(y,b,!1),t.if((0,pt.not)(b),()=>{e.reset(),h(y)})):(g(y,b),a||t.if((0,pt.not)(b),()=>t.break()))}}function g(y,b,w){let k={keyword:"additionalProperties",dataProp:y,dataPropType:ui.Type.Str};w===!1&&Object.assign(k,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(k,b)}}};Od.default=E1});var Ng=z(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var I1=po(),Ag=rt(),Cd=ee(),Mg=jd(),O1={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Mg.default.code(new I1.KeywordCxt(s,Mg.default,"additionalProperties"));let i=(0,Ag.allSchemaProperties)(r);for(let l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Cd.mergeEvaluated.props(t,(0,Cd.toHash)(i),s.props));let a=i.filter(l=>!(0,Cd.alwaysValidSchema)(s,r[l]));if(a.length===0)return;let c=t.name("valid");for(let l of a)u(l)?d(l):(t.if((0,Ag.propertyInData)(t,o,l,s.opts.ownProperties)),d(l),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(l),e.ok(c);function u(l){return s.opts.useDefaults&&!s.compositeRule&&r[l].default!==void 0}function d(l){e.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};Ad.default=O1});var Ug=z(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var Lg=rt(),di=F(),Dg=ee(),Zg=ee(),j1={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,Lg.allSchemaProperties)(r),c=a.filter(g=>(0,Dg.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,d=t.name("valid");s.props!==!0&&!(s.props instanceof di.Name)&&(s.props=(0,Zg.evaluatedPropsToName)(t,s.props));let{props:l}=s;p();function p(){for(let g of a)u&&h(g),s.allErrors?f(g):(t.var(d,!0),f(g),t.if(d))}function h(g){for(let y in u)new RegExp(g).test(y)&&(0,Dg.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function f(g){t.forIn("key",n,y=>{t.if((0,di._)`${(0,Lg.usePattern)(e,g)}.test(${y})`,()=>{let b=c.includes(g);b||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:Zg.Type.Str},d),s.opts.unevaluated&&l!==!0?t.assign((0,di._)`${l}[${y}]`,!0):!b&&!s.allErrors&&t.if((0,di.not)(d),()=>t.break())})})}}};Md.default=j1});var qg=z(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var C1=ee(),A1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,C1.alwaysValidSchema)(n,r)){e.fail();return}let o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Nd.default=A1});var Jg=z(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var M1=rt(),N1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:M1.validateUnion,error:{message:"must match a schema in anyOf"}};Ld.default=N1});var Fg=z(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var li=F(),L1=ee(),D1={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,li._)`{passingSchemas: ${e.passing}}`},Z1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:D1,code(e){let{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(i,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((d,l)=>{let p;(0,L1.alwaysValidSchema)(o,d)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&t.if((0,li._)`${c} && ${i}`).assign(i,!1).assign(a,(0,li._)`[${a}, ${l}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,l),p&&e.mergeEvaluated(p,li.Name)})})}}};Dd.default=Z1});var Vg=z(Zd=>{"use strict";Object.defineProperty(Zd,"__esModule",{value:!0});var U1=ee(),q1={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 o=t.name("valid");r.forEach((s,i)=>{if((0,U1.alwaysValidSchema)(n,s))return;let a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};Zd.default=q1});var Wg=z(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var pi=F(),Hg=ee(),J1={message:({params:e})=>(0,pi.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,pi._)`{failingKeyword: ${e.ifClause}}`},F1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:J1,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Hg.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Bg(n,"then"),s=Bg(n,"else");if(!o&&!s)return;let i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&s){let d=t.let("ifClause");e.setParams({ifClause:d}),t.if(a,u("then",d),u("else",d))}else o?t.if(a,u("then")):t.if((0,pi.not)(a),u("else"));e.pass(i,()=>e.error(!0));function c(){let d=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(d)}function u(d,l){return()=>{let p=e.subschema({keyword:d},a);t.assign(i,a),e.mergeValidEvaluated(p,i),l?t.assign(l,(0,pi._)`${d}`):e.setParams({ifClause:d})}}}};function Bg(e,t){let r=e.schema[t];return r!==void 0&&!(0,Hg.alwaysValidSchema)(e,r)}Ud.default=F1});var Gg=z(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var V1=ee(),B1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,V1.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};qd.default=B1});var Kg=z(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var H1=$d(),W1=zg(),G1=zd(),K1=Tg(),X1=Rg(),Y1=Og(),Q1=Cg(),eP=jd(),tP=Ng(),rP=Ug(),nP=qg(),oP=Jg(),sP=Fg(),iP=Vg(),aP=Wg(),cP=Gg();function uP(e=!1){let t=[nP.default,oP.default,sP.default,iP.default,aP.default,cP.default,Q1.default,eP.default,Y1.default,tP.default,rP.default];return e?t.push(W1.default,K1.default):t.push(H1.default,G1.default),t.push(X1.default),t}Jd.default=uP});var Xg=z(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var ye=F(),dP={message:({schemaCode:e})=>(0,ye.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ye._)`{format: ${e}}`},lP={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:dP,code(e,t){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?p():h();function p(){let f=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),g=r.const("fDef",(0,ye._)`${f}[${i}]`),y=r.let("fType"),b=r.let("format");r.if((0,ye._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,ye._)`${g}.type || "string"`).assign(b,(0,ye._)`${g}.validate`),()=>r.assign(y,(0,ye._)`"string"`).assign(b,g)),e.fail$data((0,ye.or)(w(),k()));function w(){return c.strictSchema===!1?ye.nil:(0,ye._)`${i} && !${b}`}function k(){let R=d.$async?(0,ye._)`(${g}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,ye._)`${b}(${n})`,M=(0,ye._)`(typeof ${b} == "function" ? ${R} : ${b}.test(${n}))`;return(0,ye._)`${b} && ${b} !== true && ${y} === ${t} && !${M}`}}function h(){let f=l.formats[s];if(!f){w();return}if(f===!0)return;let[g,y,b]=k(f);g===t&&e.pass(R());function w(){if(c.strictSchema===!1){l.logger.warn(M());return}throw new Error(M());function M(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function k(M){let Oe=M instanceof RegExp?(0,ye.regexpCode)(M):c.code.formats?(0,ye._)`${c.code.formats}${(0,ye.getProperty)(s)}`:void 0,Ge=r.scopeValue("formats",{key:s,ref:M,code:Oe});return typeof M=="object"&&!(M instanceof RegExp)?[M.type||"string",M.validate,(0,ye._)`${Ge}.validate`]:["string",M,Ge]}function R(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!d.$async)throw new Error("async format in sync schema");return(0,ye._)`await ${b}(${n})`}return typeof y=="function"?(0,ye._)`${b}(${n})`:(0,ye._)`${b}.test(${n})`}}}};Fd.default=lP});var Yg=z(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var pP=Xg(),mP=[pP.default];Vd.default=mP});var Qg=z(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.contentVocabulary=gn.metadataVocabulary=void 0;gn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];gn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ty=z(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var fP=cg(),hP=kg(),gP=Kg(),yP=Yg(),ey=Qg(),_P=[fP.default,hP.default,(0,gP.default)(),yP.default,ey.metadataVocabulary,ey.contentVocabulary];Bd.default=_P});var ny=z(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});mi.DiscrError=void 0;var ry;(function(e){e.Tag="tag",e.Mapping="mapping"})(ry||(mi.DiscrError=ry={}))});var sy=z(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var yn=F(),Hd=ny(),oy=Ws(),vP=mo(),bP=ee(),wP={message:({params:{discrError:e,tagName:t}})=>e===Hd.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,yn._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},kP={keyword:"discriminator",type:"object",schemaType:"object",error:wP,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:s}=e,{oneOf:i}=o;if(!s.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(!i)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),u=t.const("tag",(0,yn._)`${r}${(0,yn.getProperty)(a)}`);t.if((0,yn._)`typeof ${u} == "string"`,()=>d(),()=>e.error(!1,{discrError:Hd.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function d(){let h=p();t.if(!1);for(let f in h)t.elseIf((0,yn._)`${u} === ${f}`),t.assign(c,l(h[f]));t.else(),e.error(!1,{discrError:Hd.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function l(h){let f=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:h},f);return e.mergeEvaluated(g,yn.Name),f}function p(){var h;let f={},g=b(o),y=!0;for(let R=0;R<i.length;R++){let M=i[R];if(M?.$ref&&!(0,bP.schemaHasRulesButRef)(M,s.self.RULES)){let Ge=M.$ref;if(M=oy.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Ge),M instanceof oy.SchemaEnv&&(M=M.schema),M===void 0)throw new vP.default(s.opts.uriResolver,s.baseId,Ge)}let Oe=(h=M?.properties)===null||h===void 0?void 0:h[a];if(typeof Oe!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||b(M)),w(Oe,R)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return f;function b({required:R}){return Array.isArray(R)&&R.includes(a)}function w(R,M){if(R.const)k(R.const,M);else if(R.enum)for(let Oe of R.enum)k(Oe,M);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function k(R,M){if(typeof R!="string"||R in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[R]=M}}}};Wd.default=kP});var iy=z((LA,xP)=>{xP.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 Kd=z((le,Gd)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv=void 0;var SP=rg(),$P=ty(),zP=sy(),ay=iy(),PP=["/properties"],fi="http://json-schema.org/draft-07/schema",_n=class extends SP.default{_addVocabularies(){super._addVocabularies(),$P.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(zP.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(ay,PP):ay;this.addMetaSchema(t,fi,!1),this.refs["http://json-schema.org/schema"]=fi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(fi)?fi:void 0)}};le.Ajv=_n;Gd.exports=le=_n;Gd.exports.Ajv=_n;Object.defineProperty(le,"__esModule",{value:!0});le.default=_n;var TP=po();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return TP.KeywordCxt}});var vn=F();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return vn._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return vn.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return vn.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return vn.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return vn.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return vn.CodeGen}});var RP=Bs();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:function(){return RP.default}});var EP=mo();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:function(){return EP.default}})});var hy=z(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.formatNames=St.fastFormats=St.fullFormats=void 0;function xt(e,t){return{validate:e,compare:t}}St.fullFormats={date:xt(ly,el),time:xt(Yd(!0),tl),"date-time":xt(cy(!0),my),"iso-time":xt(Yd(),py),"iso-date-time":xt(cy(),fy),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:MP,"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:JP,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:NP,int32:{type:"number",validate:ZP},int64:{type:"number",validate:UP},float:{type:"number",validate:dy},double:{type:"number",validate:dy},password:!0,binary:!0};St.fastFormats={...St.fullFormats,date:xt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,el),time:xt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,tl),"date-time":xt(/^\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,my),"iso-time":xt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,py),"iso-date-time":xt(/^\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,fy),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};St.formatNames=Object.keys(St.fullFormats);function IP(e){return e%4===0&&(e%100!==0||e%400===0)}var OP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,jP=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ly(e){let t=OP.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&IP(r)?29:jP[n])}function el(e,t){if(e&&t)return e>t?1:e<t?-1:0}var Xd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Yd(e){return function(r){let n=Xd.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||e&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let l=s-d*c,p=o-u*c-(l<0?1:0);return(p===23||p===-1)&&(l===59||l===-1)&&i<61}}function tl(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 py(e,t){if(!(e&&t))return;let r=Xd.exec(e),n=Xd.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 Qd=/t|\s/i;function cy(e){let t=Yd(e);return function(n){let o=n.split(Qd);return o.length===2&&ly(o[0])&&t(o[1])}}function my(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function fy(e,t){if(!(e&&t))return;let[r,n]=e.split(Qd),[o,s]=t.split(Qd),i=el(r,o);if(i!==void 0)return i||tl(n,s)}var CP=/\/|:/,AP=/^(?:[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 MP(e){return CP.test(e)&&AP.test(e)}var uy=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function NP(e){return uy.lastIndex=0,uy.test(e)}var LP=-(2**31),DP=2**31-1;function ZP(e){return Number.isInteger(e)&&e<=DP&&e>=LP}function UP(e){return Number.isInteger(e)}function dy(){return!0}var qP=/[^\\]\\Z/;function JP(e){if(qP.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var gy=z(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.formatLimitDefinition=void 0;var FP=Kd(),mt=F(),rr=mt.operators,hi={formatMaximum:{okStr:"<=",ok:rr.LTE,fail:rr.GT},formatMinimum:{okStr:">=",ok:rr.GTE,fail:rr.LT},formatExclusiveMaximum:{okStr:"<",ok:rr.LT,fail:rr.GTE},formatExclusiveMinimum:{okStr:">",ok:rr.GT,fail:rr.LTE}},VP={message:({keyword:e,schemaCode:t})=>(0,mt.str)`should be ${hi[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,mt._)`{comparison: ${hi[e].okStr}, limit: ${t}}`};bn.formatLimitDefinition={keyword:Object.keys(hi),type:"string",schemaType:"string",$data:!0,error:VP,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:s}=e,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new FP.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let p=t.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=t.const("fmt",(0,mt._)`${p}[${c.schemaCode}]`);e.fail$data((0,mt.or)((0,mt._)`typeof ${h} != "object"`,(0,mt._)`${h} instanceof RegExp`,(0,mt._)`typeof ${h}.compare != "function"`,l(h)))}function d(){let p=c.schema,h=a.formats[p];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let f=t.scopeValue("formats",{key:p,ref:h,code:i.code.formats?(0,mt._)`${i.code.formats}${(0,mt.getProperty)(p)}`:void 0});e.fail$data(l(f))}function l(p){return(0,mt._)`${p}.compare(${r}, ${n}) ${hi[o].fail} 0`}},dependencies:["format"]};var BP=e=>(e.addKeyword(bn.formatLimitDefinition),e);bn.default=BP});var by=z((Po,vy)=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});var wn=hy(),HP=gy(),rl=F(),yy=new rl.Name("fullFormats"),WP=new rl.Name("fastFormats"),nl=(e,t={keywords:!0})=>{if(Array.isArray(t))return _y(e,t,wn.fullFormats,yy),e;let[r,n]=t.mode==="fast"?[wn.fastFormats,WP]:[wn.fullFormats,yy],o=t.formats||wn.formatNames;return _y(e,o,r,n),t.keywords&&(0,HP.default)(e),e};nl.get=(e,t="full")=>{let n=(t==="fast"?wn.fastFormats:wn.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function _y(e,t,r,n){var o,s;(o=(s=e.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,rl._)`require("ajv-formats/dist/formats").${n}`);for(let i of t)e.addFormat(i,r[i])}vy.exports=Po=nl;Object.defineProperty(Po,"__esModule",{value:!0});Po.default=nl});import{pathToFileURL as _E}from"node:url";var m={};Ii(m,{BRAND:()=>Cv,DIRTY:()=>or,EMPTY_PATH:()=>pv,INVALID:()=>N,NEVER:()=>yb,OK:()=>Te,ParseStatus:()=>ke,Schema:()=>J,ZodAny:()=>Ut,ZodArray:()=>It,ZodBigInt:()=>ir,ZodBoolean:()=>ar,ZodBranded:()=>$n,ZodCatch:()=>_r,ZodDate:()=>cr,ZodDefault:()=>yr,ZodDiscriminatedUnion:()=>Lo,ZodEffects:()=>Xe,ZodEnum:()=>hr,ZodError:()=>Ne,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>Zo,ZodIntersection:()=>pr,ZodIssueCode:()=>x,ZodLazy:()=>mr,ZodLiteral:()=>fr,ZodMap:()=>Vr,ZodNaN:()=>Hr,ZodNativeEnum:()=>gr,ZodNever:()=>st,ZodNull:()=>dr,ZodNullable:()=>yt,ZodNumber:()=>sr,ZodObject:()=>De,ZodOptional:()=>Le,ZodParsedType:()=>P,ZodPipeline:()=>zn,ZodPromise:()=>qt,ZodReadonly:()=>vr,ZodRecord:()=>Do,ZodSchema:()=>J,ZodSet:()=>Br,ZodString:()=>Zt,ZodSymbol:()=>Jr,ZodTransformer:()=>Xe,ZodTuple:()=>gt,ZodType:()=>J,ZodUndefined:()=>ur,ZodUnion:()=>lr,ZodUnknown:()=>Et,ZodVoid:()=>Fr,addIssueToContext:()=>$,any:()=>Jv,array:()=>Hv,bigint:()=>Lv,boolean:()=>Kl,coerce:()=>gb,custom:()=>Hl,date:()=>Dv,datetimeRegex:()=>Vl,defaultErrorMap:()=>Tt,discriminatedUnion:()=>Kv,effect:()=>cb,enum:()=>sb,function:()=>rb,getErrorMap:()=>Zr,getParsedType:()=>ht,instanceof:()=>Mv,intersection:()=>Xv,isAborted:()=>Mo,isAsync:()=>Ur,isDirty:()=>No,isValid:()=>Dt,late:()=>Av,lazy:()=>nb,literal:()=>ob,makeIssue:()=>Sn,map:()=>eb,nan:()=>Nv,nativeEnum:()=>ib,never:()=>Vv,null:()=>qv,nullable:()=>db,number:()=>Gl,object:()=>Ai,objectUtil:()=>Oi,oboolean:()=>hb,onumber:()=>fb,optional:()=>ub,ostring:()=>mb,pipeline:()=>pb,preprocess:()=>lb,promise:()=>ab,quotelessJson:()=>uv,record:()=>Qv,set:()=>tb,setErrorMap:()=>lv,strictObject:()=>Wv,string:()=>Wl,symbol:()=>Zv,transformer:()=>cb,tuple:()=>Yv,undefined:()=>Uv,union:()=>Gv,unknown:()=>Fv,util:()=>H,void:()=>Bv});var H;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=o=>{let s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(H||(H={}));var Oi;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Oi||(Oi={}));var P=H.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ht=e=>{switch(typeof e){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN(e)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(e)?P.array:e===null?P.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?P.promise:typeof Map<"u"&&e instanceof Map?P.map:typeof Set<"u"&&e instanceof Set?P.set:typeof Date<"u"&&e instanceof Date?P.date:P.object;default:return P.unknown}};var x=H.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"]),uv=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Ne=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(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(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,H.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ne.create=e=>new Ne(e);var dv=(e,t)=>{let r;switch(e.code){case x.invalid_type:e.received===P.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case x.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,H.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:r=`Unrecognized key(s) in object: ${H.joinValues(e.keys,", ")}`;break;case x.invalid_union:r="Invalid input";break;case x.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${H.joinValues(e.options)}`;break;case x.invalid_enum_value:r=`Invalid enum value. Expected ${H.joinValues(e.options)}, received '${e.received}'`;break;case x.invalid_arguments:r="Invalid function arguments";break;case x.invalid_return_type:r="Invalid function return type";break;case x.invalid_date:r="Invalid date";break;case x.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}"`:H.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case x.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 x.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 x.custom:r="Invalid input";break;case x.invalid_intersection_types:r="Intersection results could not be merged";break;case x.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case x.not_finite:r="Number must be finite";break;default:r=t.defaultError,H.assertNever(e)}return{message:r}},Tt=dv;var Zl=Tt;function lv(e){Zl=e}function Zr(){return Zl}var Sn=e=>{let{data:t,path:r,errorMaps:n,issueData:o}=e,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},pv=[];function $(e,t){let r=Zr(),n=Sn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Tt?void 0:Tt].filter(o=>!!o)});e.common.issues.push(n)}var ke=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 o of r){if(o.status==="aborted")return N;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return N;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:t.value,value:n}}},N=Object.freeze({status:"aborted"}),or=e=>({status:"dirty",value:e}),Te=e=>({status:"valid",value:e}),Mo=e=>e.status==="aborted",No=e=>e.status==="dirty",Dt=e=>e.status==="valid",Ur=e=>typeof Promise<"u"&&e instanceof Promise;var I;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(I||(I={}));var Ke=class{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=o}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}},Ul=(e,t)=>{if(Dt(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 Ne(e.common.issues);return this._error=r,this._error}}};function U(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:o}=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:o}:{errorMap:(i,a)=>{let{message:c}=e;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var J=class{get description(){return this._def.description}_getType(t){return ht(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:ht(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ke,ctx:{common:t.parent.common,data:t.data,parsedType:ht(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(Ur(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:ht(t)},o=this._parseSync({data:t,path:n.path,parent:n});return Ul(n,o)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ht(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Dt(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=>Dt(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:ht(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(Ur(o)?o:Promise.resolve(o));return Ul(n,s)}refine(t,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=t(o),a=()=>s.addIssue({code:x.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,o)=>t(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(t){return new Xe({schema:this,typeName:S.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 Le.create(this,this._def)}nullable(){return yt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return It.create(this)}promise(){return qt.create(this,this._def)}or(t){return lr.create([this,t],this._def)}and(t){return pr.create(this,t,this._def)}transform(t){return new Xe({...U(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new yr({...U(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new $n({typeName:S.ZodBranded,type:this,...U(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new _r({...U(this._def),innerType:this,catchValue:r,typeName:S.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return zn.create(this,t)}readonly(){return vr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},mv=/^c[^\s-]{8,}$/i,fv=/^[0-9a-z]+$/,hv=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gv=/^[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,yv=/^[a-z0-9_-]{21}$/i,_v=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vv=/^[-+]?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)?)??$/,bv=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,wv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ji,kv=/^(?:(?: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])$/,xv=/^(?:(?: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])$/,Sv=/^(([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]))$/,$v=/^(([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])$/,zv=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Pv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Jl="((\\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])))",Tv=new RegExp(`^${Jl}$`);function Fl(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 Rv(e){return new RegExp(`^${Fl(e)}$`)}function Vl(e){let t=`${Jl}T${Fl(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 Ev(e,t){return!!((t==="v4"||!t)&&kv.test(e)||(t==="v6"||!t)&&Sv.test(e))}function Iv(e,t){if(!_v.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,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Ov(e,t){return!!((t==="v4"||!t)&&xv.test(e)||(t==="v6"||!t)&&$v.test(e))}var Zt=class e extends J{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==P.string){let s=this._getOrReturnCtx(t);return $(s,{code:x.invalid_type,expected:P.string,received:s.parsedType}),N}let n=new ke,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),$(o,{code:x.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),$(o,{code:x.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?$(o,{code:x.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&$(o,{code:x.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")bv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"email",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")ji||(ji=new RegExp(wv,"u")),ji.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"emoji",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")gv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"uuid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")yv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"nanoid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")mv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"cuid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")fv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"cuid2",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")hv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"ulid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),$(o,{validation:"url",code:x.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"regex",code:x.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),$(o,{code:x.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),$(o,{code:x.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),$(o,{code:x.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Vl(s).test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{code:x.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Tv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{code:x.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Rv(s).test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{code:x.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?vv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"duration",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Ev(t.data,s.version)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"ip",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Iv(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"jwt",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Ov(t.data,s.version)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"cidr",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?zv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"base64",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Pv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"base64url",code:x.invalid_string,message:s.message}),n.dirty()):H.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:x.invalid_string,...I.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...I.errToObj(t)})}url(t){return this._addCheck({kind:"url",...I.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...I.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...I.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...I.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...I.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...I.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...I.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...I.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...I.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...I.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...I.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...I.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,...I.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,...I.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...I.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...I.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...I.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...I.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...I.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...I.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...I.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...I.errToObj(r)})}nonempty(t){return this.min(1,I.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}};Zt.create=e=>new Zt({checks:[],typeName:S.ZodString,coerce:e?.coerce??!1,...U(e)});function jv(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}var sr=class e extends J{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)!==P.number){let s=this._getOrReturnCtx(t);return $(s,{code:x.invalid_type,expected:P.number,received:s.parsedType}),N}let n,o=new ke;for(let s of this._def.checks)s.kind==="int"?H.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),$(n,{code:x.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),$(n,{code:x.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),$(n,{code:x.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?jv(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),$(n,{code:x.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),$(n,{code:x.not_finite,message:s.message}),o.dirty()):H.assertNever(s);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,I.toString(r))}gt(t,r){return this.setLimit("min",t,!1,I.toString(r))}lte(t,r){return this.setLimit("max",t,!0,I.toString(r))}lt(t,r){return this.setLimit("max",t,!1,I.toString(r))}setLimit(t,r,n,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:I.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:I.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:I.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:I.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.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"&&H.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)}};sr.create=e=>new sr({checks:[],typeName:S.ZodNumber,coerce:e?.coerce||!1,...U(e)});var ir=class e extends J{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)!==P.bigint)return this._getInvalidInput(t);let n,o=new ke;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),$(n,{code:x.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),$(n,{code:x.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),$(n,{code:x.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):H.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return $(r,{code:x.invalid_type,expected:P.bigint,received:r.parsedType}),N}gte(t,r){return this.setLimit("min",t,!0,I.toString(r))}gt(t,r){return this.setLimit("min",t,!1,I.toString(r))}lte(t,r){return this.setLimit("max",t,!0,I.toString(r))}lt(t,r){return this.setLimit("max",t,!1,I.toString(r))}setLimit(t,r,n,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:I.toString(o)}]})}_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:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:I.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}};ir.create=e=>new ir({checks:[],typeName:S.ZodBigInt,coerce:e?.coerce??!1,...U(e)});var ar=class extends J{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==P.boolean){let n=this._getOrReturnCtx(t);return $(n,{code:x.invalid_type,expected:P.boolean,received:n.parsedType}),N}return Te(t.data)}};ar.create=e=>new ar({typeName:S.ZodBoolean,coerce:e?.coerce||!1,...U(e)});var cr=class e extends J{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==P.date){let s=this._getOrReturnCtx(t);return $(s,{code:x.invalid_type,expected:P.date,received:s.parsedType}),N}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return $(s,{code:x.invalid_date}),N}let n=new ke,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),$(o,{code:x.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),$(o,{code:x.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):H.assertNever(s);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:I.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:I.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}};cr.create=e=>new cr({checks:[],coerce:e?.coerce||!1,typeName:S.ZodDate,...U(e)});var Jr=class extends J{_parse(t){if(this._getType(t)!==P.symbol){let n=this._getOrReturnCtx(t);return $(n,{code:x.invalid_type,expected:P.symbol,received:n.parsedType}),N}return Te(t.data)}};Jr.create=e=>new Jr({typeName:S.ZodSymbol,...U(e)});var ur=class extends J{_parse(t){if(this._getType(t)!==P.undefined){let n=this._getOrReturnCtx(t);return $(n,{code:x.invalid_type,expected:P.undefined,received:n.parsedType}),N}return Te(t.data)}};ur.create=e=>new ur({typeName:S.ZodUndefined,...U(e)});var dr=class extends J{_parse(t){if(this._getType(t)!==P.null){let n=this._getOrReturnCtx(t);return $(n,{code:x.invalid_type,expected:P.null,received:n.parsedType}),N}return Te(t.data)}};dr.create=e=>new dr({typeName:S.ZodNull,...U(e)});var Ut=class extends J{constructor(){super(...arguments),this._any=!0}_parse(t){return Te(t.data)}};Ut.create=e=>new Ut({typeName:S.ZodAny,...U(e)});var Et=class extends J{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Te(t.data)}};Et.create=e=>new Et({typeName:S.ZodUnknown,...U(e)});var st=class extends J{_parse(t){let r=this._getOrReturnCtx(t);return $(r,{code:x.invalid_type,expected:P.never,received:r.parsedType}),N}};st.create=e=>new st({typeName:S.ZodNever,...U(e)});var Fr=class extends J{_parse(t){if(this._getType(t)!==P.undefined){let n=this._getOrReturnCtx(t);return $(n,{code:x.invalid_type,expected:P.void,received:n.parsedType}),N}return Te(t.data)}};Fr.create=e=>new Fr({typeName:S.ZodVoid,...U(e)});var It=class e extends J{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==P.array)return $(r,{code:x.invalid_type,expected:P.array,received:r.parsedType}),N;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&($(r,{code:i?x.too_big:x.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&($(r,{code:x.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&($(r,{code:x.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new Ke(r,i,r.path,a)))).then(i=>ke.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Ke(r,i,r.path,a)));return ke.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:I.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:I.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:I.toString(r)}})}nonempty(t){return this.min(1,t)}};It.create=(e,t)=>new It({type:e,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...U(t)});function qr(e){if(e instanceof De){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Le.create(qr(n))}return new De({...e._def,shape:()=>t})}else return e instanceof It?new It({...e._def,type:qr(e.element)}):e instanceof Le?Le.create(qr(e.unwrap())):e instanceof yt?yt.create(qr(e.unwrap())):e instanceof gt?gt.create(e.items.map(t=>qr(t))):e}var De=class e extends J{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=H.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==P.object){let u=this._getOrReturnCtx(t);return $(u,{code:x.invalid_type,expected:P.object,received:u.parsedType}),N}let{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof st&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let d=s[u],l=o.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new Ke(o,l,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof st){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(u==="strict")a.length>0&&($(o,{code:x.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=o.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new Ke(o,l,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,p=await d.value;u.push({key:l,value:p,alwaysSet:d.alwaysSet})}return u}).then(u=>ke.mergeObjectSync(n,u)):ke.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return I.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:I.errToObj(t).message??o}:{message:o}}}:{}})}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:S.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 H.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 H.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return qr(this)}partial(t){let r={};for(let n of H.objectKeys(this.shape)){let o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of H.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Le;)s=s._def.innerType;r[n]=s}return new e({...this._def,shape:()=>r})}keyof(){return Bl(H.objectKeys(this.shape))}};De.create=(e,t)=>new De({shape:()=>e,unknownKeys:"strip",catchall:st.create(),typeName:S.ZodObject,...U(t)});De.strictCreate=(e,t)=>new De({shape:()=>e,unknownKeys:"strict",catchall:st.create(),typeName:S.ZodObject,...U(t)});De.lazycreate=(e,t)=>new De({shape:e,unknownKeys:"strip",catchall:st.create(),typeName:S.ZodObject,...U(t)});var lr=class extends J{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ne(a.ctx.common.issues));return $(r,{code:x.invalid_union,unionErrors:i}),N}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ne(c));return $(r,{code:x.invalid_union,unionErrors:a}),N}}get options(){return this._def.options}};lr.create=(e,t)=>new lr({options:e,typeName:S.ZodUnion,...U(t)});var Rt=e=>e instanceof mr?Rt(e.schema):e instanceof Xe?Rt(e.innerType()):e instanceof fr?[e.value]:e instanceof hr?e.options:e instanceof gr?H.objectValues(e.enum):e instanceof yr?Rt(e._def.innerType):e instanceof ur?[void 0]:e instanceof dr?[null]:e instanceof Le?[void 0,...Rt(e.unwrap())]:e instanceof yt?[null,...Rt(e.unwrap())]:e instanceof $n||e instanceof vr?Rt(e.unwrap()):e instanceof _r?Rt(e._def.innerType):[],Lo=class e extends J{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==P.object)return $(r,{code:x.invalid_type,expected:P.object,received:r.parsedType}),N;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):($(r,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),N)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let o=new Map;for(let s of r){let i=Rt(s.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,s)}}return new e({typeName:S.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...U(n)})}};function Ci(e,t){let r=ht(e),n=ht(t);if(e===t)return{valid:!0,data:e};if(r===P.object&&n===P.object){let o=H.objectKeys(t),s=H.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let c=Ci(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===P.array&&n===P.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],c=Ci(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===P.date&&n===P.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var pr=class extends J{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),o=(s,i)=>{if(Mo(s)||Mo(i))return N;let a=Ci(s.value,i.value);return a.valid?((No(s)||No(i))&&r.dirty(),{status:r.value,value:a.data}):($(n,{code:x.invalid_intersection_types}),N)};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(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};pr.create=(e,t,r)=>new pr({left:e,right:t,typeName:S.ZodIntersection,...U(r)});var gt=class e extends J{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==P.array)return $(n,{code:x.invalid_type,expected:P.array,received:n.parsedType}),N;if(n.data.length<this._def.items.length)return $(n,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),N;!this._def.rest&&n.data.length>this._def.items.length&&($(n,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ke(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>ke.mergeArray(r,i)):ke.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};gt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new gt({items:e,typeName:S.ZodTuple,rest:null,...U(t)})};var Do=class e extends J{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!==P.object)return $(n,{code:x.invalid_type,expected:P.object,received:n.parsedType}),N;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Ke(n,a,n.path,a)),value:i._parse(new Ke(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ke.mergeObjectAsync(r,o):ke.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof J?new e({keyType:t,valueType:r,typeName:S.ZodRecord,...U(n)}):new e({keyType:Zt.create(),valueType:t,typeName:S.ZodRecord,...U(r)})}},Vr=class extends J{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!==P.map)return $(n,{code:x.invalid_type,expected:P.map,received:n.parsedType}),N;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new Ke(n,a,n.path,[u,"key"])),value:s._parse(new Ke(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return N;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return N;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};Vr.create=(e,t,r)=>new Vr({valueType:t,keyType:e,typeName:S.ZodMap,...U(r)});var Br=class e extends J{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==P.set)return $(n,{code:x.invalid_type,expected:P.set,received:n.parsedType}),N;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&($(n,{code:x.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&($(n,{code:x.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let d of c){if(d.status==="aborted")return N;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new Ke(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:I.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:I.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Br.create=(e,t)=>new Br({valueType:e,minSize:null,maxSize:null,typeName:S.ZodSet,...U(t)});var Zo=class e extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==P.function)return $(r,{code:x.invalid_type,expected:P.function,received:r.parsedType}),N;function n(a,c){return Sn({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Zr(),Tt].filter(u=>!!u),issueData:{code:x.invalid_arguments,argumentsError:c}})}function o(a,c){return Sn({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Zr(),Tt].filter(u=>!!u),issueData:{code:x.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof qt){let a=this;return Te(async function(...c){let u=new Ne([]),d=await a._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(n(c,h)),u}),l=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(l,s).catch(h=>{throw u.addIssue(o(l,h)),u})})}else{let a=this;return Te(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ne([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),l=a._def.returns.safeParse(d,s);if(!l.success)throw new Ne([o(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:gt.create(t).rest(Et.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||gt.create([]).rest(Et.create()),returns:r||Et.create(),typeName:S.ZodFunction,...U(n)})}},mr=class extends J{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})}};mr.create=(e,t)=>new mr({getter:e,typeName:S.ZodLazy,...U(t)});var fr=class extends J{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return $(r,{received:r.data,code:x.invalid_literal,expected:this._def.value}),N}return{status:"valid",value:t.data}}get value(){return this._def.value}};fr.create=(e,t)=>new fr({value:e,typeName:S.ZodLiteral,...U(t)});function Bl(e,t){return new hr({values:e,typeName:S.ZodEnum,...U(t)})}var hr=class e extends J{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return $(r,{expected:H.joinValues(n),received:r.parsedType,code:x.invalid_type}),N}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 $(r,{received:r.data,code:x.invalid_enum_value,options:n}),N}return Te(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})}};hr.create=Bl;var gr=class extends J{_parse(t){let r=H.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==P.string&&n.parsedType!==P.number){let o=H.objectValues(r);return $(n,{expected:H.joinValues(o),received:n.parsedType,code:x.invalid_type}),N}if(this._cache||(this._cache=new Set(H.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=H.objectValues(r);return $(n,{received:n.data,code:x.invalid_enum_value,options:o}),N}return Te(t.data)}get enum(){return this._def.values}};gr.create=(e,t)=>new gr({values:e,typeName:S.ZodNativeEnum,...U(t)});var qt=class extends J{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==P.promise&&r.common.async===!1)return $(r,{code:x.invalid_type,expected:P.promise,received:r.parsedType}),N;let n=r.parsedType===P.promise?r.data:Promise.resolve(r.data);return Te(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};qt.create=(e,t)=>new qt({type:e,typeName:S.ZodPromise,...U(t)});var Xe=class extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i=>{$(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return N;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?N:c.status==="dirty"?or(c.value):r.value==="dirty"?or(c.value):c});{if(r.value==="aborted")return N;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?N:a.status==="dirty"?or(a.value):r.value==="dirty"?or(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c 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"?N:(a.status==="dirty"&&r.dirty(),i(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"?N:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Dt(i))return N;let a=o.transform(i.value,s);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(i=>Dt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):N);H.assertNever(o)}};Xe.create=(e,t,r)=>new Xe({schema:e,typeName:S.ZodEffects,effect:t,...U(r)});Xe.createWithPreprocess=(e,t,r)=>new Xe({schema:t,effect:{type:"preprocess",transform:e},typeName:S.ZodEffects,...U(r)});var Le=class extends J{_parse(t){return this._getType(t)===P.undefined?Te(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Le.create=(e,t)=>new Le({innerType:e,typeName:S.ZodOptional,...U(t)});var yt=class extends J{_parse(t){return this._getType(t)===P.null?Te(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};yt.create=(e,t)=>new yt({innerType:e,typeName:S.ZodNullable,...U(t)});var yr=class extends J{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===P.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};yr.create=(e,t)=>new yr({innerType:e,typeName:S.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...U(t)});var _r=class extends J{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ur(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ne(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ne(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};_r.create=(e,t)=>new _r({innerType:e,typeName:S.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...U(t)});var Hr=class extends J{_parse(t){if(this._getType(t)!==P.nan){let n=this._getOrReturnCtx(t);return $(n,{code:x.invalid_type,expected:P.nan,received:n.parsedType}),N}return{status:"valid",value:t.data}}};Hr.create=e=>new Hr({typeName:S.ZodNaN,...U(e)});var Cv=Symbol("zod_brand"),$n=class extends J{_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}},zn=class e extends J{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?N:s.status==="dirty"?(r.dirty(),or(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?N:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:S.ZodPipeline})}},vr=class extends J{_parse(t){let r=this._def.innerType._parse(t),n=o=>(Dt(o)&&(o.value=Object.freeze(o.value)),o);return Ur(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};vr.create=(e,t)=>new vr({innerType:e,typeName:S.ZodReadonly,...U(t)});function ql(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function Hl(e,t={},r){return e?Ut.create().superRefine((n,o)=>{let s=e(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=ql(t,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=ql(t,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Ut.create()}var Av={object:De.lazycreate},S;(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"})(S||(S={}));var Mv=(e,t={message:`Input not instance of ${e.name}`})=>Hl(r=>r instanceof e,t),Wl=Zt.create,Gl=sr.create,Nv=Hr.create,Lv=ir.create,Kl=ar.create,Dv=cr.create,Zv=Jr.create,Uv=ur.create,qv=dr.create,Jv=Ut.create,Fv=Et.create,Vv=st.create,Bv=Fr.create,Hv=It.create,Ai=De.create,Wv=De.strictCreate,Gv=lr.create,Kv=Lo.create,Xv=pr.create,Yv=gt.create,Qv=Do.create,eb=Vr.create,tb=Br.create,rb=Zo.create,nb=mr.create,ob=fr.create,sb=hr.create,ib=gr.create,ab=qt.create,cb=Xe.create,ub=Le.create,db=yt.create,lb=Xe.createWithPreprocess,pb=zn.create,mb=()=>Wl().optional(),fb=()=>Gl().optional(),hb=()=>Kl().optional(),gb={string:(e=>Zt.create({...e,coerce:!0})),number:(e=>sr.create({...e,coerce:!0})),boolean:(e=>ar.create({...e,coerce:!0})),bigint:(e=>ir.create({...e,coerce:!0})),date:(e=>cr.create({...e,coerce:!0}))};var yb=N;var vb=Object.freeze({status:"aborted"});function v(e,t,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(e),t(a,c);for(let d in i.prototype)d in a||Object.defineProperty(a,d,{value:i.prototype[d].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}var Ot=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Uo={};function Be(e){return e&&Object.assign(Uo,e),Uo}var W={};Ii(W,{BIGINT_FORMAT_RANGES:()=>Yl,Class:()=>Ni,NUMBER_FORMAT_RANGES:()=>Fi,aborted:()=>wr,allowsEval:()=>Ui,assert:()=>Sb,assertEqual:()=>bb,assertIs:()=>kb,assertNever:()=>xb,assertNotEqual:()=>wb,assignProp:()=>Zi,cached:()=>Rn,captureStackTrace:()=>Jo,cleanEnum:()=>Nb,cleanRegex:()=>In,clone:()=>He,createTransparentProxy:()=>Eb,defineLazy:()=>ie,esc:()=>br,escapeRegex:()=>Jt,extend:()=>jb,finalizeIssue:()=>it,floatSafeRemainder:()=>Di,getElementAtPath:()=>$b,getEnumValues:()=>Tn,getLengthableOrigin:()=>On,getParsedType:()=>Rb,getSizableOrigin:()=>Ql,isObject:()=>Wr,isPlainObject:()=>Gr,issue:()=>Vi,joinValues:()=>qo,jsonStringifyReplacer:()=>Li,merge:()=>Cb,normalizeParams:()=>L,nullish:()=>En,numKeys:()=>Tb,omit:()=>Ob,optionalKeys:()=>Ji,partial:()=>Ab,pick:()=>Ib,prefixIssues:()=>_t,primitiveTypes:()=>Xl,promiseAllObject:()=>zb,propertyKeyTypes:()=>qi,randomString:()=>Pb,required:()=>Mb,stringifyPrimitive:()=>Fo,unwrapMessage:()=>Pn});function bb(e){return e}function wb(e){return e}function kb(e){}function xb(e){throw new Error}function Sb(e){}function Tn(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function qo(e,t="|"){return e.map(r=>Fo(r)).join(t)}function Li(e,t){return typeof t=="bigint"?t.toString():t}function Rn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function En(e){return e==null}function In(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Di(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}function ie(e,t,r){Object.defineProperty(e,t,{get(){{let o=r();return e[t]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Zi(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function $b(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function zb(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=n[s];return o})}function Pb(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function br(e){return JSON.stringify(e)}var Jo=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ui=Rn(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Gr(e){if(Wr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Wr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Tb(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var Rb=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}`)}},qi=new Set(["string","number","symbol"]),Xl=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Jt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function He(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 Eb(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,s){return t??(t=e()),Reflect.set(t,n,o,s)},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,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function Fo(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Ji(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Fi={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]},Yl={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Ib(e,t){let r={},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return He(e,{...e._zod.def,shape:r,checks:[]})}function Ob(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return He(e,{...e._zod.def,shape:r,checks:[]})}function jb(e,t){if(!Gr(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 Zi(this,"shape",n),n},checks:[]};return He(e,r)}function Cb(e,t){return He(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Zi(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Ab(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return He(t,{...t._zod.def,shape:o,checks:[]})}function Mb(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new e({type:"nonoptional",innerType:n[s]});return He(t,{...t._zod.def,shape:o,checks:[]})}function wr(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function _t(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Pn(e){return typeof e=="string"?e:e?.message}function it(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=Pn(e.inst?._zod.def?.error?.(e))??Pn(t?.error?.(e))??Pn(r.customError?.(e))??Pn(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Ql(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function On(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Vi(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function Nb(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Ni=class{constructor(...t){}};var ep=(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,Li,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Vo=v("$ZodError",ep),jn=v("$ZodError",ep,{Parent:Error});function Bi(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function Hi(e,t){let r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(e),n}var Wi=e=>(t,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Ot;if(i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>it(c,s,Be())));throw Jo(a,o?.callee),a}return i.value},Gi=Wi(jn),Ki=e=>async(t,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>it(c,s,Be())));throw Jo(a,o?.callee),a}return i.value},Xi=Ki(jn),Yi=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ot;return s.issues.length?{success:!1,error:new(e??Vo)(s.issues.map(i=>it(i,o,Be())))}:{success:!0,data:s.value}},kr=Yi(jn),Qi=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>it(i,o,Be())))}:{success:!0,data:s.value}},xr=Qi(jn);var tp=/^[cC][^\s-]{8,}$/,rp=/^[0-9a-z]+$/,np=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,op=/^[0-9a-vA-V]{20}$/,sp=/^[A-Za-z0-9]{27}$/,ip=/^[a-zA-Z0-9_-]{21}$/,ap=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var cp=/^([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})$/,ea=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 up=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Db="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function dp(){return new RegExp(Db,"u")}var lp=/^(?:(?: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])$/,pp=/^(([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})$/,mp=/^((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])$/,fp=/^(([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])$/,hp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ta=/^[A-Za-z0-9_-]*$/,gp=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var yp=/^\+(?:[0-9]){6,14}[0-9]$/,_p="(?:(?:\\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])))",vp=new RegExp(`^${_p}$`);function bp(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 wp(e){return new RegExp(`^${bp(e)}$`)}function kp(e){let t=bp({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(`^${_p}T(?:${n})$`)}var xp=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Sp=/^\d+$/,$p=/^-?\d+(?:\.\d+)?/i,zp=/true|false/i,Pp=/null/i;var Tp=/^[^A-Z]*$/,Rp=/^[^a-z]*$/;var xe=v("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Ep={number:"number",bigint:"bigint",object:"date"},ra=v("$ZodCheckLessThan",(e,t)=>{xe.init(e,t);let r=Ep[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.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})}}),na=v("$ZodCheckGreaterThan",(e,t)=>{xe.init(e,t);let r=Ep[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.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})}}),Ip=v("$ZodCheckMultipleOf",(e,t)=>{xe.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):Di(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})}}),Op=v("$ZodCheckNumberFormat",(e,t)=>{xe.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Fi[t.format];e._zod.onattach.push(i=>{let a=i._zod.bag;a.format=t.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Sp)}),e._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.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}):i.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<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}});var jp=v("$ZodCheckMaxLength",(e,t)=>{var r;xe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!En(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let i=On(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Cp=v("$ZodCheckMinLength",(e,t)=>{var r;xe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!En(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let i=On(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Ap=v("$ZodCheckLengthEquals",(e,t)=>{var r;xe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!En(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,s=o.length;if(s===t.length)return;let i=On(o),a=s>t.length;n.issues.push({origin:i,...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})}}),Cn=v("$ZodCheckStringFormat",(e,t)=>{var r,n;xe.init(e,t),e._zod.onattach.push(o=>{let s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Mp=v("$ZodCheckRegex",(e,t)=>{Cn.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})}}),Np=v("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Tp),Cn.init(e,t)}),Lp=v("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Rp),Cn.init(e,t)}),Dp=v("$ZodCheckIncludes",(e,t)=>{xe.init(e,t);let r=Jt(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Zp=v("$ZodCheckStartsWith",(e,t)=>{xe.init(e,t);let r=new RegExp(`^${Jt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.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})}}),Up=v("$ZodCheckEndsWith",(e,t)=>{xe.init(e,t);let r=new RegExp(`.*${Jt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.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 qp=v("$ZodCheckOverwrite",(e,t)=>{xe.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Ho=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(`
|
|
11
|
+
`).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
|
|
12
|
+
`))}};var Fp={major:4,minor:0,patch:0};var ne=v("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Fp;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(s,i,a)=>{let c=wr(s),u;for(let d of i){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(c)continue;let l=s.issues.length,p=d._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Ot;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==l&&(c||(c=wr(s,l)))});else{if(s.issues.length===l)continue;c||(c=wr(s,l))}}return u?u.then(()=>s):s};e._zod.run=(s,i)=>{let a=e._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Ot;return a.then(c=>o(c,n,i))}return o(a,n,i)}}e["~standard"]={validate:o=>{try{let s=kr(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return xr(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),An=v("$ZodString",(e,t)=>{ne.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??xp(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}}),ae=v("$ZodStringFormat",(e,t)=>{Cn.init(e,t),An.init(e,t)}),sa=v("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=cp),ae.init(e,t)}),ia=v("$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=ea(n))}else t.pattern??(t.pattern=ea());ae.init(e,t)}),aa=v("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=up),ae.init(e,t)}),ca=v("$ZodURL",(e,t)=>{ae.init(e,t),e._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:gp.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.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("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),ua=v("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=dp()),ae.init(e,t)}),da=v("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ip),ae.init(e,t)}),la=v("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=tp),ae.init(e,t)}),pa=v("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=rp),ae.init(e,t)}),ma=v("$ZodULID",(e,t)=>{t.pattern??(t.pattern=np),ae.init(e,t)}),fa=v("$ZodXID",(e,t)=>{t.pattern??(t.pattern=op),ae.init(e,t)}),ha=v("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=sp),ae.init(e,t)}),em=v("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=kp(t)),ae.init(e,t)}),tm=v("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=vp),ae.init(e,t)}),rm=v("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=wp(t)),ae.init(e,t)}),nm=v("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ap),ae.init(e,t)}),ga=v("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=lp),ae.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),ya=v("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=pp),ae.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})}}}),_a=v("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=mp),ae.init(e,t)}),va=v("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=fp),ae.init(e,t),e._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>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 om(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var ba=v("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=hp),ae.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{om(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Zb(e){if(!ta.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return om(r)}var wa=v("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ta),ae.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{Zb(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),ka=v("$ZodE164",(e,t)=>{t.pattern??(t.pattern=yp),ae.init(e,t)});function Ub(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var xa=v("$ZodJWT",(e,t)=>{ae.init(e,t),e._zod.check=r=>{Ub(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Go=v("$ZodNumber",(e,t)=>{ne.init(e,t),e._zod.pattern=e._zod.bag.pattern??$p,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Sa=v("$ZodNumber",(e,t)=>{Op.init(e,t),Go.init(e,t)}),$a=v("$ZodBoolean",(e,t)=>{ne.init(e,t),e._zod.pattern=zp,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var za=v("$ZodNull",(e,t)=>{ne.init(e,t),e._zod.pattern=Pp,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}});var Pa=v("$ZodUnknown",(e,t)=>{ne.init(e,t),e._zod.parse=r=>r}),Ta=v("$ZodNever",(e,t)=>{ne.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Vp(e,t,r){e.issues.length&&t.issues.push(..._t(r,e.issues)),t.value[r]=e.value}var Ra=v("$ZodArray",(e,t)=>{ne.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>Vp(u,r,i))):Vp(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Wo(e,t,r){e.issues.length&&t.issues.push(..._t(r,e.issues)),t.value[r]=e.value}function Bp(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(..._t(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var Ko=v("$ZodObject",(e,t)=>{ne.init(e,t);let r=Rn(()=>{let l=Object.keys(t.shape);for(let h of l)if(!(t.shape[h]instanceof ne))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);let p=Ji(t.shape);return{shape:t.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set(p)}});ie(e._zod,"propValues",()=>{let l=t.shape,p={};for(let h in l){let f=l[h]._zod;if(f.values){p[h]??(p[h]=new Set);for(let g of f.values)p[h].add(g)}}return p});let n=l=>{let p=new Ho(["shape","payload","ctx"]),h=r.value,f=w=>{let k=br(w);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),y=0;for(let w of h.keys)g[w]=`key_${y++}`;p.write("const newResult = {}");for(let w of h.keys)if(h.optionalKeys.has(w)){let k=g[w];p.write(`const ${k} = ${f(w)};`);let R=br(w);p.write(`
|
|
13
|
+
if (${k}.issues.length) {
|
|
14
|
+
if (input[${R}] === undefined) {
|
|
15
|
+
if (${R} in input) {
|
|
16
|
+
newResult[${R}] = undefined;
|
|
17
|
+
}
|
|
18
|
+
} else {
|
|
19
|
+
payload.issues = payload.issues.concat(
|
|
20
|
+
${k}.issues.map((iss) => ({
|
|
21
|
+
...iss,
|
|
22
|
+
path: iss.path ? [${R}, ...iss.path] : [${R}],
|
|
23
|
+
}))
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
} else if (${k}.value === undefined) {
|
|
27
|
+
if (${R} in input) newResult[${R}] = undefined;
|
|
28
|
+
} else {
|
|
29
|
+
newResult[${R}] = ${k}.value;
|
|
30
|
+
}
|
|
31
|
+
`)}else{let k=g[w];p.write(`const ${k} = ${f(w)};`),p.write(`
|
|
32
|
+
if (${k}.issues.length) payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
|
|
33
|
+
...iss,
|
|
34
|
+
path: iss.path ? [${br(w)}, ...iss.path] : [${br(w)}]
|
|
35
|
+
})));`),p.write(`newResult[${br(w)}] = ${k}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let b=p.compile();return(w,k)=>b(l,w,k)},o,s=Wr,i=!Uo.jitless,c=i&&Ui.value,u=t.catchall,d;e._zod.parse=(l,p)=>{d??(d=r.value);let h=l.value;if(!s(h))return l.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),l;let f=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),l=o(l,p);else{l.value={};let k=d.shape;for(let R of d.keys){let M=k[R],Oe=M._zod.run({value:h[R],issues:[]},p),Ge=M._zod.optin==="optional"&&M._zod.optout==="optional";Oe instanceof Promise?f.push(Oe.then(Dr=>Ge?Bp(Dr,l,R,h):Wo(Dr,l,R))):Ge?Bp(Oe,l,R,h):Wo(Oe,l,R)}}if(!u)return f.length?Promise.all(f).then(()=>l):l;let g=[],y=d.keySet,b=u._zod,w=b.def.type;for(let k of Object.keys(h)){if(y.has(k))continue;if(w==="never"){g.push(k);continue}let R=b.run({value:h[k],issues:[]},p);R instanceof Promise?f.push(R.then(M=>Wo(M,l,k))):Wo(R,l,k)}return g.length&&l.issues.push({code:"unrecognized_keys",keys:g,input:h,inst:e}),f.length?Promise.all(f).then(()=>l):l}});function Hp(e,t,r,n){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(s=>it(s,n,Be())))}),t}var Xo=v("$ZodUnion",(e,t)=>{ne.init(e,t),ie(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ie(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ie(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),ie(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=>In(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of t.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Hp(i,r,e,n)):Hp(s,r,e,n)}}),Ea=v("$ZodDiscriminatedUnion",(e,t)=>{Xo.init(e,t);let r=e._zod.parse;ie(e._zod,"propValues",()=>{let o={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Rn(()=>{let o=t.options,s=new Map;for(let i of o){let a=i._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});e._zod.parse=(o,s)=>{let i=o.value;if(!Wr(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let a=n.value.get(i?.[t.discriminator]);return a?a._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[t.discriminator],inst:e}),o)}}),Ia=v("$ZodIntersection",(e,t)=>{ne.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Wp(r,c,u)):Wp(r,s,i)}});function oa(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(Gr(e)&&Gr(t)){let r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(let s of n){let i=oa(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}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 o=e[n],s=t[n],i=oa(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Wp(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),wr(e))return e;let n=oa(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 Oa=v("$ZodRecord",(e,t)=>{ne.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Gr(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let s=[];if(t.keyType._zod.values){let i=t.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=t.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(d=>{d.issues.length&&r.issues.push(..._t(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(..._t(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=t.keyType._zod.run({value:i,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(u=>it(u,n,Be())),input:i,path:[i],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(..._t(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(..._t(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var ja=v("$ZodEnum",(e,t)=>{ne.init(e,t);let r=Tn(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>qi.has(typeof n)).map(n=>typeof n=="string"?Jt(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),Ca=v("$ZodLiteral",(e,t)=>{ne.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Jt(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});var Aa=v("$ZodTransform",(e,t)=>{ne.init(e,t),e._zod.parse=(r,n)=>{let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Ot;return r.value=o,r}}),Ma=v("$ZodOptional",(e,t)=>{ne.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ie(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ie(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${In(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)}),Na=v("$ZodNullable",(e,t)=>{ne.init(e,t),ie(e._zod,"optin",()=>t.innerType._zod.optin),ie(e._zod,"optout",()=>t.innerType._zod.optout),ie(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${In(r.source)}|null)$`):void 0}),ie(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)}),La=v("$ZodDefault",(e,t)=>{ne.init(e,t),e._zod.optin="optional",ie(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Gp(s,t)):Gp(o,t)}});function Gp(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Da=v("$ZodPrefault",(e,t)=>{ne.init(e,t),e._zod.optin="optional",ie(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))}),Za=v("$ZodNonOptional",(e,t)=>{ne.init(e,t),ie(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 o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Kp(s,e)):Kp(o,e)}});function Kp(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 Ua=v("$ZodCatch",(e,t)=>{ne.init(e,t),e._zod.optin="optional",ie(e._zod,"optout",()=>t.innerType._zod.optout),ie(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>it(i,n,Be()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>it(s,n,Be()))},input:r.value}),r.issues=[]),r)}});var qa=v("$ZodPipe",(e,t)=>{ne.init(e,t),ie(e._zod,"values",()=>t.in._zod.values),ie(e._zod,"optin",()=>t.in._zod.optin),ie(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Xp(s,t,n)):Xp(o,t,n)}});function Xp(e,t,r){return wr(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var Ja=v("$ZodReadonly",(e,t)=>{ne.init(e,t),ie(e._zod,"propValues",()=>t.innerType._zod.propValues),ie(e._zod,"values",()=>t.innerType._zod.values),ie(e._zod,"optin",()=>t.innerType._zod.optin),ie(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(Yp):Yp(o)}});function Yp(e){return e.value=Object.freeze(e.value),e}var Fa=v("$ZodCustom",(e,t)=>{xe.init(e,t),ne.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>Qp(s,r,n,e));Qp(o,r,n,e)}});function Qp(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(Vi(o))}}var qb=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},Jb=()=>{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 ${qb(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Fo(n.values[0])}`:`Invalid option: expected one of ${qo(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=t(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=t(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.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":""}: ${qo(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 sm(){return{localeError:Jb()}}var Mn=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 im(){return new Mn}var Ft=im();function Va(e,t){return new e({type:"string",...L(t)})}function Ba(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...L(t)})}function Yo(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...L(t)})}function Ha(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...L(t)})}function Wa(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...L(t)})}function Ga(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...L(t)})}function Ka(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...L(t)})}function Xa(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...L(t)})}function Ya(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...L(t)})}function Qa(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...L(t)})}function ec(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...L(t)})}function tc(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...L(t)})}function rc(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...L(t)})}function nc(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...L(t)})}function oc(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...L(t)})}function sc(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...L(t)})}function ic(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...L(t)})}function ac(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...L(t)})}function cc(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...L(t)})}function uc(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...L(t)})}function dc(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...L(t)})}function lc(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...L(t)})}function pc(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...L(t)})}function am(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...L(t)})}function cm(e,t){return new e({type:"string",format:"date",check:"string_format",...L(t)})}function um(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...L(t)})}function dm(e,t){return new e({type:"string",format:"duration",check:"string_format",...L(t)})}function mc(e,t){return new e({type:"number",checks:[],...L(t)})}function fc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...L(t)})}function hc(e,t){return new e({type:"boolean",...L(t)})}function gc(e,t){return new e({type:"null",...L(t)})}function yc(e){return new e({type:"unknown"})}function _c(e,t){return new e({type:"never",...L(t)})}function Qo(e,t){return new ra({check:"less_than",...L(t),value:e,inclusive:!1})}function Nn(e,t){return new ra({check:"less_than",...L(t),value:e,inclusive:!0})}function es(e,t){return new na({check:"greater_than",...L(t),value:e,inclusive:!1})}function Ln(e,t){return new na({check:"greater_than",...L(t),value:e,inclusive:!0})}function ts(e,t){return new Ip({check:"multiple_of",...L(t),value:e})}function rs(e,t){return new jp({check:"max_length",...L(t),maximum:e})}function Kr(e,t){return new Cp({check:"min_length",...L(t),minimum:e})}function ns(e,t){return new Ap({check:"length_equals",...L(t),length:e})}function vc(e,t){return new Mp({check:"string_format",format:"regex",...L(t),pattern:e})}function bc(e){return new Np({check:"string_format",format:"lowercase",...L(e)})}function wc(e){return new Lp({check:"string_format",format:"uppercase",...L(e)})}function kc(e,t){return new Dp({check:"string_format",format:"includes",...L(t),includes:e})}function xc(e,t){return new Zp({check:"string_format",format:"starts_with",...L(t),prefix:e})}function Sc(e,t){return new Up({check:"string_format",format:"ends_with",...L(t),suffix:e})}function Sr(e){return new qp({check:"overwrite",tx:e})}function $c(e){return Sr(t=>t.normalize(e))}function zc(){return Sr(e=>e.trim())}function Pc(){return Sr(e=>e.toLowerCase())}function Tc(){return Sr(e=>e.toUpperCase())}function lm(e,t,r){return new e({type:"array",element:t,...L(r)})}function Rc(e,t,r){let n=L(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Ec(e,t,r){return new e({type:"custom",check:"custom",fn:t,...L(r)})}var os=class{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??Ft,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 o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,a);let c=t._zod.toJSONSchema?.();if(c)a.schema=c;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)a.ref=p,this.process(p,l),this.seen.get(p).isParent=!0;else{let h=a.schema;switch(o.type){case"string":{let f=h;f.type="string";let{minimum:g,maximum:y,format:b,patterns:w,contentEncoding:k}=t._zod.bag;if(typeof g=="number"&&(f.minLength=g),typeof y=="number"&&(f.maxLength=y),b&&(f.format=s[b]??b,f.format===""&&delete f.format),k&&(f.contentEncoding=k),w&&w.size>0){let R=[...w];R.length===1?f.pattern=R[0].source:R.length>1&&(a.schema.allOf=[...R.map(M=>({...this.target==="draft-7"?{type:"string"}:{},pattern:M.source}))])}break}case"number":{let f=h,{minimum:g,maximum:y,format:b,multipleOf:w,exclusiveMaximum:k,exclusiveMinimum:R}=t._zod.bag;typeof b=="string"&&b.includes("int")?f.type="integer":f.type="number",typeof R=="number"&&(f.exclusiveMinimum=R),typeof g=="number"&&(f.minimum=g,typeof R=="number"&&(R>=g?delete f.minimum:delete f.exclusiveMinimum)),typeof k=="number"&&(f.exclusiveMaximum=k),typeof y=="number"&&(f.maximum=y,typeof k=="number"&&(k<=y?delete f.maximum:delete f.exclusiveMaximum)),typeof w=="number"&&(f.multipleOf=w);break}case"boolean":{let f=h;f.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":{h.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":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=h,{minimum:g,maximum:y}=t._zod.bag;typeof g=="number"&&(f.minItems=g),typeof y=="number"&&(f.maxItems=y),f.type="array",f.items=this.process(o.element,{...l,path:[...l.path,"items"]});break}case"object":{let f=h;f.type="object",f.properties={};let g=o.shape;for(let w in g)f.properties[w]=this.process(g[w],{...l,path:[...l.path,"properties",w]});let y=new Set(Object.keys(g)),b=new Set([...y].filter(w=>{let k=o.shape[w]._zod;return this.io==="input"?k.optin===void 0:k.optout===void 0}));b.size>0&&(f.required=Array.from(b)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=h;f.anyOf=o.options.map((g,y)=>this.process(g,{...l,path:[...l.path,"anyOf",y]}));break}case"intersection":{let f=h,g=this.process(o.left,{...l,path:[...l.path,"allOf",0]}),y=this.process(o.right,{...l,path:[...l.path,"allOf",1]}),b=k=>"allOf"in k&&Object.keys(k).length===1,w=[...b(g)?g.allOf:[g],...b(y)?y.allOf:[y]];f.allOf=w;break}case"tuple":{let f=h;f.type="array";let g=o.items.map((w,k)=>this.process(w,{...l,path:[...l.path,"prefixItems",k]}));if(this.target==="draft-2020-12"?f.prefixItems=g:f.items=g,o.rest){let w=this.process(o.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?f.items=w:f.additionalItems=w}o.rest&&(f.items=this.process(o.rest,{...l,path:[...l.path,"items"]}));let{minimum:y,maximum:b}=t._zod.bag;typeof y=="number"&&(f.minItems=y),typeof b=="number"&&(f.maxItems=b);break}case"record":{let f=h;f.type="object",f.propertyNames=this.process(o.keyType,{...l,path:[...l.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...l,path:[...l.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 f=h,g=Tn(o.entries);g.every(y=>typeof y=="number")&&(f.type="number"),g.every(y=>typeof y=="string")&&(f.type="string"),f.enum=g;break}case"literal":{let f=h,g=[];for(let y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");g.push(Number(y))}else g.push(y);if(g.length!==0)if(g.length===1){let y=g[0];f.type=y===null?"null":typeof y,f.const=y}else g.every(y=>typeof y=="number")&&(f.type="number"),g.every(y=>typeof y=="string")&&(f.type="string"),g.every(y=>typeof y=="boolean")&&(f.type="string"),g.every(y=>y===null)&&(f.type="null"),f.enum=g;break}case"file":{let f=h,g={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:b,mime:w}=t._zod.bag;y!==void 0&&(g.minLength=y),b!==void 0&&(g.maxLength=b),w?w.length===1?(g.contentMediaType=w[0],Object.assign(f,g)):f.anyOf=w.map(k=>({...g,contentMediaType:k})):Object.assign(f,g);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,l);h.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,l),a.ref=o.innerType;break}case"success":{let f=h;f.type="boolean";break}case"default":{this.process(o.innerType,l),a.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,l),a.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,l),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=h,g=t._zod.pattern;if(!g)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=g.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,l),a.ref=f;break}case"readonly":{this.process(o.innerType,l),a.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,l),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,l),a.ref=o.innerType;break}case"lazy":{let f=t._zod.innerType;this.process(f,l),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(t);return u&&Object.assign(a.schema,u),this.io==="input"&&_e(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},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=d=>{let l=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let g=n.external.registry.get(d[0])?.id,y=n.external.uri??(w=>w);if(g)return{ref:y(g)};let b=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=b,{defId:b,ref:`${y("__shared")}#/${l}/${b}`}}if(d[1]===o)return{ref:"#"};let h=`#/${l}/`,f=d[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:h+f}},i=d=>{if(d[1].schema.$ref)return;let l=d[1],{ref:p,defId:h}=s(d);l.def={...l.schema},h&&(l.defId=h);let f=l.schema;for(let g in f)delete f[g];f.$ref=p};if(n.cycles==="throw")for(let d of this.seen.entries()){let l=d[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
|
|
36
|
+
|
|
37
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of this.seen.entries()){let l=d[1];if(t===d[0]){i(d);continue}if(n.external){let h=n.external.registry.get(d[0])?.id;if(t!==d[0]&&h){i(d);continue}}if(this.metadataRegistry.get(d[0])?.id){i(d);continue}if(l.cycle){i(d);continue}if(l.count>1&&n.reused==="ref"){i(d);continue}}let a=(d,l)=>{let p=this.seen.get(d),h=p.def??p.schema,f={...h};if(p.ref===null)return;let g=p.ref;if(p.ref=null,g){a(g,l);let y=this.seen.get(g).schema;y.$ref&&l.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(y)):(Object.assign(h,y),Object.assign(h,f))}p.isParent||this.override({zodSchema:d,jsonSchema:h,path:p.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let d=n.external.registry.get(t)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let d of this.seen.entries()){let l=d[1];l.def&&l.defId&&(u[l.defId]=l.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function Ic(e,t){if(e instanceof Mn){let n=new os(t),o={};for(let a of e._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:e,uri:t?.uri,defs:o};for(let a of e._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...t,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new os(t);return r.process(e),r.emit(e,t)}function _e(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;switch(o.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 _e(o.element,r);case"object":{for(let s in o.shape)if(_e(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(_e(s,r))return!0;return!1}case"intersection":return _e(o.left,r)||_e(o.right,r);case"tuple":{for(let s of o.items)if(_e(s,r))return!0;return!!(o.rest&&_e(o.rest,r))}case"record":return _e(o.keyType,r)||_e(o.valueType,r);case"map":return _e(o.keyType,r)||_e(o.valueType,r);case"set":return _e(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return _e(o.innerType,r);case"lazy":return _e(o.getter(),r);case"default":return _e(o.innerType,r);case"prefault":return _e(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return _e(o.in,r)||_e(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Sw=v("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");ne.init(e,t),e.def=t,e.parse=(r,n)=>Gi(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>kr(e,r,n),e.parseAsync=async(r,n)=>Xi(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>xr(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)=>He(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e))});var $w=v("ZodMiniObject",(e,t)=>{Ko.init(e,t),Sw.init(e,t),W.defineLazy(e,"shape",()=>t.shape)});function Oc(e,t){let r={type:"object",get shape(){return W.assignProp(this,"shape",{...e}),this.shape},...W.normalizeParams(t)};return new $w(r)}function Ye(e){return!!e._zod}function zr(e){let t=Object.values(e);if(t.length===0)return Oc({});let r=t.every(Ye),n=t.every(o=>!Ye(o));if(r)return Oc(e);if(n)return Ai(e);throw new Error("Mixed Zod versions detected in object shape.")}function Vt(e,t){return Ye(e)?kr(e,t):e.safeParse(t)}async function ss(e,t){return Ye(e)?await xr(e,t):await e.safeParseAsync(t)}function Bt(e){if(!e)return;let t;if(Ye(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Xr(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(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return zr(e)}}if(Ye(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 is(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 mm(e){return e.description}function fm(e){if(Ye(e))return e._zod?.def?.type==="optional";let t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function as(e){if(Ye(e)){let s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.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}var Dn={};Ii(Dn,{ZodISODate:()=>gm,ZodISODateTime:()=>hm,ZodISODuration:()=>_m,ZodISOTime:()=>ym,date:()=>Cc,datetime:()=>jc,duration:()=>Mc,time:()=>Ac});var hm=v("ZodISODateTime",(e,t)=>{em.init(e,t),pe.init(e,t)});function jc(e){return am(hm,e)}var gm=v("ZodISODate",(e,t)=>{tm.init(e,t),pe.init(e,t)});function Cc(e){return cm(gm,e)}var ym=v("ZodISOTime",(e,t)=>{rm.init(e,t),pe.init(e,t)});function Ac(e){return um(ym,e)}var _m=v("ZodISODuration",(e,t)=>{nm.init(e,t),pe.init(e,t)});function Mc(e){return dm(_m,e)}var vm=(e,t)=>{Vo.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Hi(e,r)},flatten:{value:r=>Bi(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},eO=v("ZodError",vm),Zn=v("ZodError",vm,{Parent:Error});var bm=Wi(Zn),wm=Ki(Zn),km=Yi(Zn),xm=Qi(Zn);var ge=v("ZodType",(e,t)=>(ne.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>He(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>bm(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>km(e,r,n),e.parseAsync=async(r,n)=>wm(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>xm(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(kk(r,n)),e.superRefine=r=>e.check(xk(r)),e.overwrite=r=>e.check(Sr(r)),e.optional=()=>fe(e),e.nullable=()=>zm(e),e.nullish=()=>fe(zm(e)),e.nonoptional=r=>hk(e,r),e.array=()=>G(e),e.or=r=>ue([e,r]),e.and=r=>us(e,r),e.transform=r=>Lc(e,Om(r)),e.default=r=>pk(e,r),e.prefault=r=>fk(e,r),e.catch=r=>yk(e,r),e.pipe=r=>Lc(e,r),e.readonly=()=>bk(e),e.describe=r=>{let n=e.clone();return Ft.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Ft.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Ft.get(e);let n=e.clone();return Ft.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Pm=v("_ZodString",(e,t)=>{An.init(e,t),ge.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(vc(...n)),e.includes=(...n)=>e.check(kc(...n)),e.startsWith=(...n)=>e.check(xc(...n)),e.endsWith=(...n)=>e.check(Sc(...n)),e.min=(...n)=>e.check(Kr(...n)),e.max=(...n)=>e.check(rs(...n)),e.length=(...n)=>e.check(ns(...n)),e.nonempty=(...n)=>e.check(Kr(1,...n)),e.lowercase=n=>e.check(bc(n)),e.uppercase=n=>e.check(wc(n)),e.trim=()=>e.check(zc()),e.normalize=(...n)=>e.check($c(...n)),e.toLowerCase=()=>e.check(Pc()),e.toUpperCase=()=>e.check(Tc())}),Cw=v("ZodString",(e,t)=>{An.init(e,t),Pm.init(e,t),e.email=r=>e.check(Ba(Aw,r)),e.url=r=>e.check(Xa(Mw,r)),e.jwt=r=>e.check(pc(Xw,r)),e.emoji=r=>e.check(Ya(Nw,r)),e.guid=r=>e.check(Yo(Sm,r)),e.uuid=r=>e.check(Ha(cs,r)),e.uuidv4=r=>e.check(Wa(cs,r)),e.uuidv6=r=>e.check(Ga(cs,r)),e.uuidv7=r=>e.check(Ka(cs,r)),e.nanoid=r=>e.check(Qa(Lw,r)),e.guid=r=>e.check(Yo(Sm,r)),e.cuid=r=>e.check(ec(Dw,r)),e.cuid2=r=>e.check(tc(Zw,r)),e.ulid=r=>e.check(rc(Uw,r)),e.base64=r=>e.check(uc(Ww,r)),e.base64url=r=>e.check(dc(Gw,r)),e.xid=r=>e.check(nc(qw,r)),e.ksuid=r=>e.check(oc(Jw,r)),e.ipv4=r=>e.check(sc(Fw,r)),e.ipv6=r=>e.check(ic(Vw,r)),e.cidrv4=r=>e.check(ac(Bw,r)),e.cidrv6=r=>e.check(cc(Hw,r)),e.e164=r=>e.check(lc(Kw,r)),e.datetime=r=>e.check(jc(r)),e.date=r=>e.check(Cc(r)),e.time=r=>e.check(Ac(r)),e.duration=r=>e.check(Mc(r))});function _(e){return Va(Cw,e)}var pe=v("ZodStringFormat",(e,t)=>{ae.init(e,t),Pm.init(e,t)}),Aw=v("ZodEmail",(e,t)=>{aa.init(e,t),pe.init(e,t)});var Sm=v("ZodGUID",(e,t)=>{sa.init(e,t),pe.init(e,t)});var cs=v("ZodUUID",(e,t)=>{ia.init(e,t),pe.init(e,t)});var Mw=v("ZodURL",(e,t)=>{ca.init(e,t),pe.init(e,t)});var Nw=v("ZodEmoji",(e,t)=>{ua.init(e,t),pe.init(e,t)});var Lw=v("ZodNanoID",(e,t)=>{da.init(e,t),pe.init(e,t)});var Dw=v("ZodCUID",(e,t)=>{la.init(e,t),pe.init(e,t)});var Zw=v("ZodCUID2",(e,t)=>{pa.init(e,t),pe.init(e,t)});var Uw=v("ZodULID",(e,t)=>{ma.init(e,t),pe.init(e,t)});var qw=v("ZodXID",(e,t)=>{fa.init(e,t),pe.init(e,t)});var Jw=v("ZodKSUID",(e,t)=>{ha.init(e,t),pe.init(e,t)});var Fw=v("ZodIPv4",(e,t)=>{ga.init(e,t),pe.init(e,t)});var Vw=v("ZodIPv6",(e,t)=>{ya.init(e,t),pe.init(e,t)});var Bw=v("ZodCIDRv4",(e,t)=>{_a.init(e,t),pe.init(e,t)});var Hw=v("ZodCIDRv6",(e,t)=>{va.init(e,t),pe.init(e,t)});var Ww=v("ZodBase64",(e,t)=>{ba.init(e,t),pe.init(e,t)});var Gw=v("ZodBase64URL",(e,t)=>{wa.init(e,t),pe.init(e,t)});var Kw=v("ZodE164",(e,t)=>{ka.init(e,t),pe.init(e,t)});var Xw=v("ZodJWT",(e,t)=>{xa.init(e,t),pe.init(e,t)});var Tm=v("ZodNumber",(e,t)=>{Go.init(e,t),ge.init(e,t),e.gt=(n,o)=>e.check(es(n,o)),e.gte=(n,o)=>e.check(Ln(n,o)),e.min=(n,o)=>e.check(Ln(n,o)),e.lt=(n,o)=>e.check(Qo(n,o)),e.lte=(n,o)=>e.check(Nn(n,o)),e.max=(n,o)=>e.check(Nn(n,o)),e.int=n=>e.check($m(n)),e.safe=n=>e.check($m(n)),e.positive=n=>e.check(es(0,n)),e.nonnegative=n=>e.check(Ln(0,n)),e.negative=n=>e.check(Qo(0,n)),e.nonpositive=n=>e.check(Nn(0,n)),e.multipleOf=(n,o)=>e.check(ts(n,o)),e.step=(n,o)=>e.check(ts(n,o)),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 te(e){return mc(Tm,e)}var Yw=v("ZodNumberFormat",(e,t)=>{Sa.init(e,t),Tm.init(e,t)});function $m(e){return fc(Yw,e)}var Qw=v("ZodBoolean",(e,t)=>{$a.init(e,t),ge.init(e,t)});function be(e){return hc(Qw,e)}var ek=v("ZodNull",(e,t)=>{za.init(e,t),ge.init(e,t)});function Rm(e){return gc(ek,e)}var tk=v("ZodUnknown",(e,t)=>{Pa.init(e,t),ge.init(e,t)});function me(){return yc(tk)}var rk=v("ZodNever",(e,t)=>{Ta.init(e,t),ge.init(e,t)});function nk(e){return _c(rk,e)}var ok=v("ZodArray",(e,t)=>{Ra.init(e,t),ge.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Kr(r,n)),e.nonempty=r=>e.check(Kr(1,r)),e.max=(r,n)=>e.check(rs(r,n)),e.length=(r,n)=>e.check(ns(r,n)),e.unwrap=()=>e.element});function G(e,t){return lm(ok,e,t)}var Em=v("ZodObject",(e,t)=>{Ko.init(e,t),ge.init(e,t),W.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Ze(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:me()}),e.loose=()=>e.clone({...e._zod.def,catchall:me()}),e.strict=()=>e.clone({...e._zod.def,catchall:nk()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>W.extend(e,r),e.merge=r=>W.merge(e,r),e.pick=r=>W.pick(e,r),e.omit=r=>W.omit(e,r),e.partial=(...r)=>W.partial(jm,e,r[0]),e.required=(...r)=>W.required(Cm,e,r[0])});function T(e,t){let r={type:"object",get shape(){return W.assignProp(this,"shape",{...e}),this.shape},...W.normalizeParams(t)};return new Em(r)}function je(e,t){return new Em({type:"object",get shape(){return W.assignProp(this,"shape",{...e}),this.shape},catchall:me(),...W.normalizeParams(t)})}var Im=v("ZodUnion",(e,t)=>{Xo.init(e,t),ge.init(e,t),e.options=t.options});function ue(e,t){return new Im({type:"union",options:e,...W.normalizeParams(t)})}var sk=v("ZodDiscriminatedUnion",(e,t)=>{Im.init(e,t),Ea.init(e,t)});function Dc(e,t,r){return new sk({type:"union",options:t,discriminator:e,...W.normalizeParams(r)})}var ik=v("ZodIntersection",(e,t)=>{Ia.init(e,t),ge.init(e,t)});function us(e,t){return new ik({type:"intersection",left:e,right:t})}var ak=v("ZodRecord",(e,t)=>{Oa.init(e,t),ge.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ce(e,t,r){return new ak({type:"record",keyType:e,valueType:t,...W.normalizeParams(r)})}var Nc=v("ZodEnum",(e,t)=>{ja.init(e,t),ge.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Nc({...t,checks:[],...W.normalizeParams(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Nc({...t,checks:[],...W.normalizeParams(o),entries:s})}});function Ze(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Nc({type:"enum",entries:r,...W.normalizeParams(t)})}var ck=v("ZodLiteral",(e,t)=>{Ca.init(e,t),ge.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 j(e,t){return new ck({type:"literal",values:Array.isArray(e)?e:[e],...W.normalizeParams(t)})}var uk=v("ZodTransform",(e,t)=>{Aa.init(e,t),ge.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(W.issue(s,r.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),r.issues.push(W.issue(i))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Om(e){return new uk({type:"transform",transform:e})}var jm=v("ZodOptional",(e,t)=>{Ma.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function fe(e){return new jm({type:"optional",innerType:e})}var dk=v("ZodNullable",(e,t)=>{Na.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function zm(e){return new dk({type:"nullable",innerType:e})}var lk=v("ZodDefault",(e,t)=>{La.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function pk(e,t){return new lk({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var mk=v("ZodPrefault",(e,t)=>{Da.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function fk(e,t){return new mk({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Cm=v("ZodNonOptional",(e,t)=>{Za.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function hk(e,t){return new Cm({type:"nonoptional",innerType:e,...W.normalizeParams(t)})}var gk=v("ZodCatch",(e,t)=>{Ua.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function yk(e,t){return new gk({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var _k=v("ZodPipe",(e,t)=>{qa.init(e,t),ge.init(e,t),e.in=t.in,e.out=t.out});function Lc(e,t){return new _k({type:"pipe",in:e,out:t})}var vk=v("ZodReadonly",(e,t)=>{Ja.init(e,t),ge.init(e,t)});function bk(e){return new vk({type:"readonly",innerType:e})}var Am=v("ZodCustom",(e,t)=>{Fa.init(e,t),ge.init(e,t)});function wk(e){let t=new xe({check:"custom"});return t._zod.check=e,t}function Mm(e,t){return Rc(Am,e??(()=>!0),t)}function kk(e,t={}){return Ec(Am,e,t)}function xk(e){let t=wk(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(W.issue(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(W.issue(o))}},e(r.value,r)));return t}function Zc(e,t){return Lc(Om(e),t)}Be(sm());var qc="2025-11-25";var Nm=[qc,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ht="io.modelcontextprotocol/related-task",ls="2.0",ve=Mm(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Lm=ue([_(),te().int()]),Dm=_(),fO=je({ttl:te().optional(),pollInterval:te().optional()}),Sk=T({ttl:te().optional()}),$k=T({taskId:_()}),Jc=je({progressToken:Lm.optional(),[Ht]:$k.optional()}),We=T({_meta:Jc.optional()}),Un=We.extend({task:Sk.optional()}),Zm=e=>Un.safeParse(e).success,Se=T({method:_(),params:We.loose().optional()}),Qe=T({_meta:Jc.optional()}),et=T({method:_(),params:Qe.loose().optional()}),$e=je({_meta:Jc.optional()}),ps=ue([_(),te().int()]),Um=T({jsonrpc:j(ls),id:ps,...Se.shape}).strict(),Fc=e=>Um.safeParse(e).success,qm=T({jsonrpc:j(ls),...et.shape}).strict(),Jm=e=>qm.safeParse(e).success,Vc=T({jsonrpc:j(ls),id:ps,result:$e}).strict(),qn=e=>Vc.safeParse(e).success;var A;(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"})(A||(A={}));var Bc=T({jsonrpc:j(ls),id:ps.optional(),error:T({code:te().int(),message:_(),data:me().optional()})}).strict();var Fm=e=>Bc.safeParse(e).success;var Vm=ue([Um,qm,Vc,Bc]),hO=ue([Vc,Bc]),ms=$e.strict(),zk=Qe.extend({requestId:ps.optional(),reason:_().optional()}),fs=et.extend({method:j("notifications/cancelled"),params:zk}),Pk=T({src:_(),mimeType:_().optional(),sizes:G(_()).optional(),theme:Ze(["light","dark"]).optional()}),Jn=T({icons:G(Pk).optional()}),Yr=T({name:_(),title:_().optional()}),Bm=Yr.extend({...Yr.shape,...Jn.shape,version:_(),websiteUrl:_().optional(),description:_().optional()}),Tk=us(T({applyDefaults:be().optional()}),ce(_(),me())),Rk=Zc(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,us(T({form:Tk.optional(),url:ve.optional()}),ce(_(),me()).optional())),Ek=je({list:ve.optional(),cancel:ve.optional(),requests:je({sampling:je({createMessage:ve.optional()}).optional(),elicitation:je({create:ve.optional()}).optional()}).optional()}),Ik=je({list:ve.optional(),cancel:ve.optional(),requests:je({tools:je({call:ve.optional()}).optional()}).optional()}),Ok=T({experimental:ce(_(),ve).optional(),sampling:T({context:ve.optional(),tools:ve.optional()}).optional(),elicitation:Rk.optional(),roots:T({listChanged:be().optional()}).optional(),tasks:Ek.optional(),extensions:ce(_(),ve).optional()}),jk=We.extend({protocolVersion:_(),capabilities:Ok,clientInfo:Bm}),Hc=Se.extend({method:j("initialize"),params:jk});var Ck=T({experimental:ce(_(),ve).optional(),logging:ve.optional(),completions:ve.optional(),prompts:T({listChanged:be().optional()}).optional(),resources:T({subscribe:be().optional(),listChanged:be().optional()}).optional(),tools:T({listChanged:be().optional()}).optional(),tasks:Ik.optional(),extensions:ce(_(),ve).optional()}),Ak=$e.extend({protocolVersion:_(),capabilities:Ck,serverInfo:Bm,instructions:_().optional()}),Wc=et.extend({method:j("notifications/initialized"),params:Qe.optional()});var hs=Se.extend({method:j("ping"),params:We.optional()}),Mk=T({progress:te(),total:fe(te()),message:fe(_())}),Nk=T({...Qe.shape,...Mk.shape,progressToken:Lm}),gs=et.extend({method:j("notifications/progress"),params:Nk}),Lk=We.extend({cursor:Dm.optional()}),Fn=Se.extend({params:Lk.optional()}),Vn=$e.extend({nextCursor:Dm.optional()}),Dk=Ze(["working","input_required","completed","failed","cancelled"]),Bn=T({taskId:_(),status:Dk,ttl:ue([te(),Rm()]),createdAt:_(),lastUpdatedAt:_(),pollInterval:fe(te()),statusMessage:fe(_())}),Qr=$e.extend({task:Bn}),Zk=Qe.merge(Bn),Hn=et.extend({method:j("notifications/tasks/status"),params:Zk}),ys=Se.extend({method:j("tasks/get"),params:We.extend({taskId:_()})}),_s=$e.merge(Bn),vs=Se.extend({method:j("tasks/result"),params:We.extend({taskId:_()})}),gO=$e.loose(),bs=Fn.extend({method:j("tasks/list")}),ws=Vn.extend({tasks:G(Bn)}),ks=Se.extend({method:j("tasks/cancel"),params:We.extend({taskId:_()})}),Hm=$e.merge(Bn),Wm=T({uri:_(),mimeType:fe(_()),_meta:ce(_(),me()).optional()}),Gm=Wm.extend({text:_()}),Gc=_().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Km=Wm.extend({blob:Gc}),Wn=Ze(["user","assistant"]),en=T({audience:G(Wn).optional(),priority:te().min(0).max(1).optional(),lastModified:Dn.datetime({offset:!0}).optional()}),Xm=T({...Yr.shape,...Jn.shape,uri:_(),description:fe(_()),mimeType:fe(_()),size:fe(te()),annotations:en.optional(),_meta:fe(je({}))}),Uk=T({...Yr.shape,...Jn.shape,uriTemplate:_(),description:fe(_()),mimeType:fe(_()),annotations:en.optional(),_meta:fe(je({}))}),tn=Fn.extend({method:j("resources/list")}),qk=Vn.extend({resources:G(Xm)}),rn=Fn.extend({method:j("resources/templates/list")}),Jk=Vn.extend({resourceTemplates:G(Uk)}),Kc=We.extend({uri:_()}),Fk=Kc,xs=Se.extend({method:j("resources/read"),params:Fk}),Vk=$e.extend({contents:G(ue([Gm,Km]))}),Bk=et.extend({method:j("notifications/resources/list_changed"),params:Qe.optional()}),Hk=Kc,Wk=Se.extend({method:j("resources/subscribe"),params:Hk}),Gk=Kc,Kk=Se.extend({method:j("resources/unsubscribe"),params:Gk}),Xk=Qe.extend({uri:_()}),Yk=et.extend({method:j("notifications/resources/updated"),params:Xk}),Qk=T({name:_(),description:fe(_()),required:fe(be())}),ex=T({...Yr.shape,...Jn.shape,description:fe(_()),arguments:fe(G(Qk)),_meta:fe(je({}))}),Ss=Fn.extend({method:j("prompts/list")}),tx=Vn.extend({prompts:G(ex)}),rx=We.extend({name:_(),arguments:ce(_(),_()).optional()}),$s=Se.extend({method:j("prompts/get"),params:rx}),Xc=T({type:j("text"),text:_(),annotations:en.optional(),_meta:ce(_(),me()).optional()}),Yc=T({type:j("image"),data:Gc,mimeType:_(),annotations:en.optional(),_meta:ce(_(),me()).optional()}),Qc=T({type:j("audio"),data:Gc,mimeType:_(),annotations:en.optional(),_meta:ce(_(),me()).optional()}),nx=T({type:j("tool_use"),name:_(),id:_(),input:ce(_(),me()),_meta:ce(_(),me()).optional()}),ox=T({type:j("resource"),resource:ue([Gm,Km]),annotations:en.optional(),_meta:ce(_(),me()).optional()}),sx=Xm.extend({type:j("resource_link")}),eu=ue([Xc,Yc,Qc,sx,ox]),ix=T({role:Wn,content:eu}),ax=$e.extend({description:_().optional(),messages:G(ix)}),cx=et.extend({method:j("notifications/prompts/list_changed"),params:Qe.optional()}),ux=T({title:_().optional(),readOnlyHint:be().optional(),destructiveHint:be().optional(),idempotentHint:be().optional(),openWorldHint:be().optional()}),dx=T({taskSupport:Ze(["required","optional","forbidden"]).optional()}),Ym=T({...Yr.shape,...Jn.shape,description:_().optional(),inputSchema:T({type:j("object"),properties:ce(_(),ve).optional(),required:G(_()).optional()}).catchall(me()),outputSchema:T({type:j("object"),properties:ce(_(),ve).optional(),required:G(_()).optional()}).catchall(me()).optional(),annotations:ux.optional(),execution:dx.optional(),_meta:ce(_(),me()).optional()}),zs=Fn.extend({method:j("tools/list")}),lx=Vn.extend({tools:G(Ym)}),Ps=$e.extend({content:G(eu).default([]),structuredContent:ce(_(),me()).optional(),isError:be().optional()}),yO=Ps.or($e.extend({toolResult:me()})),px=Un.extend({name:_(),arguments:ce(_(),me()).optional()}),nn=Se.extend({method:j("tools/call"),params:px}),mx=et.extend({method:j("notifications/tools/list_changed"),params:Qe.optional()}),_O=T({autoRefresh:be().default(!0),debounceMs:te().int().nonnegative().default(300)}),Gn=Ze(["debug","info","notice","warning","error","critical","alert","emergency"]),fx=We.extend({level:Gn}),tu=Se.extend({method:j("logging/setLevel"),params:fx}),hx=Qe.extend({level:Gn,logger:_().optional(),data:me()}),gx=et.extend({method:j("notifications/message"),params:hx}),yx=T({name:_().optional()}),_x=T({hints:G(yx).optional(),costPriority:te().min(0).max(1).optional(),speedPriority:te().min(0).max(1).optional(),intelligencePriority:te().min(0).max(1).optional()}),vx=T({mode:Ze(["auto","required","none"]).optional()}),bx=T({type:j("tool_result"),toolUseId:_().describe("The unique identifier for the corresponding tool call."),content:G(eu).default([]),structuredContent:T({}).loose().optional(),isError:be().optional(),_meta:ce(_(),me()).optional()}),wx=Dc("type",[Xc,Yc,Qc]),ds=Dc("type",[Xc,Yc,Qc,nx,bx]),kx=T({role:Wn,content:ue([ds,G(ds)]),_meta:ce(_(),me()).optional()}),xx=Un.extend({messages:G(kx),modelPreferences:_x.optional(),systemPrompt:_().optional(),includeContext:Ze(["none","thisServer","allServers"]).optional(),temperature:te().optional(),maxTokens:te().int(),stopSequences:G(_()).optional(),metadata:ve.optional(),tools:G(Ym).optional(),toolChoice:vx.optional()}),Sx=Se.extend({method:j("sampling/createMessage"),params:xx}),Kn=$e.extend({model:_(),stopReason:fe(Ze(["endTurn","stopSequence","maxTokens"]).or(_())),role:Wn,content:wx}),ru=$e.extend({model:_(),stopReason:fe(Ze(["endTurn","stopSequence","maxTokens","toolUse"]).or(_())),role:Wn,content:ue([ds,G(ds)])}),$x=T({type:j("boolean"),title:_().optional(),description:_().optional(),default:be().optional()}),zx=T({type:j("string"),title:_().optional(),description:_().optional(),minLength:te().optional(),maxLength:te().optional(),format:Ze(["email","uri","date","date-time"]).optional(),default:_().optional()}),Px=T({type:Ze(["number","integer"]),title:_().optional(),description:_().optional(),minimum:te().optional(),maximum:te().optional(),default:te().optional()}),Tx=T({type:j("string"),title:_().optional(),description:_().optional(),enum:G(_()),default:_().optional()}),Rx=T({type:j("string"),title:_().optional(),description:_().optional(),oneOf:G(T({const:_(),title:_()})),default:_().optional()}),Ex=T({type:j("string"),title:_().optional(),description:_().optional(),enum:G(_()),enumNames:G(_()).optional(),default:_().optional()}),Ix=ue([Tx,Rx]),Ox=T({type:j("array"),title:_().optional(),description:_().optional(),minItems:te().optional(),maxItems:te().optional(),items:T({type:j("string"),enum:G(_())}),default:G(_()).optional()}),jx=T({type:j("array"),title:_().optional(),description:_().optional(),minItems:te().optional(),maxItems:te().optional(),items:T({anyOf:G(T({const:_(),title:_()}))}),default:G(_()).optional()}),Cx=ue([Ox,jx]),Ax=ue([Ex,Ix,Cx]),Mx=ue([Ax,$x,zx,Px]),Nx=Un.extend({mode:j("form").optional(),message:_(),requestedSchema:T({type:j("object"),properties:ce(_(),Mx),required:G(_()).optional()})}),Lx=Un.extend({mode:j("url"),message:_(),elicitationId:_(),url:_().url()}),Dx=ue([Nx,Lx]),Zx=Se.extend({method:j("elicitation/create"),params:Dx}),Ux=Qe.extend({elicitationId:_()}),qx=et.extend({method:j("notifications/elicitation/complete"),params:Ux}),on=$e.extend({action:Ze(["accept","decline","cancel"]),content:Zc(e=>e===null?void 0:e,ce(_(),ue([_(),te(),be(),G(_())])).optional())}),Jx=T({type:j("ref/resource"),uri:_()});var Fx=T({type:j("ref/prompt"),name:_()}),Vx=We.extend({ref:ue([Fx,Jx]),argument:T({name:_(),value:_()}),context:T({arguments:ce(_(),_()).optional()}).optional()}),Ts=Se.extend({method:j("completion/complete"),params:Vx});function Qm(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function ef(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var Bx=$e.extend({completion:je({values:G(_()).max(100),total:fe(te().int()),hasMore:fe(be())})}),Hx=T({uri:_().startsWith("file://"),name:_().optional(),_meta:ce(_(),me()).optional()}),Wx=Se.extend({method:j("roots/list"),params:We.optional()}),nu=$e.extend({roots:G(Hx)}),Gx=et.extend({method:j("notifications/roots/list_changed"),params:Qe.optional()}),vO=ue([hs,Hc,Ts,tu,$s,Ss,tn,rn,xs,Wk,Kk,nn,zs,ys,vs,bs,ks]),bO=ue([fs,gs,Wc,Gx,Hn]),wO=ue([ms,Kn,ru,on,nu,_s,ws,Qr]),kO=ue([hs,Sx,Zx,Wx,ys,vs,bs,ks]),xO=ue([fs,gs,gx,Yk,Bk,mx,cx,Hn,qx]),SO=ue([ms,Ak,Bx,ax,tx,qk,Jk,Vk,Ps,lx,_s,ws,Qr]),O=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===A.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Uc(o.elicitations,r)}return new e(t,r,n)}},Uc=class extends O{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(A.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function Wt(e){return e==="completed"||e==="failed"||e==="cancelled"}var rf=Symbol("Let zodToJsonSchema decide on which parser to use");var tf={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"},nf=e=>typeof e=="string"?{...tf,name:e}:{...tf,...e};var of=e=>{let t=nf(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,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function ou(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function K(e,t,r,n,o){e[t]=r,ou(e,t,n,o)}var Rs=(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 he(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Rs(t,e.currentPath):t.join("/")}}function sf(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==S.ZodAny&&(r.items=D(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&K(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&K(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(K(r,"minItems",e.exactLength.value,e.exactLength.message,t),K(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function af(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?K(r,"minimum",n.value,n.message,t):K(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),K(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?K(r,"maximum",n.value,n.message,t):K(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),K(r,"maximum",n.value,n.message,t));break;case"multipleOf":K(r,"multipleOf",n.value,n.message,t);break}return r}function cf(){return{type:"boolean"}}function Es(e,t){return D(e.type._def,t)}var uf=(e,t)=>D(e.innerType._def,t);function su(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>su(e,t,o))};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 Kx(e,t)}}var Kx=(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":K(r,"minimum",n.value,n.message,t);break;case"max":K(r,"maximum",n.value,n.message,t);break}return r};function df(e,t){return{...D(e.innerType._def,t),default:e.defaultValue()}}function lf(e,t){return t.effectStrategy==="input"?D(e.schema._def,t):he(t)}function pf(e){return{type:"string",enum:Array.from(e.values)}}var Xx=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function mf(e,t){let r=[D(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),D(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(Xx(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function ff(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 iu,at={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:()=>(iu===void 0&&(iu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),iu),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 Is(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":K(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":K(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":ct(r,"email",n.message,t);break;case"format:idn-email":ct(r,"idn-email",n.message,t);break;case"pattern:zod":Ce(r,at.email,n.message,t);break}break;case"url":ct(r,"uri",n.message,t);break;case"uuid":ct(r,"uuid",n.message,t);break;case"regex":Ce(r,n.regex,n.message,t);break;case"cuid":Ce(r,at.cuid,n.message,t);break;case"cuid2":Ce(r,at.cuid2,n.message,t);break;case"startsWith":Ce(r,RegExp(`^${au(n.value,t)}`),n.message,t);break;case"endsWith":Ce(r,RegExp(`${au(n.value,t)}$`),n.message,t);break;case"datetime":ct(r,"date-time",n.message,t);break;case"date":ct(r,"date",n.message,t);break;case"time":ct(r,"time",n.message,t);break;case"duration":ct(r,"duration",n.message,t);break;case"length":K(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),K(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{Ce(r,RegExp(au(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&ct(r,"ipv4",n.message,t),n.version!=="v4"&&ct(r,"ipv6",n.message,t);break}case"base64url":Ce(r,at.base64url,n.message,t);break;case"jwt":Ce(r,at.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Ce(r,at.ipv4Cidr,n.message,t),n.version!=="v4"&&Ce(r,at.ipv6Cidr,n.message,t);break}case"emoji":Ce(r,at.emoji(),n.message,t);break;case"ulid":{Ce(r,at.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{ct(r,"binary",n.message,t);break}case"contentEncoding:base64":{K(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{Ce(r,at.base64,n.message,t);break}}break}case"nanoid":Ce(r,at.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function au(e,t){return t.patternStrategy==="escape"?Qx(e):e}var Yx=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Qx(e){let t="";for(let r=0;r<e.length;r++)Yx.has(e[r])||(t+="\\"),t+=e[r];return t}function ct(e,t,r,n){e.format||e.anyOf?.some(o=>o.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}}})):K(e,"format",t,r,n)}function Ce(e,t,r,n){e.pattern||e.allOf?.some(o=>o.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:hf(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):K(e,"pattern",hf(t,n),r,n)}function hf(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,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
38
|
+
]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
|
|
39
|
+
]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
|
|
40
|
+
`:`[${n[c]}\r
|
|
41
|
+
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}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 o}function Os(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===S.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:D(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??he(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:D(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===S.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Is(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===S.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===S.ZodBranded&&e.keyType._def.type._def.typeName===S.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=Es(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function gf(e,t){if(t.mapStrategy==="record")return Os(e,t);let r=D(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||he(t),n=D(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||he(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function yf(e){let t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function _f(e){return e.target==="openAi"?void 0:{not:he({...e,currentPath:[...e.currentPath,"not"]})}}function vf(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Xn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function wf(e,t){if(t.target==="openApi3")return bf(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Xn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Xn[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return bf(e,t)}var bf=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>D(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function kf(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:Xn[e.innerType._def.typeName],nullable:!0}:{type:[Xn[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=D(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=D(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function xf(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",ou(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?K(r,"minimum",n.value,n.message,t):K(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),K(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?K(r,"maximum",n.value,n.message,t):K(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),K(r,"maximum",n.value,n.message,t));break;case"multipleOf":K(r,"multipleOf",n.value,n.message,t);break}return r}function Sf(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],s=e.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=t0(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let d=D(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});d!==void 0&&(n.properties[a]=d,u||o.push(a))}o.length&&(n.required=o);let i=e0(e,t);return i!==void 0&&(n.additionalProperties=i),n}function e0(e,t){if(e.catchall._def.typeName!=="ZodNever")return D(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 t0(e){try{return e.isOptional()}catch{return!0}}var $f=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return D(e.innerType._def,t);let r=D(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:he(t)},r]}:he(t)};var zf=(e,t)=>{if(t.pipeStrategy==="input")return D(e.in._def,t);if(t.pipeStrategy==="output")return D(e.out._def,t);let r=D(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=D(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Pf(e,t){return D(e.type._def,t)}function Tf(e,t){let n={type:"array",uniqueItems:!0,items:D(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&K(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&K(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function Rf(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>D(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:D(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>D(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Ef(e){return{not:he(e)}}function If(e){return he(e)}var Of=(e,t)=>D(e.innerType._def,t);var jf=(e,t,r)=>{switch(t){case S.ZodString:return Is(e,r);case S.ZodNumber:return xf(e,r);case S.ZodObject:return Sf(e,r);case S.ZodBigInt:return af(e,r);case S.ZodBoolean:return cf();case S.ZodDate:return su(e,r);case S.ZodUndefined:return Ef(r);case S.ZodNull:return vf(r);case S.ZodArray:return sf(e,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return wf(e,r);case S.ZodIntersection:return mf(e,r);case S.ZodTuple:return Rf(e,r);case S.ZodRecord:return Os(e,r);case S.ZodLiteral:return ff(e,r);case S.ZodEnum:return pf(e);case S.ZodNativeEnum:return yf(e);case S.ZodNullable:return kf(e,r);case S.ZodOptional:return $f(e,r);case S.ZodMap:return gf(e,r);case S.ZodSet:return Tf(e,r);case S.ZodLazy:return()=>e.getter()._def;case S.ZodPromise:return Pf(e,r);case S.ZodNaN:case S.ZodNever:return _f(r);case S.ZodEffects:return lf(e,r);case S.ZodAny:return he(r);case S.ZodUnknown:return If(r);case S.ZodDefault:return df(e,r);case S.ZodBranded:return Es(e,r);case S.ZodReadonly:return Of(e,r);case S.ZodCatch:return uf(e,r);case S.ZodPipeline:return zf(e,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(t)}};function D(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==rf)return a}if(n&&!r){let a=r0(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let s=jf(e,e.typeName,t),i=typeof s=="function"?D(s(),t):s;if(i&&n0(e,t,i),t.postProcess){let a=t.postProcess(i,e,t);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var r0=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Rs(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`),he(t)):t.$refStrategy==="seen"?he(t):void 0}},n0=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var cu=(e,t)=>{let r=of(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,d])=>({...c,[u]:D(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??he(r)}),{}):void 0,o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=D(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??he(r),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(s.title=i),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=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};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 o0(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function uu(e,t){return Ye(e)?Ic(e,{target:o0(t?.target),io:t?.pipeStrategy??"input"}):cu(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function du(e){let r=Bt(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=as(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function lu(e,t){let r=Vt(e,t);if(!r.success)throw r.error;return r.data}var s0=6e4,js=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(fs,r=>{this._oncancel(r)}),this.setNotificationHandler(gs,r=>{this._onprogress(r)}),this.setRequestHandler(hs,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ys,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new O(A.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(vs,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,p=new O(l.error.code,l.error.message,l.error.data);d(p)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new O(A.InvalidParams,`Task not found: ${s}`);if(!Wt(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Wt(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Ht]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(bs,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new O(A.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ks,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new O(A.InvalidParams,`Task not found: ${r.params.taskId}`);if(Wt(o.status))throw new O(A.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new O(A.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof O?o:new O(A.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_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),O.fromError(A.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=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),qn(s)||Fm(s)?this._onresponse(s):Fc(s)?this._onrequest(s,i):Jm(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},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=O.fromError(A.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,o=this._transport,s=t.params?._meta?.[Ht]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:t.id,error:{code:A.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):o?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);let a=Zm(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:t.id};s&&(l.relatedTask={taskId:s}),await this.notification(d,l)},sendRequest:async(d,l,p)=>{if(i.signal.aborted)throw new O(A.ConnectionClosed,"Request was cancelled");let h={...p,relatedRequestId:t.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});let f=h.relatedTask?.taskId??s;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(d,l,h)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,u)).then(async d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(d.code)?d.code:A.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===i&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),qn(t))n(t);else{let i=new O(t.error.code,t.error.message,t.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===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 s=!1;if(qn(t)&&t.result&&typeof t.result=="object"){let i=t.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),qn(t))o(t);else{let i=O.fromError(t.error.code,t.error.message,t.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(i){yield{type:"error",error:i instanceof O?i:new O(A.InternalError,String(i))}}return}let s;try{let i=await this.request(t,Qr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new O(A.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Wt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new O(A.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new O(A.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof O?i:new O(A.InternalError,String(i))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=w=>{d(w)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(w){l(w);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,h={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),h.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Ht]:c}});let f=w=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(w)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(R=>this._onerror(new Error(`Failed to send cancellation: ${R}`)));let k=w instanceof O?w:new O(A.RequestTimeout,String(w));d(k)};this._responseHandlers.set(p,w=>{if(!n?.signal?.aborted){if(w instanceof Error)return d(w);try{let k=Vt(r,w.result);k.success?u(k.data):d(k.error)}catch(k){d(k)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let g=n?.timeout??s0,y=()=>f(O.fromError(A.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let b=c?.taskId;if(b){let w=k=>{let R=this._responseHandlers.get(p);R?R(k):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,w),this._enqueueTaskMessage(b,{type:"request",message:h,timestamp:Date.now()}).catch(k=>{this._cleanupTimeout(p),d(k)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(w=>{this._cleanupTimeout(p),d(w)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},_s,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},ws,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Hm,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||{},[Ht]: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||{},[Ht]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Ht]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){let n=du(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=lu(t,o);return Promise.resolve(r(i,s))})}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=du(t);this._notificationHandlers.set(n,o=>{let s=lu(t,o);return Promise.resolve(r(s))})}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 o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&Fc(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new O(A.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new O(A.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new O(A.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new O(A.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Hn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Wt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new O(A.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Wt(a.status))throw new O(A.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=Hn.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Wt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Cf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Af(e,t){let r={...e};for(let n in t){let o=n,s=t[o];if(s===void 0)continue;let i=r[o];Cf(i)&&Cf(s)?r[o]={...i,...s}:r[o]=s}return r}var wy=Dl(Kd(),1),ky=Dl(by(),1);function GP(){let e=new wy.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,ky.default)(e),e}var gi=class{constructor(t){this._ajv=t??GP()}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 yi=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 o=t.messages[t.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(d=>d.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(d=>d.type==="tool_use");if(i){if(s.some(d=>d.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 d=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),l=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(d.size!==l.size||![...d].every(p=>l.has(p)))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},Kn,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.mode??"form";switch(o){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 s=o==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:s},on,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 xy(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 Sy(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 _i=class extends js{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Gn.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new gi,this.setRequestHandler(Hc,n=>this._oninitialize(n)),this.setNotificationHandler(Wc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(tu,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Gn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new yi(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Af(this._capabilities,t)}setRequestHandler(t,r){let o=Bt(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Ye(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let d=Vt(nn,c);if(!d.success){let f=d.error instanceof Error?d.error.message:String(d.error);throw new O(A.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:l}=d.data,p=await Promise.resolve(r(c,u));if(l.task){let f=Vt(Qr,p);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new O(A.InvalidParams,`Invalid task creation result: ${g}`)}return f.data}let h=Vt(Ps,p);if(!h.success){let f=h.error instanceof Error?h.error.message:String(h.error);throw new O(A.InvalidParams,`Invalid tools/call result: ${f}`)}return h.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){Sy(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&xy(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:Nm.includes(r)?r:qc,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"},ms)}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],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.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(a.filter(l=>l.type==="tool_use").map(l=>l.id)),d=new Set(o.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(u.size!==d.size||![...u].every(l=>d.has(l)))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},ru,r):this.request({method:"sampling/createMessage",params:t},Kn,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 o=t;return this.request({method:"elicitation/create",params:o},on,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},s=await this.request({method:"elicitation/create",params:o},on,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new O(A.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof O?i:new O(A.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}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},nu,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 zy=Symbol.for("mcp.completable");function ol(e){return!!e&&typeof e=="object"&&zy in e}function Py(e){return e[zy]?.complete}var $y;(function(e){e.Completable="McpCompletable"})($y||($y={}));var KP=/^[A-Za-z0-9._-]{1,128}$/;function XP(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"),!KP.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);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 YP(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 sl(e){let t=XP(e);return YP(e,t.warnings),t.isValid}var vi=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.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,o,r._meta,n)}};var bi=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 _i(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new vi(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(nr(zs)),this.server.assertCanSetRequestHandler(nr(nn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(zs,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=Xr(r.inputSchema);return o?uu(o,{strictUnions:!0,pipeStrategy:"input"}):QP})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Xr(r.outputSchema);o&&(n.outputSchema=uu(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(nn,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new O(A.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new O(A.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new O(A.InternalError,`Tool ${t.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new O(A.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,t.params.name),c}catch(n){if(n instanceof O&&n.code===A.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 s=Xr(t.inputSchema)??t.inputSchema,i=await ss(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=is(a);throw new O(A.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new O(A.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Xr(t.outputSchema),s=await ss(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=is(i);throw new O(A.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(t.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),s=t.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,d=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,d));let l=await n.taskStore.getTask(c);if(!l)throw new O(A.InternalError,`Task ${c} not found during polling`);u=l}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(nr(Ts)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ts,async t=>{switch(t.params.ref.type){case"ref/prompt":return Qm(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return ef(t),this.handleResourceCompletion(t,t.params.ref);default:throw new O(A.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new O(A.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new O(A.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return To;let s=Bt(n.argsSchema)?.[t.params.argument.name];if(!ol(s))return To;let i=Py(s);if(!i)return To;let a=await i(t.params.argument.value,t.params.context);return Ry(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return To;throw new O(A.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return To;let s=await o(t.params.argument.value,t.params.context);return Ry(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(nr(tn)),this.server.assertCanSetRequestHandler(nr(rn)),this.server.assertCanSetRequestHandler(nr(xs)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(tn,async(t,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(rn,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(xs,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new O(A.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new O(A.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(nr(Ss)),this.server.assertCanSetRequestHandler(nr($s)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ss,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?eT(r.argsSchema):void 0}))})),this.server.setRequestHandler($s,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new O(A.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new O(A.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=Xr(n.argsSchema),s=await ss(o,t.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=is(c);throw new O(A.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,n.title,r,n,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,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(t,r,n,o,s){let i={name:t,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(t,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==t&&(delete this._registeredResourceTemplates[t],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(t,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:zr(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=zr(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=i,o&&Object.values(o).some(c=>{let u=c instanceof Le?c._def?.innerType:c;return ol(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(t,r,n,o,s,i,a,c,u){sl(t);let d={title:r,description:n,inputSchema:Ty(o),outputSchema:Ty(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==t&&(typeof l.name=="string"&&sl(l.name),delete this._registeredTools[t],l.name&&(this._registeredTools[l.name]=d)),typeof l.title<"u"&&(d.title=l.title),typeof l.description<"u"&&(d.description=l.description),typeof l.paramsSchema<"u"&&(d.inputSchema=zr(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=zr(l.outputSchema)),typeof l.callback<"u"&&(d.handler=l.callback),typeof l.annotations<"u"&&(d.annotations=l.annotations),typeof l._meta<"u"&&(d._meta=l._meta),typeof l.enabled<"u"&&(d.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(il(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!il(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(t,o,s,i,a,c,{taskSupport:"forbidden"},u,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 o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(t,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(t,o,s,i,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 QP={type:"object",properties:{}};function Ey(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function Iy(e){return"_def"in e||"_zod"in e||Ey(e)}function il(e){return typeof e!="object"||e===null||Iy(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Ey)}function Ty(e){if(e){if(il(e))return zr(e);if(!Iy(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function eT(e){let t=Bt(e);return t?Object.entries(t).map(([r,n])=>{let o=mm(n),s=fm(n);return{name:r,description:o,required:!s}}):[]}function nr(e){let r=Bt(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=as(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Ry(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var To={completion:{values:[],hasMore:!1}};import jy from"node:process";var wi=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
|
|
42
|
+
`);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),tT(r)}clear(){this._buffer=void 0}};function tT(e){return Vm.parse(JSON.parse(e))}function Oy(e){return JSON.stringify(e)+`
|
|
43
|
+
`}var ki=class{constructor(t=jy.stdin,r=jy.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new wi,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=Oy(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{readFile as Y_}from"node:fs/promises";import{hostname as bR}from"node:os";import{randomBytes as MT}from"node:crypto";import{existsSync as ll,mkdirSync as NT,readFileSync as pl,renameSync as LT,rmSync as DT,writeFileSync as ZT}from"node:fs";import{homedir as UT}from"node:os";import{dirname as qT,join as JT}from"node:path";import{spawn as wT}from"node:child_process";import{randomBytes as kT}from"node:crypto";import{createServer as xT}from"node:http";import{appendFileSync as aT,openSync as $4}from"node:fs";import{homedir as Ly}from"node:os";import{dirname as cT,join as Dy,resolve as uT,sep as dT}from"node:path";import{mkdirSync as lT}from"node:fs";var $t={_generated:"GENERATED by scripts/naming_dual_emit_codegen.mjs from scripts/naming_canonical_key_map.json (N2.2 dual-emit, D46) - DO NOT EDIT; run: node scripts/naming_dual_emit_codegen.mjs --write",events:[["codex.agent_turn_narration_only_no_reply","harness.agent_turn_narration_only_no_reply"],["codex.cost_cap_402_seen","harness.cost_cap_402_seen"],["codex.edge_blocked_captured","harness.edge_blocked_captured"],["codex.empty_turn_auto_retry_suppressed_cost_cap","harness.empty_turn_auto_retry_suppressed_cost_cap"],["codex.empty_turn_loop_guard_tripped","harness.empty_turn_loop_guard_tripped"],["codex.error_without_http_status_captured","harness.error_without_http_status_captured"],["codex.mid_stream_stall_auto_resume_flagged","harness.mid_stream_stall_auto_resume_flagged"],["codex.mid_stream_stall_resume_suppressed_rate_limit","harness.mid_stream_stall_resume_suppressed_rate_limit"],["codex.mid_stream_stall_second_stall_after_resume","harness.mid_stream_stall_second_stall_after_resume"],["codex.pre_first_byte_stall_auto_retry_flagged","harness.pre_first_byte_stall_auto_retry_flagged"],["codex.pre_first_byte_stall_retry_suppressed_cost_cap","harness.pre_first_byte_stall_retry_suppressed_cost_cap"],["codex.provider_outage_flagged_captured","harness.provider_outage_flagged_captured"],["codex.reasoning_loop_breaker_tripped","harness.reasoning_loop_breaker_tripped"],["codex.tool_fatal_captured","harness.tool_fatal_captured"],["codex.turn_completed","job.turn_completed"],["codex.turn_completed_with_protocol_failure","job.turn_completed_with_protocol_failure"],["codex.turn_completed_with_unsupported_tool_call_ignored","job.turn_completed_with_unsupported_tool_call_ignored"],["codex.turn_completed_without_assistant_output","job.turn_completed_without_assistant_output"],["codex.turn_forward_failed","job.turn_forward_failed"],["codex.upstream_error_captured","harness.upstream_error_captured"],["codex.upstream_rejection_captured","harness.upstream_rejection_captured"],["codex.upstream_turn_error_captured","harness.upstream_turn_error_captured"],["kandan.chat_event","linzumi.chat_event"],["kandan.chat_event_abandoned","linzumi.chat_event_abandoned"],["kandan.chat_event_failed","linzumi.chat_event_failed"],["kandan.chat_event_failure_cleared","linzumi.chat_event_failure_cleared"],["kandan.claude_code_interrupt_state_push_failed","linzumi.claude_code_interrupt_state_push_failed"],["kandan.claude_code_stop_state_push_failed","linzumi.claude_code_stop_state_push_failed"],["kandan.claude_code_typing_heartbeat_failed","linzumi.claude_code_typing_heartbeat_failed"],["kandan.claude_code_typing_start_wait_timeout","linzumi.claude_code_typing_start_wait_timeout"],["kandan.claude_code_typing_stop_failed","linzumi.claude_code_typing_stop_failed"],["kandan.claude_code_user_input_abort_publish_failed","linzumi.claude_code_user_input_abort_publish_failed"],["kandan.claude_code_user_question_completed_publish_failed","linzumi.claude_code_user_question_completed_publish_failed"],["kandan.codex_command_output_forwarded","linzumi.codex_command_output_forwarded"],["kandan.codex_delta_forwarded","linzumi.codex_delta_forwarded"],["kandan.codex_file_change_forwarded","linzumi.codex_file_change_forwarded"],["kandan.codex_notification_push_failed","linzumi.codex_notification_push_failed"],["kandan.codex_output_forwarded","linzumi.codex_output_forwarded"],["kandan.codex_reasoning_delta_forwarded","linzumi.codex_reasoning_delta_forwarded"],["kandan.codex_web_search_progress_forwarded","linzumi.codex_web_search_progress_forwarded"],["kandan.connection_force_reconnect","linzumi.connection_force_reconnect"],["kandan.connection_force_reconnect_dispatched","linzumi.connection_force_reconnect_dispatched"],["kandan.connection_hard_reset","linzumi.connection_hard_reset"],["kandan.connection_hard_reset_exhausted","linzumi.connection_hard_reset_exhausted"],["kandan.connection_recovered","linzumi.connection_recovered"],["kandan.connection_stale","linzumi.connection_stale"],["kandan.connection_unrecoverable","linzumi.connection_unrecoverable"],["kandan.control","linzumi.control"],["kandan.control_ack_withheld_on_failure","linzumi.control_ack_withheld_on_failure"],["kandan.control_epoch_changed","linzumi.control_epoch_changed"],["kandan.control_handler_threw","linzumi.control_handler_threw"],["kandan.control_ignored","linzumi.control_ignored"],["kandan.control_response_push_failed","linzumi.control_response_push_failed"],["kandan.failed_seq_overflow","linzumi.failed_seq_overflow"],["kandan.forward_port_revoked_push_failed","linzumi.forward_port_revoked_push_failed"],["kandan.forward_response","linzumi.forward_response"],["kandan.forward_response_push_failed","linzumi.forward_response_push_failed"],["kandan.forward_tunnel_error","linzumi.forward_tunnel_error"],["kandan.forward_tunnel_open_failed","linzumi.forward_tunnel_open_failed"],["kandan.heartbeat_push_failed","linzumi.heartbeat_push_failed"],["kandan.local_editor_initial_status_failed","linzumi.local_editor_initial_status_failed"],["kandan.local_editor_status_push_failed","linzumi.local_editor_status_push_failed"],["kandan.message_duplicate_ignored","linzumi.message_duplicate_ignored"],["kandan.message_ignored","linzumi.message_ignored"],["kandan.message_queued","linzumi.message_queued"],["kandan.message_spawn_on_miss","linzumi.message_spawn_on_miss"],["kandan.message_spawn_on_miss_failed","linzumi.message_spawn_on_miss_failed"],["kandan.message_state_refresh_failed","linzumi.message_state_refresh_failed"],["kandan.optional_push_failed","linzumi.optional_push_failed"],["kandan.post_stop_queue_drain_failed","linzumi.post_stop_queue_drain_failed"],["kandan.queue_drain_blocked","linzumi.queue_drain_blocked"],["kandan.queue_drain_dead_worker_fail_publish_failed","linzumi.queue_drain_dead_worker_fail_publish_failed"],["kandan.queue_drain_dead_worker_rebuild","linzumi.queue_drain_dead_worker_rebuild"],["kandan.queue_drain_dead_worker_rebuild_exhausted","linzumi.queue_drain_dead_worker_rebuild_exhausted"],["kandan.queue_drain_dead_worker_rebuild_failed","linzumi.queue_drain_dead_worker_rebuild_failed"],["kandan.reconnect_handling_failed","linzumi.reconnect_handling_failed"],["kandan.reconnect_thread_context_fetch_failed","linzumi.reconnect_thread_context_fetch_failed"],["kandan.reconnect_thread_cwd_failed_state_push_failed","linzumi.reconnect_thread_cwd_failed_state_push_failed"],["kandan.reconnect_thread_failed","linzumi.reconnect_thread_failed"],["kandan.reconnect_thread_processing_state_push_failed","linzumi.reconnect_thread_processing_state_push_failed"],["kandan.reconnect_thread_queue_closed_state_push_failed","linzumi.reconnect_thread_queue_closed_state_push_failed"],["kandan.reconnect_thread_queue_failed_state_push_failed","linzumi.reconnect_thread_queue_failed_state_push_failed"],["kandan.reconnect_thread_queue_state_push_failed","linzumi.reconnect_thread_queue_state_push_failed"],["kandan.reconnect_thread_rehydrate_forced","linzumi.reconnect_thread_rehydrate_forced"],["kandan.reconnect_thread_rehydrated","linzumi.reconnect_thread_rehydrated"],["kandan.reconnect_thread_rehydrated_state_push_failed","linzumi.reconnect_thread_rehydrated_state_push_failed"],["kandan.reconnect_thread_rehydration_failed","linzumi.reconnect_thread_rehydration_failed"],["kandan.reconnect_thread_rehydration_ir_emitted","linzumi.reconnect_thread_rehydration_ir_emitted"],["kandan.reconnect_thread_rehydration_items_failed","linzumi.reconnect_thread_rehydration_items_failed"],["kandan.reconnect_thread_resume_failed","linzumi.reconnect_thread_resume_failed"],["kandan.reconnect_thread_seq_already_applied","linzumi.reconnect_thread_seq_already_applied"],["kandan.reconnect_thread_transcript_fetch_failed","linzumi.reconnect_thread_transcript_fetch_failed"],["kandan.reconnect_thread_unarchive_failed","linzumi.reconnect_thread_unarchive_failed"],["kandan.reconnect_thread_unarchive_resumed","linzumi.reconnect_thread_unarchive_resumed"],["kandan.reconnect_thread_unarchive_started","linzumi.reconnect_thread_unarchive_started"],["kandan.reconnect_thread_unavailable_state_push_failed","linzumi.reconnect_thread_unavailable_state_push_failed"],["kandan.reconnected","linzumi.reconnected"],["kandan.roster_seeded","linzumi.roster_seeded"],["kandan.session_app_server_lost_push_failed","linzumi.session_app_server_lost_push_failed"],["kandan.session_settings_publish_failed","linzumi.session_settings_publish_failed"],["kandan.start_instance_claude_code_attachment_failed_state_push_failed","linzumi.start_instance_claude_code_attachment_failed_state_push_failed"],["kandan.start_instance_codex_app_server_unavailable","linzumi.start_instance_codex_app_server_unavailable"],["kandan.start_instance_cwd_failed_state_push_failed","linzumi.start_instance_cwd_failed_state_push_failed"],["kandan.start_instance_cwd_rejected","linzumi.start_instance_cwd_rejected"],["kandan.start_instance_failed","linzumi.start_instance_failed"],["kandan.start_instance_processing_state_push_failed","linzumi.start_instance_processing_state_push_failed"],["kandan.start_instance_skipped_known_session","linzumi.start_instance_skipped_known_session"],["kandan.start_instance_stale_skipped","linzumi.start_instance_stale_skipped"],["kandan.start_instance_unavailable_state_push_failed","linzumi.start_instance_unavailable_state_push_failed"],["kandan.start_instance_wafer_state_push_failed","linzumi.start_instance_wafer_state_push_failed"],["kandan.start_turn_replay_skipped","linzumi.start_turn_replay_skipped"],["kandan.steer_duplicate_ignored","linzumi.steer_duplicate_ignored"],["kandan.steer_parked_as_own_turn","linzumi.steer_parked_as_own_turn"],["kandan.thread_bind_from_historical_reply_failed","linzumi.thread_bind_from_historical_reply_failed"],["kandan.thread_bound_from_historical_reply","linzumi.thread_bound_from_historical_reply"],["kandan.thread_sessions_reannounce_failed","linzumi.thread_sessions_reannounce_failed"],["kandan.thread_sessions_reannounced","linzumi.thread_sessions_reannounced"],["kandan.tui_input_mirrored","linzumi.tui_input_mirrored"],["kandan.typing_heartbeat_failed","linzumi.typing_heartbeat_failed"],["kandan.typing_stop_after_completion_failed","linzumi.typing_stop_after_completion_failed"]],keys:[["codexThreadId","harness_session_id"],["codex_thread_id","harness_session_id"],["kandanThreadId","thread_id"],["kandan_preview_ticket","linzumi_preview_ticket"],["kandan_thread_id","thread_id"],["linzumiThreadId","thread_id"],["linzumi_thread_id","thread_id"],["local_codex_runner","commander"],["runnerId","commander_id"],["runner_config","commander_config"],["runner_id","commander_id"]],keyPrimaryLegacy:[["commander","local_codex_runner"],["commander_config","runner_config"],["commander_id","runner_id"],["harness_session_id","codex_thread_id"],["linzumi_preview_ticket","kandan_preview_ticket"],["thread_id","kandan_thread_id"]],values:[["engine_boot_reconnect","harness_boot_reconnect"],["engine_for_runner_event_type","harness_for_commander_event_type"],["engine_rejected_steer","harness_rejected_steer"],["engine_unavailable","harness_unavailable"],["join_engine","join_harness"],["kandan-local-codex-runner","linzumi-commander"],["local_codex_runner","commander"],["original_engine","original_harness"],["resume_engine","resume_harness"]],topic:{legacyPrefix:"local_codex_runner:",canonicalPrefix:"commander:"},originator:{legacy:"kandan-local-codex-runner",canonical:"linzumi-commander"}};var nT=new Map($t.events),oT=new Map($t.events.map(([e,t])=>[t,e])),Ay=new Map($t.keys),My=new Map($t.keyPrimaryLegacy),sT=new Map($t.values),iT=new Map($t.values.map(([e,t])=>[t,e])),b4={eventCanonicalByLegacy:nT,eventLegacyByCanonical:oT,keyCanonicalByLegacy:Ay,keyPrimaryLegacyByCanonical:My,valueCanonicalByLegacy:sT,valueLegacyByCanonical:iT,originator:$t.originator,topic:$t.topic};function Ny(e){let t=new Set(e);for(let r of e){let n=Ay.get(r);n!==void 0&&t.add(n);let o=My.get(r);o!==void 0&&t.add(o)}return t}var Cy=new Map;for(let[e,t]of $t.keys){let r=Cy.get(t)??[];r.push(e),Cy.set(t,r)}var Nr="<SENSITIVE_DATA>",Zy=Ny(new Set(["access_token","authorization","code","cookie","kandan_preview_ticket","refresh_token","token"])),pT=new Set(["--access-token","--api-key","--authorization","--cookie","--oauth-code","--password","--refresh-token","--secret","--token"]);function mT(e){if(process.env.VITEST===void 0)return;let t=Dy(Ly(),".linzumi"),r=uT(e);if(r===t||r.startsWith(`${t}${dT}`))throw new Error(`test-mode log isolation violated: refusing to open ${e} inside the real ~/.linzumi (point the logger at a temp path; the harness defaults LINZUMI_RUNNER_LOG_FILE / LINZUMI_CLI_AUDIT_LOG for exactly this - see plans/2026-07-10-cli-test-hygiene-spec.md item 2)`)}function al(e,t,r={}){let n=r.logFile??fT();mT(n);try{lT(cT(n),{recursive:!0}),aT(n,`${JSON.stringify({ts:new Date().toISOString(),event:e,...r.sessionId===void 0?{}:{sessionId:r.sessionId},...hT(t)})}
|
|
44
|
+
`,"utf8")}catch{return}}function fT(){let e=process.env.LINZUMI_CLI_AUDIT_LOG?.trim();return e===void 0||e===""?Dy(Ly(),".linzumi","logs","command-events.jsonl"):e}function hT(e){return Uy(e)}function cl(e,t){return _T(t)?Nr:typeof e=="string"?qy(e):Array.isArray(e)?t==="args"?gT(e):e.map(r=>cl(r,void 0)):e!==null&&typeof e=="object"?Uy(e):e}function Uy(e){let t=typeof e.name=="string"?e.name.toLowerCase():void 0,r=t==="authorization"||t==="cookie"||t==="set-cookie";return Object.fromEntries(Object.entries(e).filter(([n])=>n!=="runner_console").map(([n,o])=>[n,r&&n==="value"?Nr:cl(o,n)]))}function gT(e){let t=!1;return e.map(r=>{if(typeof r!="string")return t=!1,cl(r,void 0);if(t)return t=!1,Nr;let[n,o]=yT(r);return pT.has(n)?o===void 0?(t=!0,r):`${n}=${Nr}`:qy(r)})}function yT(e){let t=e.indexOf("=");return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function _T(e){return e===void 0?!1:/^(authorization|cookie|set-cookie|password)$/i.test(e)||/(^|[_-])(access[_-]?token|api[_-]?key|auth[_-]?token|oauth[_-]?code|refresh[_-]?token|secret|token)$/i.test(e)}function qy(e){return vT(e).replace(/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,Nr)}function vT(e){let t;try{t=new URL(e)}catch{return bT(e)}for(let r of[...t.searchParams.keys()])Zy.has(r.toLowerCase())&&t.searchParams.set(r,Nr);return t.toString()}function bT(e){let t=e.indexOf("?"),r=e.indexOf("#");if(t===-1||r!==-1&&r<t)return e;let n=e.slice(0,t),o=r===-1?e.slice(t+1):e.slice(t+1,r),s=r===-1?"":e.slice(r),i=new URLSearchParams(o),a=!1;for(let c of[...i.keys()])Zy.has(c.toLowerCase())&&(i.set(c,Nr),a=!0);switch(a){case!0:return`${n}?${i.toString()}${s}`;case!1:return e}}var ST=300*1e3,$T=1e4;function Jy(e,t=process.env){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;let r=t.LINZUMI_OAUTH_CALLBACK_TIMEOUT_MS?.trim();if(r!==void 0&&r!==""){let n=Number.parseInt(r,10);if(Number.isFinite(n)&&n>0)return n}return ST}async function Fy(e){let t=Ve(e.kandanUrl),r=kT(18).toString("base64url"),n=await ET({host:zT(e.kandanUrl,e.callbackHost),exchange:async s=>{if(s.state!==r)throw new Error("local runner OAuth state mismatch");return await RT({httpBaseUrl:t,code:s.code,redirectUri:s.redirectUri})}}),o=TT({httpBaseUrl:t,redirectUri:n.redirectUri,state:r,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,onboarding:e.onboarding,purpose:e.purpose});process.stderr.write(`Authorize the local Codex runner:
|
|
45
|
+
${o}
|
|
46
|
+
`);try{return await(e.openAuthorizationUrl??AT)(o),await n.waitForToken(Jy(e.waitForTokenTimeoutMs))}finally{n.close()}}async function Vy(e){return await Eo(e)==="usable"}async function Eo(e){let t=new URL("/api/v2/local-codex-runner/oauth/validate",Ve(e.kandanUrl));e.workspaceSlug!==void 0&&t.searchParams.set("workspace",e.workspaceSlug),e.channelSlug!==void 0&&t.searchParams.set("channel",e.channelSlug);for(let n of e.requiredScopes??[])t.searchParams.append("required_scope",n);let r=await fetch(t,{method:"GET",headers:{authorization:`Bearer ${e.accessToken}`}});switch(r.status){case 200:{let n=await r.json();return typeof n=="object"&&n!==null&&"ok"in n&&n.ok===!0?"usable":"rejected"}case 401:case 403:return"rejected";case 404:return"not_found";default:throw new Error(`local runner auth validation failed with HTTP ${r.status}`)}}function Ve(e){let t=new URL(e);switch(t.protocol){case"ws:":t.protocol="http:";break;case"wss:":t.protocol="https:";break;case"http:":case"https:":break;default:throw new Error("--api-url must be ws://, wss://, http://, or https://")}return t.pathname="",t.search="",t.hash="",t.toString().replace(/\/$/,"")}function zT(e,t){let r=t?.trim();if(r!==void 0&&r!=="")return r;let n=new URL(e).hostname.trim();return PT(n)&&n!=="localhost"?n:"127.0.0.1"}function PT(e){let t=e.split(".").map(o=>Number.parseInt(o,10));if(t.length!==4||t.some(o=>!Number.isInteger(o)||o<0||o>255))return e==="localhost";let[r,n]=t;return r===void 0||n===void 0?!1:r===10||r===127||r===172&&n>=16&&n<=31||r===192&&n===168||r===169&&n===254||r===100&&n>=64&&n<=127}function TT(e){let t=new URL("/api/v2/local-codex-runner/oauth/authorize",e.httpBaseUrl);return t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("state",e.state),e.workspaceSlug!==void 0&&t.searchParams.set("workspace",e.workspaceSlug),e.channelSlug!==void 0&&t.searchParams.set("channel",e.channelSlug),e.onboarding!==void 0&&t.searchParams.set("onboarding",e.onboarding),e.purpose!==void 0&&t.searchParams.set("purpose",e.purpose),t.toString()}async function RT(e){let t=await fetch(new URL("/api/v2/local-codex-runner/oauth/token",e.httpBaseUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:e.code,redirect_uri:e.redirectUri})}),r=await t.json();if(!t.ok||typeof r!="object"||r===null){let s=typeof r=="object"&&r!==null&&"error"in r&&typeof r.error=="string"?r.error:void 0;throw s==="admin_role_required"?new Error("This token requires a Linzumi admin account. Approve the request while signed in as an admin."):new Error(s!==void 0?`local runner OAuth token exchange failed: ${s}`:"local runner OAuth token exchange failed")}let n="access_token"in r?r.access_token:void 0;if(typeof n!="string"||n.trim()==="")throw new Error("local runner OAuth token response did not include access_token");let o="expires_in"in r?r.expires_in:void 0;return{accessToken:n,expiresInSeconds:typeof o=="number"?o:void 0,workspaceSlug:xi(r,"workspace"),channelSlug:xi(r,"channel")}}async function By(e){let t=await fetch(new URL("/api/v2/local-codex-runner/device/start",e.httpBaseUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({workspace:e.workspaceSlug,channel:e.channelSlug,onboarding:e.onboarding,runner_id:e.identity?.runnerId,machine_fingerprint:e.identity?.machineFingerprint,hostname:e.identity?.hostname})}),r=await t.json();if(!t.ok||typeof r!="object"||r===null){let a=dl(r);throw new Error(a===void 0?`local runner device authorization failed to start (HTTP ${t.status})`:`local runner device authorization failed to start (server said: ${a})`)}let n="device_code"in r?r.device_code:void 0,o="user_code"in r?r.user_code:void 0,s="verification_uri"in r?r.verification_uri:void 0,i="expires_in"in r?r.expires_in:void 0;if(typeof n!="string"||n.trim()===""||typeof o!="string"||o.trim()===""||typeof s!="string"||s.trim()==="")throw new Error("local runner device authorization response was incomplete");return{deviceCode:n,userCode:o,verificationUri:s,expiresInSeconds:typeof i=="number"?i:void 0}}async function Hy(e){let t=e.now??Date.now,r=typeof e.expiresInSeconds=="number"&&e.expiresInSeconds>=0?e.expiresInSeconds:600,n=t()+r*1e3;for(;t()<n;){let o=Math.max(0,Math.min(3e4,n-t())),s=new AbortController,i=setTimeout(()=>s.abort(),o+$T),a,c;try{a=await fetch(new URL("/api/v2/local-codex-runner/device/token",e.httpBaseUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:e.deviceCode,wait_ms:o}),signal:s.signal})}catch(l){if(clearTimeout(i),s.signal.aborted)continue;return{kind:"transient",reason:l instanceof Error?l.message:String(l)}}try{c=await a.json()}catch(l){if(s.signal.aborted)continue;return{kind:"transient",reason:`non-JSON device/token response (${l instanceof Error?l.message:String(l)})`,httpStatus:a.status}}finally{clearTimeout(i)}if(a.status===202&&dl(c)==="authorization_pending")continue;if(!a.ok||typeof c!="object"||c===null){let l=dl(c);switch(l){case"access_denied":return{kind:"denied"};case"device_session_expired":return{kind:"code_expired"};case"device_session_consumed":return{kind:"consumed"};default:return a.status>=500||a.status===429?{kind:"transient",reason:l??`HTTP ${a.status}`,httpStatus:a.status}:{kind:"rejected",reason:l,httpStatus:a.status}}}let u="access_token"in c?c.access_token:void 0;if(typeof u!="string"||u.trim()==="")return{kind:"rejected",reason:"device token response did not include access_token",httpStatus:a.status};let d="expires_in"in c?c.expires_in:void 0;return{kind:"token",token:{accessToken:u,expiresInSeconds:typeof d=="number"?d:void 0,workspaceSlug:xi(c,"workspace"),channelSlug:xi(c,"channel")}}}return{kind:"code_expired"}}function dl(e){if(!(typeof e!="object"||e===null||!("error"in e)))return typeof e.error=="string"?e.error:void 0}function Wy(e,t){switch(e){case"access_denied":return"local runner device authorization was denied";case"device_session_expired":return"local runner device authorization expired";case"device_session_consumed":return"local runner device authorization was already used";case"invalid_device_code":return"local runner device authorization code was rejected";case"device_session_not_pending":return"local runner device authorization was already decided (approved or denied) on the server";case"invalid_user_code":return"local runner device authorization code was not recognized by the server";case"approving_user_not_found":return"local runner device authorization failed: the approving Linzumi account could not be found";case"rate_limited":return"local runner device authorization was rate limited by the server; wait a minute and retry";case void 0:return t===void 0?"local runner device authorization failed (no reason returned by the server)":`local runner device authorization failed (HTTP ${t}, no reason returned by the server)`;default:return`local runner device authorization failed (server said: ${e})`}}function xi(e,t){let r=e[t];return typeof r=="string"&&r.trim()!==""?r:void 0}function ET(e){return new Promise((t,r)=>{let n,o,s=!1,i=new Promise((d,l)=>{n=d,o=l});i.catch(()=>{});let a=d=>s?!1:(s=!0,d(),!0),c=`http://${e.host}/callback`,u=xT((d,l)=>{(async()=>{try{let p=new URL(d.url??"/",`http://${e.host}`),h=p.searchParams.get("code"),f=p.searchParams.get("state"),g=p.searchParams.get("error");if(g!==null&&g.trim()!==""){a(()=>o?.(new Error(`local runner OAuth failed: ${g}`))),Ro(l,{title:"Not authorized",body:"You denied the request. Close this tab and rerun the bootstrap command when you're ready.",status:403});return}if(h===null||f===null||h.trim()===""||f.trim()===""){Ro(l,{title:"Authorization callback was incomplete",body:"We didn't receive the authorization code. Return to your terminal and try again.",status:400});return}let y;try{y=await e.exchange({code:h,state:f,redirectUri:c})}catch(w){a(()=>o?.(w)),Ro(l,{title:"Authorization could not be completed",body:"We received the authorization but could not finish setup. Return to your terminal for details and rerun the bootstrap command.",status:400});return}let b=a(()=>n?.(y));Ro(l,{title:b?"Computer authorized":"Already authorized",body:"This computer has been authorized for agentic use in Linzumi. Feel free to close this tab and let the terminal finish setup.",status:200})}catch(p){a(()=>o?.(p)),Ro(l,{title:"Authorization callback failed",body:"Return to your terminal and rerun the bootstrap command.",status:500})}})()});u.once("error",r),u.listen(0,e.host,()=>{let d=u.address();if(!IT(d)){r(new Error("local runner OAuth callback server did not bind to a TCP port"));return}c=`http://${e.host}:${d.port}/callback`,t({redirectUri:c,waitForToken:l=>{let p=Jy(l),h=setTimeout(()=>{a(()=>o?.(new Error("Authorization timed out before the browser callback completed. Rerun the connect command and finish authorizing in the browser."))),u.close()},p);return h.unref?.(),i.finally(()=>{clearTimeout(h)}).catch(()=>{}),i},close:()=>{u.close()}})})})}function IT(e){return typeof e=="object"&&e!==null&&typeof e.port=="number"}function Ro(e,t){e.writeHead(t.status,{"content-type":"text/html; charset=utf-8"}),e.end(jT(t))}var OT='<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path fill="currentColor" d="M206.7,82.37l2.55-6.45,2.01-3.63c.67-1.21,1.07-1.88,2.55-3.63,1.34-1.61,3.36-4.43,5.64-6.58,2.42-2.24,5.06-4.3,7.93-6.18,3.92-2.53,8.17-4.52,12.63-5.91,1.79-.63,4.03-1.16,6.72-1.61,6.1-.88,12.29-.92,18.4-.13,2.69.45,5.06,1.03,7.12,1.75,2.15.67,3.49,1.07,5.64,2.15,4.55,2.16,8.87,4.77,12.9,7.79,1.61,1.34,2.42,2.15,4.16,4.16l5.91,7.66c1.34,2.01,1.34,2.28,2.15,4.03l2.55,6.58c.67,1.34-.13,1.34,1.07.94,1.21-.27,4.3-2.01,6.45-2.82,4.7-1.83,9.62-3,14.64-3.49,2.42-.27,3.76-.54,7.12-.27s9.27,1.21,12.76,2.15c3.63.94,6.58,2.55,8.73,3.49,2.15,1.07,2.55,1.48,4.16,2.55,3.49,2.51,6.77,5.29,9.81,8.33,1.52,1.7,3.04,3.58,4.57,5.64,2.74,4.49,4.86,9.32,6.31,14.37.67,2.28,1.07,3.49,1.34,6.72.27,3.22,0,10.48.4,12.76.27,2.28.27.67,1.61.94,1.48.27,4.3,0,6.72.4,2.42.27,4.97.85,7.66,1.75,6.76,2.32,13.01,5.92,18.4,10.61,2.28,1.75,2.96,2.69,4.3,4.3,3.51,3.93,6.32,8.43,8.33,13.3,1.07,2.15,1.21,2.28,1.88,5.1.54,2.96,1.61,8.19,1.61,12.36s-.81,9.67-1.34,12.76c-.67,3.22-1.07,4.03-2.15,6.18-2.16,4.54-4.81,8.82-7.93,12.76-1.25,1.61-2.6,3-4.03,4.16-1.48,1.34-2.69,2.42-4.7,3.76-3.79,2.34-7.74,4.4-11.82,6.18l-6.58,2.15c-2.06.45-4.12.72-6.18.81l-7.25.13c-2.28,0-2.82.27-6.58-.4-3.76-.81-11.69-2.82-15.99-4.3-4.16-1.34-6.31-2.69-9.67-4.43-3.49-1.75-10.48-6.18-12.9-7.39-8.26-4.54-16.78-8.58-25.52-12.09-4.3-1.75-9.27-3.22-11.82-4.03-2.55-.81-5.24-1.61-7.66-2.15-8.39-2.25-16.99-3.6-25.66-4.03-3.9-.27-4.84-.27-8.19-.13-3.67-.09-7.79.04-12.36.4-7.9.79-15.75,2.04-23.51,3.76-8.37,2.26-16.62,4.95-24.72,8.06-3.22,1.34-2.82.81-9.13,4.16-6.31,3.36-22.03,12.22-28.75,15.58-6.72,3.36-8.73,3.49-11.82,4.43-3.09,1.07-4.3,1.21-6.58,1.61-7.3,1.09-14.71,1.18-22.03.27-2.55-.54-5.78-1.61-7.79-2.28-2.01-.54-2.15-.67-4.03-1.75-2.02-1.07-5.64-3.22-7.79-4.7-3.24-2.15-6.14-4.77-8.6-7.79-1.34-1.52-2.69-3.36-4.03-5.51-1.52-2.51-2.96-5.24-4.3-8.19-2.03-5.46-3.03-11.24-2.96-17.06,0-2.96.13-6.72.67-9.67.54-2.87,1.34-5.6,2.42-8.19,4.24-10.52,12.04-19.22,22.03-24.58,5.19-2.98,10.88-4.98,16.79-5.91,2.55-.4,5.37-.13,6.72-.4,1.34-.27,1.34,1.34,1.61-.94.4-2.28,0-9.4.4-12.76.27-3.36.81-4.97,1.48-7.25,1.87-6.19,4.88-11.97,8.87-17.06,3.47-3.98,7.39-7.54,11.69-10.61,4.43-2.61,9.11-4.77,13.97-6.45,2.55-.67,6.99-1.34,9.13-1.75,2.15-.27,1.88-.13,3.63-.13,1.79-.09,4.03,0,6.72.27,2.69.18,5.73.72,9.13,1.61,3.49,1.07,9.27,4.03,11.28,4.7s.4.27,1.07-.94ZM512.27,255.7c0,141.39-114.62,256-256,256S.27,397.09.27,255.7,114.89-.3,256.27-.3s256,114.62,256,256ZM449.33,352.66c14.67-29.16,22.94-62.09,22.94-96.95,0-119.29-96.71-216-216-216S40.27,136.41,40.27,255.7c0,41.89,11.94,80.98,32.57,114.09,1.7,1.79,2.94.65,3.05-.57.27-1.61,2.75-20.85,4.43-27.27,1.87-7.6,4.52-14.98,7.93-22.03,1.75-3.49,3.76-7.93,6.18-11.82,8.77-13.95,19.75-26.38,32.51-36.81,7.24-5.32,14.87-10.08,22.84-14.24,9.74-4.78,20.09-8.22,30.76-10.21,4.03-.99,7.61-1.66,10.75-2.02,3.36-.54,5.78-.54,9.27-.94,3.49-.54,9.32-1.16,11.82-2.01,6.65-2.27,5.64-6.72,3.09-7.52-2.55-.81-9.67-1.88-13.84-2.96-4.16-1.21-8.73-2.82-11.28-3.76-2.55-.94-2.28-.94-3.9-2.02l-5.91-4.03c-.94-.94-1.34-.94.54-2.02l10.21-5.51c2.01-1.07,1.75-.67,3.09-.13,1.34.67,4.3,2.42,6.72,3.36,7.2,2.69,14.96,3.52,22.57,2.42,1.34-.27,1.34-.54,1.61-1.21.27-.67.81-.94-.13-2.69-.94-1.88-4.43-6.58-5.64-8.46l-1.21-2.28c-.27-.45-1.07-1.07,1.21-1.75,2.42-.54,10.48-2.58,12.9-2.82.86-.09.67,0,1.75,1.07,1.07,1.07,3.09,3.63,4.84,5.24,1.88,1.61,4.43,3.22,6.18,4.3,2.8,1.71,5.99,2.68,9.27,2.82,1.88,0,4.97-.13,7.12-.67,2.15-.4,3.63-.94,5.64-2.02,2.01-1.07,4.7-2.69,6.72-4.43,2.01-1.75,3.49-5.1,5.64-6.04,2.15-.81,4.97.54,7.12.94,2.28.4,4.97,1.21,6.18,1.61,1.21.4,2.01.4.67,2.28l-8.06,10.34c-1.34,1.88.13,5.51,1.21,5.64l5.64.27c2.28-.13,4.43.13,7.66-.67,3.36-.81,9.27-2.96,11.82-3.9,2.69-.94,3.22-1.34,4.16-2.01.81-.54,1.39-1.03,1.75-1.48.45-.27.67-1.07,2.82,0s9.4,4.97,11.28,6.18c2.01,1.21,1.07.94,0,1.75l-5.51,3.9c-1.48.94-1.07.94-3.22,1.88-2.15,1.07-6.58,2.96-9.67,4.03s-4.03,1.75-8.73,2.69c-4.7.81-14.51,1.75-19.48,2.55-4.97.81-7.93,1.34-10.34,2.01-2.28.67-2.15.94-3.49,1.88-1.48,1.07-2.69,1.61-4.97,3.9-2.28,2.28-5.91,6.85-8.73,9.81-2.82,2.96-6.45,6.04-8.33,7.79-2.02,1.61-1.61,1.34-3.36,2.42l-6.99,4.03-4.03,2.02-6.72,2.15c-2.42.67-3.9,1.21-7.66,2.01l-14.91,2.82c-3.63.81-4.3,1.07-7.12,2.01-2.96,1.07-6.22,2.46-9.81,4.16-3.22,1.43-6.81,3.45-10.75,6.04-13.6,9.14-24.61,21.63-31.97,36.27-2.01,3.76-2.96,6.58-3.9,9.27-1.07,2.69-1.61,4.03-2.28,6.58-.67,2.69-1.48,5.24-2.15,9.27-.54,4.16-1.48,11.15-1.75,15.45-.27,4.16-.27,6.04,0,10.21l1.88,14.91c.67,3.76,1.48,5.91,2.15,8.19l1.88,5.64c.99,2.6,2.42,5.78,4.3,9.54,2.15,3.76,5.37,9.13,8.06,13.03,10.08,14.51,23.81,26.36,40.17,33.05,22.55,9.22,43.32,10.46,61.89,10.46,3.25,0,6.49-.09,9.71-.23,3.07-.42,2.74-6.09,10.48-9.42,5.26-2.26,13.7-2.42,14.91-2.55,1.07-.13-5.24-4.57-7.79-6.45-2.55-1.88-4.97-4.3-6.72-5.91-1.75-1.75-2.42-2.28-3.9-4.16-1.61-1.88-3.9-5.51-5.24-7.12-1.34-1.61-1.48-2.28-2.55-2.55-.98-.27-2.37-.09-4.16.54-1.88.4-5.37,1.21-7.12,1.88-1.75.67-2.02.81-3.09,2.01-1.07,1.07-2.69,3.76-3.63,4.7-.81.94-.67.67-1.48.94-.81.27-2.42.67-3.63.54-1.34-.18-2.55-.58-3.63-1.21-.81-.81-1.48-2.42-1.88-3.22-.4-.94-.54-1.21-.54-2.15l.4-3.49c.18-1.52.72-3.27,1.61-5.24.94-1.75,1.88-3.49,4.16-5.64,2.15-2.02,7.52-5.51,9.13-6.85,1.61-1.34,1.21-2.15.54-3.63-2.69-5.16-6.33-9.77-10.75-13.57-2.42-1.88-5.51-3.22-7.79-4.3-2.15-1.21-2.01-1.21-5.78-2.42-3.76-1.07-13.16-3.63-16.79-4.84-3.63-1.07-2.82-.94-5.1-2.01l-8.19-4.3c-1.75-.94-1.34-.54-2.69-1.61l-5.51-4.57c-2.18-1.93-3.77-4.45-4.57-7.25-.45-1.52-.45-2.87,0-4.03.4-1.34,0-1.21,2.01-3.63,2.15-2.42,7.25-7.93,10.21-10.75,3.09-2.82,4.97-4.03,7.79-6.04,5.43-3.82,11.09-7.32,16.93-10.48,2.42-1.21,5.37-2.02,7.12-2.69,1.61-.81,2.64-1.43,3.09-1.88.54-.4.67.54.4-.94-.4-1.48-1.88-4.97-2.28-7.66-.4-2.82-.4-6.18,0-8.73.36-2.42,1.03-4.66,2.01-6.72,1.16-2.24,2.46-4.3,3.9-6.18,1.34-1.7,2.91-3.04,4.7-4.03,1.75-1.07,4.3-2.01,6.18-2.42,1.61-.45,3.13-.58,4.57-.4l4.57.27c1.34.18,2.55.49,3.63.94,1.07.54,2.55,1.48,3.09,2.01.4.67.67.13-.27,1.61-1.07,1.48-4.16,4.57-5.78,7.12-1.61,2.69-2.96,5.6-4.03,8.73-.94,3.22-1.88,8.73-2.01,10.75-.27,2.15,4.7,1.75,5.1.54.54-1.07.27-2.55,1.07-5.1.81-2.42,2.42-7.25,3.9-9.81,1.34-2.55,2.82-3.76,4.57-5.51,1.79-1.88,3.67-3.45,5.64-4.7,1.88-1.21,3.22-1.75,5.64-2.28,2.42-.4,6.18-.67,8.73-.67,2.42,0,3.9.13,6.18.94,2.15.81,5.24,2.69,7.12,4.03,1.79,1.52,3.22,3.09,4.3,4.7,1.21,1.61,1.88,2.96,2.55,5.1.67,2.15,1.34,5.1,1.34,7.66,0,2.69-.54,6.04-1.21,8.19-.63,2.24-1.43,4.03-2.42,5.37-.67,1.34-.94,1.61-2.15,2.82-1.21,1.34-3.22,3.22-4.97,4.57-1.75,1.21-4.43,2.28-5.51,3.22-.94.81-.4,2.51.4,2.42.94.13,1.75.4,4.57-.13,2.82-.4,8.33-2.15,12.22-2.82,11.99-2.63,24.41-2.63,36.4,0,3.22.54,4.16,1.07,6.31,1.75l6.04,2.28c2.42,1.07,5.51,2.42,8.19,4.16,8.15,5.36,15.14,12.3,20.55,20.42,1.61,2.42,2.87,4.66,3.76,6.72,1.85,4.51,3.42,9.13,4.7,13.84.67,2.82,1.21,4.43,1.61,8.19.4,3.76.4,11.82.54,14.37.27,2.55-.13,2.28,1.75,1.34,1.75-.94,20.09-7.74,30.63-31.57,9.16-20.71,1.9-47.26-2.28-55.34-1.75-3.22-4.16-6.99-6.31-9.81-4.44-5.14-9.6-9.62-15.31-13.3-2.96-1.7-5.55-3.09-7.79-4.16-4.33-1.6-8.77-2.86-13.3-3.76l-6.18-.4h-14.37c-2.69-.27-3.1-3.18-.54-4.3,3.64-1.58,9.88-2.63,18.54-2.42,8.78.21,14.91,1.88,17.33,2.55,13.98,3.94,30.19,16.65,38.55,30.76,6.61,11.16,9.81,29.96,9.81,29.96.37,1.75,2.18,1.66,3.08.35ZM232.78,345.3c-3.91,0-7.08,3.17-7.08,7.08s3.17,7.08,7.08,7.08,7.08-3.17,7.08-7.08-3.17-7.08-7.08-7.08Z"/></svg>';function jT(e){let t=e.status>=200&&e.status<300,r=t?"badge badge--success":"badge badge--notice",n=t?'<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" class="mark"><path fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" d="M5 12.5l4.2 4.2L19 7"/></svg>':'<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" class="mark"><path fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" d="M12 7v6M12 17h.01"/></svg>';return`<!doctype html>
|
|
47
|
+
<html lang="en">
|
|
48
|
+
<head>
|
|
49
|
+
<meta charset="utf-8" />
|
|
50
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
51
|
+
<title>${ul(e.title)}</title>
|
|
52
|
+
<style>
|
|
53
|
+
:root {
|
|
54
|
+
color-scheme: light dark;
|
|
55
|
+
/* Linzumi brand tokens (light) \u2014 kandan/server_v2/web/src/ui/theme/tokens.css */
|
|
56
|
+
--page-bg: #f5f2ee;
|
|
57
|
+
--surface: #fcfaf7;
|
|
58
|
+
--foreground: #1e1b18;
|
|
59
|
+
--muted: #5c5550;
|
|
60
|
+
--divider: rgba(138, 148, 144, 0.16);
|
|
61
|
+
--accent: #c4897a;
|
|
62
|
+
--success: #5a9a6a;
|
|
63
|
+
--success-soft: rgba(90, 154, 106, 0.1);
|
|
64
|
+
--notice-soft: rgba(196, 137, 122, 0.1);
|
|
65
|
+
--shadow: 0 12px 40px rgba(106, 138, 122, 0.12), 0 4px 12px rgba(106, 138, 122, 0.06);
|
|
66
|
+
}
|
|
67
|
+
@media (prefers-color-scheme: dark) {
|
|
68
|
+
:root {
|
|
69
|
+
/* Linzumi brand tokens (dark) */
|
|
70
|
+
--page-bg: #171b19;
|
|
71
|
+
--surface: #202522;
|
|
72
|
+
--foreground: rgba(245, 241, 232, 0.95);
|
|
73
|
+
--muted: rgba(245, 241, 232, 0.68);
|
|
74
|
+
--divider: rgba(245, 241, 232, 0.1);
|
|
75
|
+
--accent: #c8a0b0;
|
|
76
|
+
--success: #72c488;
|
|
77
|
+
--success-soft: rgba(114, 196, 136, 0.14);
|
|
78
|
+
--notice-soft: rgba(200, 160, 176, 0.14);
|
|
79
|
+
--shadow: 0 18px 50px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.35);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
* { box-sizing: border-box; }
|
|
83
|
+
body {
|
|
84
|
+
margin: 0;
|
|
85
|
+
min-height: 100vh;
|
|
86
|
+
display: grid;
|
|
87
|
+
place-items: center;
|
|
88
|
+
padding: 24px;
|
|
89
|
+
background:
|
|
90
|
+
radial-gradient(1200px 600px at 50% -10%, var(${t?"--success-soft":"--notice-soft"}), transparent 60%),
|
|
91
|
+
var(--page-bg);
|
|
92
|
+
color: var(--foreground);
|
|
93
|
+
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
|
94
|
+
-webkit-font-smoothing: antialiased;
|
|
95
|
+
}
|
|
96
|
+
main {
|
|
97
|
+
width: min(520px, 100%);
|
|
98
|
+
border: 1px solid var(--divider);
|
|
99
|
+
border-radius: 16px;
|
|
100
|
+
background: var(--surface);
|
|
101
|
+
padding: 40px 36px;
|
|
102
|
+
box-shadow: var(--shadow);
|
|
103
|
+
text-align: center;
|
|
104
|
+
}
|
|
105
|
+
.logo {
|
|
106
|
+
width: 44px;
|
|
107
|
+
height: 44px;
|
|
108
|
+
margin: 28px auto 0;
|
|
109
|
+
color: var(--accent);
|
|
110
|
+
}
|
|
111
|
+
.logo svg { display: block; width: 100%; height: 100%; }
|
|
112
|
+
.badge {
|
|
113
|
+
width: 64px;
|
|
114
|
+
height: 64px;
|
|
115
|
+
margin: 0 auto 22px;
|
|
116
|
+
display: grid;
|
|
117
|
+
place-items: center;
|
|
118
|
+
border-radius: 999px;
|
|
119
|
+
}
|
|
120
|
+
.badge--success { background: var(--success-soft); color: var(--success); }
|
|
121
|
+
.badge--notice { background: var(--notice-soft); color: var(--accent); }
|
|
122
|
+
.mark { width: 32px; height: 32px; }
|
|
123
|
+
h1 {
|
|
124
|
+
margin: 0 0 12px;
|
|
125
|
+
font-size: 23px;
|
|
126
|
+
font-weight: 600;
|
|
127
|
+
line-height: 1.3;
|
|
128
|
+
letter-spacing: -0.01em;
|
|
129
|
+
color: var(--foreground);
|
|
130
|
+
}
|
|
131
|
+
p {
|
|
132
|
+
margin: 0;
|
|
133
|
+
color: var(--muted);
|
|
134
|
+
font-size: 15px;
|
|
135
|
+
line-height: 1.6;
|
|
136
|
+
}
|
|
137
|
+
</style>
|
|
138
|
+
</head>
|
|
139
|
+
<body>
|
|
140
|
+
<main>
|
|
141
|
+
<div class="${r}">${n}</div>
|
|
142
|
+
<h1>${ul(e.title)}</h1>
|
|
143
|
+
<p>${ul(e.body)}</p>
|
|
144
|
+
<div class="logo">${OT}</div>
|
|
145
|
+
</main>
|
|
146
|
+
</body>
|
|
147
|
+
</html>`}function ul(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function CT(e){return e.replace(/[&^|<>()%"]/g,t=>`^${t}`)}function AT(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",r=process.platform==="win32"?["/c","start","",CT(e)]:[e];return new Promise(n=>{al("process.spawn",{command:t,args:r,purpose:"oauth.open_browser"});let o=wT(t,r,{stdio:"ignore",detached:!0});al("process.spawned",{command:t,args:r,pid:o.pid,purpose:"oauth.open_browser"}),o.on("error",()=>n()),o.on("spawn",()=>{o.unref(),n()})})}function Gy(){return JT(UT(),".linzumi","auth.json")}function Si(e,t=Gy()){if(!ll(t))return;let r=ml(pl(t,"utf8")),n=Ve(e),o=r.local_codex_runner?.[n];if(!(o===void 0||o.access_token.trim()==="")&&!(o.expires_at!==void 0&&Date.parse(o.expires_at)<=Date.now()))return{accessToken:o.access_token,kandanBaseUrl:n,issuedAt:o.issued_at,expiresAt:o.expires_at}}function Ky(e){if(!ll(e))throw new Error(`missing personal-agent delegation auth file: ${e}`);let r=ml(pl(e,"utf8")).personal_agent_delegation;if(r===void 0||r.access_token.trim()==="")throw new Error("personal-agent delegation auth file is missing access_token");if(r.expires_at!==void 0&&Date.parse(r.expires_at)<=Date.now())throw new Error("personal-agent delegation auth file token is expired");return{accessToken:r.access_token,issuedAt:r.issued_at,expiresAt:r.expires_at}}function Xy(e){let t=e.authFilePath??Gy(),r=ll(t)?ml(pl(t,"utf8")):{version:1},n=Ve(e.kandanUrl),o=new Date,s=e.expiresInSeconds===void 0?void 0:new Date(o.getTime()+e.expiresInSeconds*1e3).toISOString(),i={...r,version:1,local_codex_runner:{...r.local_codex_runner??{},[n]:{access_token:e.accessToken,issued_at:o.toISOString(),expires_at:s}}};NT(qT(t),{recursive:!0});let a=`${t}.tmp.${process.pid}.${MT(6).toString("hex")}`;try{ZT(a,`${JSON.stringify(i,null,2)}
|
|
148
|
+
`,{encoding:"utf8",mode:384}),LT(a,t)}catch(c){try{DT(a,{force:!0})}catch{}throw c}return{accessToken:e.accessToken,kandanBaseUrl:n,issuedAt:o.toISOString(),expiresAt:s}}function ml(e){let t=JSON.parse(e);if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Kandan auth cache must contain a JSON object");let r=t,n=r.local_codex_runner,o=r.personal_agent_delegation;if(n!==void 0&&(typeof n!="object"||n===null||Array.isArray(n)))throw new Error("Kandan auth cache local_codex_runner must be an object");if(o!==void 0&&(typeof o!="object"||o===null||Array.isArray(o)))throw new Error("Kandan auth cache personal_agent_delegation must be an object");return{version:1,local_codex_runner:VT(n),personal_agent_delegation:FT(o)}}function FT(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.access_token,r=e.issued_at,n=e.expires_at;if(!(typeof t!="string"||typeof r!="string"))return{access_token:t,issued_at:r,expires_at:typeof n=="string"?n:void 0}}function VT(e){if(!(typeof e!="object"||e===null||Array.isArray(e)))return Object.fromEntries(Object.entries(e).flatMap(([t,r])=>{if(typeof r!="object"||r===null||Array.isArray(r))return[];let n=r.access_token,o=r.issued_at,s=r.expires_at;return typeof n!="string"||typeof o!="string"?[]:[[t,{access_token:n,issued_at:o,expires_at:typeof s=="string"?s:void 0}]]}))}var BT=3,HT=3600*1e3,WT=5e3,GT=5e3,KT=6e4;function XT(e){return e.cycle<=BT?"prompt":e.lastLoudPromptAtMs===void 0||e.nowMs-e.lastLoudPromptAtMs>=HT?"summary":e.isInteractive?"refresh_line":"silent"}function YT(e){switch(e.kind){case"prompt":return`${e.cycle===1?"":`The previous code expired; here is a fresh one (no restart needed - this prompt stays alive).
|
|
149
|
+
`}Authorize this computer:
|
|
150
|
+
Code: ${e.userCode}
|
|
151
|
+
Open: ${e.verificationUri}
|
|
152
|
+
`;case"summary":return`Still waiting for authorization after ${Yy(e.waitedMs)} (${e.cycle} codes issued so far).
|
|
153
|
+
Authorize this computer:
|
|
154
|
+
Code: ${e.userCode}
|
|
155
|
+
Open: ${e.verificationUri}
|
|
156
|
+
`;case"refresh_line":return`\r\x1B[2KCode: ${e.userCode} (waiting ${Yy(e.waitedMs)}) - open ${e.verificationUri}`;case"transient":return`Device authorization poll hit a transient failure (${e.reason}); retrying with the same code.
|
|
157
|
+
`;case"start_failed":return`Could not mint a device authorization code (${e.reason}); retrying in ${Math.round(e.retryInMs/1e3)}s.
|
|
158
|
+
`}}function Yy(e){let t=Math.floor(e/6e4),r=Math.floor(t/60),n=t%60;return r>0?`${r}h ${n}m`:`${n}m`}async function Qy(e){let t=e.deps??{},r=t.startDeviceAuthorization??By,n=t.pollDeviceCodeForToken??Hy,o=t.now??Date.now,s=t.sleep??(g=>new Promise(y=>setTimeout(y,g))),i=e.writeStderr??(g=>process.stderr.write(g)),a=e.isInteractive??process.stderr.isTTY===!0,c=t.report??(g=>i(YT(g))),u=t.log??(()=>{}),d=Ve(e.kandanUrl),l=o(),p=0,h,f=0;for(;;){let g;try{g=await r({httpBaseUrl:d,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,onboarding:e.onboarding,identity:e.identity})}catch(w){f+=1;let k=Math.min(KT,GT*2**(f-1)),R=w instanceof Error?w.message:String(w);c({kind:"start_failed",reason:R,retryInMs:k}),u("device_wait.start_failed",{reason:R,retryInMs:k,attempt:f}),await s(k);continue}f=0,p+=1;let y=XT({cycle:p,nowMs:o(),lastLoudPromptAtMs:h,isInteractive:a});y==="prompt"||y==="summary"?(h=o(),c({kind:y,cycle:p,userCode:g.userCode,verificationUri:g.verificationUri,waitedMs:o()-l})):y==="refresh_line"&&c({kind:"refresh_line",cycle:p,userCode:g.userCode,verificationUri:g.verificationUri,waitedMs:o()-l}),u("device_wait.code_issued",{cycle:p,verificationUri:g.verificationUri});let b;for(;b=await n({httpBaseUrl:d,deviceCode:g.deviceCode,expiresInSeconds:g.expiresInSeconds}),b.kind==="transient";)c({kind:"transient",reason:b.reason,waitedMs:o()-l}),u("device_wait.transient_poll_failure",{cycle:p,reason:b.reason,httpStatus:b.httpStatus??null}),await s(WT);switch(b.kind){case"token":return u("device_wait.authorized",{cycle:p,waitedMs:o()-l}),b.token;case"denied":throw new Error("local runner device authorization was denied - a signed-in user rejected this computer");case"code_expired":case"consumed":u("device_wait.code_retired",{cycle:p,outcome:b.kind});continue;case"rejected":c({kind:"transient",reason:Wy(b.reason,b.httpStatus),waitedMs:o()-l}),u("device_wait.code_rejected",{cycle:p,reason:b.reason??null,httpStatus:b.httpStatus});continue}}}import{randomUUID as u_}from"node:crypto";import{chmodSync as o_,existsSync as _l,linkSync as tR,mkdirSync as d_,readFileSync as l_,realpathSync as cM,unlinkSync as rR,writeFileSync as p_}from"node:fs";import{homedir as nR}from"node:os";import{basename as hl,dirname as Io,join as gl,resolve as s_}from"node:path";var e_="wss://serve.linzumi.com";import{homedir as QT}from"node:os";import{isAbsolute as rM,relative as nM,resolve as eR}from"node:path";import{delimiter as B4,isAbsolute as H4,join as t_,parse as W4,resolve as G4,sep as K4}from"node:path";var X4=[".volta",".nvm",".npm",".asdf",".fnm",".bun",t_(".cargo","bin"),t_(".local","bin")];function n_(e){return e==="~"?r_():e.startsWith("~/")?eR(r_(),e.slice(2)):e}function r_(){let e=process.env.HOME;return e===void 0||e.trim()===""?QT():e}var fl=384,Lt="prod";function kn(e=process.env){let t=e.LINZUMI_CONFIG_FILE;return t!==void 0&&t.trim()!==""?s_(n_(t)):s_(nR(),".linzumi","config.json")}function Oo(e){let t=Ve(e),r=Ve(e_);return t===r?Lt:t}function oR(e){let t=Oo(e);return t===Lt?Lt:Buffer.from(t).toString("base64url")}function i_(e=kn()){return f_(e)}function a_(e,t=kn()){return f_(t,e)}function m_(e,t=kn(),r=v_){if(Oo(e)===Lt)return sR(t,r);let n=a_(e,t);if(n.runnerId!==void 0)return n.runnerId;let o=__(t,r,e),s=a_(e,t),i=s.runnerId;return i!==void 0?i:(h_({...s,runnerId:o},t,e),o)}function sR(e=kn(),t=v_){let r=i_(e);if(r.runnerId!==void 0)return r.runnerId;let n=__(e,t),o=i_(e),s=o.runnerId;return s!==void 0?s:(aR({...o,runnerId:n},e),n)}function iR(e=kn(),t){return t!==void 0&&Oo(t)!==Lt?gl(Io(e),`${hl(e)}.${oR(t)}.runner-id`):gl(Io(e),`${hl(e)}.runner-id`)}function aR(e,t=kn()){h_(e,t)}function cR(e,t){_l(e)&&o_(e,fl),p_(e,`${JSON.stringify(t,null,2)}
|
|
159
|
+
`,{encoding:"utf8",mode:fl}),o_(e,fl)}function yl(e){if(!_l(e))return{version:1,allowedCwds:[]};let t=JSON.parse(l_(e,"utf8"));if(!g_(t))throw new Error(`invalid Linzumi config: ${e}`);return t}function f_(e,t){let r=yl(e),n=t===void 0?Lt:Oo(t),o=n===Lt?r:r[n]??dR();if(!y_(o))throw new Error(`invalid Linzumi config section ${n}: ${e}`);let s=b_(o.allowedCwds);return{version:1,...o.machineId===void 0?{}:{machineId:o.machineId},...o.runnerId===void 0?{}:{runnerId:o.runnerId},allowedCwds:s}}function h_(e,t,r){let n=r===void 0?Lt:Oo(r),o=uR(e),s=n===Lt?{...yl(t),...o,version:1}:{...yl(t),version:1,[n]:o};d_(Io(t),{recursive:!0}),cR(t,s)}function g_(e){return typeof e=="object"&&e!==null&&e.version===1&&y_(e)}function y_(e){return typeof e=="object"&&e!==null&&Array.isArray(e.allowedCwds)&&lR(e.machineId)&&vl(e.runnerId)&&e.allowedCwds.every(t=>typeof t=="string"&&t.trim()!=="")}function uR(e){if(!g_(e))throw new Error("invalid Linzumi config");let t=b_(e.allowedCwds);return{...e.machineId===void 0?{}:{machineId:e.machineId},...e.runnerId===void 0?{}:{runnerId:e.runnerId},allowedCwds:t}}function dR(){return{allowedCwds:[]}}function lR(e){return e===void 0||typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function vl(e){return e===void 0||typeof e=="string"&&/^[a-zA-Z0-9_.-]+$/.test(e)}function __(e,t,r){let n=iR(e,r);if(_l(n))return c_(n);let o=t();if(!vl(o))throw new Error(`invalid generated Linzumi runner id: ${o}`);d_(Io(n),{recursive:!0});let s=gl(Io(n),`.${hl(n)}.${process.pid}.${u_()}.tmp`);p_(s,`${o}
|
|
160
|
+
`,{encoding:"utf8",flag:"wx"});try{return tR(s,n),o}catch(i){if(pR(i,"EEXIST"))return c_(n);throw i}finally{rR(s)}}function c_(e){let t=l_(e,"utf8").trim();if(!vl(t))throw new Error(`invalid Linzumi runner id seed: ${e}`);return t}function v_(){return`runner-${u_()}`}function b_(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t!==""))]}function pR(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}import{execFileSync as mR}from"node:child_process";import{createHash as fR}from"node:crypto";import{readFileSync as hR}from"node:fs";var gR="linzumi-machine-fingerprint:v1:";function yR(e,t){return mR(e,[...t],{encoding:"utf8",timeout:5e3,maxBuffer:1024*1024})}function _R(e){return hR(e,"utf8")}function vR(e={}){let t=e.platform??process.platform,r=e.execFile??yR,n=e.readFile??_R;try{if(t==="darwin"){let i=r("ioreg",["-rd1","-c","IOPlatformExpertDevice"]).match(/"IOPlatformUUID"\s*=\s*"([0-9A-Fa-f-]{36})"/)?.[1];return i===void 0?void 0:i.toLowerCase()}if(t==="linux"){for(let o of["/etc/machine-id","/var/lib/dbus/machine-id"])try{let s=n(o).trim().toLowerCase();if(/^[0-9a-f]{32}$/.test(s))return s}catch{}return}return}catch{return}}function w_(e={}){let t=vR(e);return t===void 0?void 0:`mfp-${fR("sha256").update(`${gR}${t}`).digest("hex").slice(0,32)}`}async function k_(e,t={readCachedToken:Si,validateToken:Eo,acquireAndCacheToken:xR}){if(e.explicitToken!==void 0)return e.explicitToken;let r=t.readCachedToken(e.kandanUrl,e.authFilePath);if(r!==void 0){let o=await t.validateToken({kandanUrl:e.kandanUrl,accessToken:r.accessToken,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,requiredScopes:e.requiredScopes});if(o==="usable")return r.accessToken;e.reportRejectedCachedToken?.(o)}let n=await t.acquireAndCacheToken(e);return e.workspaceSlug!==void 0&&await wR(e,t,n),n}async function wR(e,t,r){let n;try{n=await t.validateToken({kandanUrl:e.kandanUrl,accessToken:r,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,requiredScopes:e.requiredScopes})}catch{return}if(n==="not_found")throw new Error(kR(e))}function kR(e){let t=new URL(Ve(e.kandanUrl)).host;return`Workspace '${e.workspaceSlug}' was not found on ${t}. Sign in to the web app to create it, then re-run connect.`}async function xR(e){let t=e.authMode??{kind:"browser",callbackHost:e.callbackHost},r=t.kind==="device"?await Qy({kandanUrl:e.kandanUrl,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,onboarding:e.onboarding,identity:{runnerId:m_(e.kandanUrl),machineFingerprint:w_(),hostname:bR()}}):await Fy({kandanUrl:e.kandanUrl,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,onboarding:e.onboarding,callbackHost:t.callbackHost??e.callbackHost});return Xy({kandanUrl:e.kandanUrl,accessToken:r.accessToken,expiresInSeconds:r.expiresInSeconds,authFilePath:e.authFilePath}),r.accessToken}import{readFile as EM,realpath as wl,stat as SR,writeFile as IM,mkdir as OM}from"node:fs/promises";import{homedir as $R}from"node:os";import{basename as zR,extname as PR,isAbsolute as S_,join as AM,relative as $_,resolve as bl}from"node:path";function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zt(e){return e!==void 0&&ft(e)?e:void 0}function $i(e){return Array.isArray(e)?e:void 0}function we(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}function x_(e){return typeof e=="number"&&Number.isInteger(e)?e:void 0}var TR=new Set([".csv",".diff",".gif",".htm",".html",".jpeg",".jpg",".json",".jsonl",".log",".md",".mp4",".patch",".pdf",".png",".svg",".txt",".webm",".webp",".xml",".zip"]);async function kl(e,t){let r=await wl(e),n=await IR(r),o=await RR(r,t);ER(n,o);let s=await SR(o);if(!s.isFile())throw new Error(`Linzumi upload path is not a file: ${o}`);return{path:o,fileName:zR(o),contentType:jR(o),sizeBytes:s.size}}async function RR(e,t){if(t==="")throw new Error("Kandan attachment path must not be empty");let r=S_(t)?bl(t):bl(e,t);return await wl(r)}function ER(e,t){let r=e.find(i=>OR(i.path,t));if(r===void 0){let i=e.map(a=>a.label).join(", ");throw new Error(`Kandan attachment path must resolve inside an allowed upload root (${i}): ${t}`)}if($_(r.path,t).split(/[\\/]+/).find(i=>i.startsWith("."))!==void 0)throw new Error(`Kandan attachment upload path must not include hidden path segments: ${t}`);let s=PR(t).toLowerCase();if(!TR.has(s))throw new Error(`Kandan attachment upload path extension is not allowed: ${t}`)}async function IR(e){let t=[{path:e,label:"runner cwd"}],r=process.env.HOME?.trim(),n=bl(r===void 0||r===""?$R():r,"Downloads");try{let o=await wl(n);t.some(s=>s.path===o)||t.push({path:o,label:"~/Downloads"})}catch{return t}return t}function OR(e,t){let r=$_(e,t);return r===""||!r.startsWith("..")&&!S_(r)}function jR(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 xl(e){let t=e.fetchImpl??fetch,r=Ve(e.kandanUrl),n=e.authMode==="personal-agent-delegation"?"/api/v2/personal-agent-mcp":"/api/v2/local-runner-mcp",o=e.operatingMode??"text",s=async(i,a,c,u={})=>{let d=new URL(a,r),l={...c,operating_mode:o},p={method:i,headers:{authorization:`Bearer ${e.accessToken}`},...u.signal===void 0?{}:{signal:u.signal}};if(i==="GET")for(let[w,k]of Object.entries(l))k!=null&&d.searchParams.set(w,String(k));else p.headers={...p.headers,"content-type":"application/json"},p.body=JSON.stringify(l);let h=await t(d,p),f=await h.json(),g=ft(f)?f:void 0;if(g===void 0)throw new Error(`Linzumi MCP API returned non-object JSON from ${a}`);if(h.ok&&g.ok===!0)return g;let y=typeof g.error=="string"?g.error:`HTTP ${h.status}`,b=typeof g.detail=="string"?g.detail:void 0;throw new Error(`Linzumi MCP API ${a} failed: ${y}${b===void 0?"":` detail=${b}`}`)};return{validateAuth:()=>s("GET",`${n}/validate`,{}),issueOnboardingDiscoveryToken:i=>s("POST",`${n}/onboarding-discovery-token`,i),getMessage:i=>s("GET",`${n}/message`,i),getThread:i=>s("GET",`${n}/thread`,i),getThreadTranscript:i=>s("GET",`${n}/thread-transcript`,i),getChannel:i=>s("GET",`${n}/channel`,i),searchWorkspace:i=>s("GET",`${n}/search`,i),askWorkspace:i=>s("POST",`${n}/ask`,i),aboutMe:i=>s("GET",`${n}/about-me`,i),webSearch:i=>s("GET",`${n}/web-search`,i),fetchUrl:i=>s("GET",`${n}/fetch-url`,i),listUiTargets:i=>s("GET",`${n}/ui-targets`,i),openUi:i=>s("POST",`${n}/open-ui`,i),getCodingJobMetadata:i=>s("GET",`${n}/coding-job-metadata`,i),listProjects:i=>s("GET",`${n}/projects`,i),getProjectTasks:i=>s("GET",`${n}/project-tasks`,i),createProjectTask:i=>s("POST",`${n}/project-tasks/create`,i),updateProjectTask:i=>s("POST",`${n}/project-tasks/update`,i),deleteProjectTask:i=>s("POST",`${n}/project-tasks/delete`,i),addProjectTaskDependency:i=>s("POST",`${n}/project-tasks/add-dependency`,i),removeProjectTaskDependency:i=>s("POST",`${n}/project-tasks/remove-dependency`,i),getCallTranscript:i=>s("GET",`${n}/call-transcript`,i),renameCodingJob:i=>s("POST",`${n}/coding-job-title`,i),upsertCodingJobPlan:(i,a)=>s("POST",`${n}/coding-job-plan`,i,a),replaceCodingJobPlanSteps:i=>s("POST",`${n}/coding-job-plan/steps`,i),updateCodingJobPlanStep:i=>s("POST",`${n}/coding-job-plan/step`,i),linkCodingJobPullRequest:i=>s("POST",`${n}/coding-job-primary-pr`,i),listVaultSecrets:i=>s("GET",`${n}/vault-secrets`,i),noteProjectDirectory:i=>s("POST",`${n}/discovered-project`,i),noteAgentConversation:i=>s("POST",`${n}/discovered-conversation`,i),noteOnboardingDiscoveryStatus:i=>s("POST",`${n}/discovery-status`,i),sendChannelMessage:i=>s("POST",`${n}/channel-message`,i),editMessage:i=>s("POST",`${n}/message/edit`,i),agentReply:i=>s("POST",`${n}/agent-reply`,i),agentTurnProgress:i=>s("POST",`${n}/agent-turn-progress`,i),agentListCodingJobs:i=>s("GET",`${n}/agent/coding-jobs`,i),agentStartCodingJob:i=>s("POST",`${n}/agent/start-coding-job`,i),agentInterruptCodingJob:i=>s("POST",`${n}/agent/interrupt-coding-job`,i),agentSendCodingJobMessage:i=>s("POST",`${n}/agent/send-coding-job-message`,i),agentReadCodingJobThread:i=>s("GET",`${n}/agent/coding-job-thread`,i),agentResolveJobApproval:i=>s("POST",`${n}/agent/resolve-job-approval`,i),agentArchiveCodingJob:i=>s("POST",`${n}/agent/archive-coding-job`,i),agentUnarchiveCodingJob:i=>s("POST",`${n}/agent/unarchive-coding-job`,i),agentSetThreadStatus:i=>s("POST",`${n}/agent/set-thread-status`,i),agentCreateChannel:i=>s("POST",`${n}/agent/create-channel`,i),agentRenameChannel:i=>s("POST",`${n}/agent/rename-channel`,i),agentArchiveChannel:i=>s("POST",`${n}/agent/archive-channel`,i),agentUnarchiveChannel:i=>s("POST",`${n}/agent/unarchive-channel`,i),agentAddReaction:i=>s("POST",`${n}/agent/add-reaction`,i),agentRemoveReaction:i=>s("POST",`${n}/agent/remove-reaction`,i),agentPinMessage:i=>s("POST",`${n}/agent/pin-message`,i),agentUnpinMessage:i=>s("POST",`${n}/agent/unpin-message`,i),prepareMessageUploads:i=>s("POST",`${n}/message-uploads/prepare`,i),attachMessageFiles:i=>s("POST",`${n}/message-files/attach`,i),prepareCustomEmoji:i=>s("POST",`${n}/custom-emoji/prepare`,i),renameCustomEmoji:i=>s("POST",`${n}/custom-emoji/rename`,i),sendThreadReply:i=>s("POST",`${n}/thread-reply`,i),sendDm:i=>s("POST",`${n}/dm`,i),dmOwner:i=>s("POST",`${n}/dm-owner`,i),getVaultValues:i=>s("POST",`${n}/vault-values`,i)}}import{closeSync as z_,fstatSync as CR,mkdirSync as zi,openSync as P_,readdirSync as AR,readFileSync as T_,readSync as MR,renameSync as NR,rmSync as Sl,statSync as LR,writeFileSync as R_}from"node:fs";import{spawn as DR,execFile as VM}from"node:child_process";import{createHash as ZR}from"node:crypto";import{createConnection as UR}from"node:net";import{homedir as qR}from"node:os";import{dirname as $l,join as Lr}from"node:path";var E_=()=>{},I_=1;function JR(){let e=process.env.LINZUMI_DEV_SERVICES_DIR?.trim();return e!==void 0&&e!==""?e:Lr(qR(),".linzumi","dev-services")}function O_(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,80),r=ZR("sha256").update(e).digest("hex").slice(0,8),n=t===""?"runner":t;return Lr(JR(),`${n}.${r}`)}function Pi(e){let t=e.trim().toLowerCase();return/^[a-z0-9][a-z0-9._-]{0,63}$/.test(t)&&!t.includes("..")?t:void 0}function zl(e,t){return Lr(e,"services",`${t}.json`)}function Pl(e,t){return Lr(e,"exits",`${t}.json`)}function j_(e,t){return Lr(e,"logs",`${t}.log`)}function jo(e){return typeof e=="string"&&e!==""?e:void 0}function Co(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function FR(e){return Array.isArray(e)?e.filter(t=>typeof t=="number"&&Number.isInteger(t)&&t>0&&t<=65535):[]}function VR(e){if(!ft(e)||e.version!==I_)return;let t=jo(e.name),r=t===void 0?void 0:Pi(t),n=jo(e.command),o=jo(e.cwd),s=e.desiredState==="running"||e.desiredState==="stopped"?e.desiredState:void 0,i=Co(e.updatedAtMs),a=jo(e.logPath);if(!(r===void 0||r!==t||n===void 0||o===void 0||s===void 0||i===void 0||a===void 0))return{name:r,command:n,cwd:o,ports:FR(e.ports),restartOnBranchChange:e.restartOnBranchChange===!0,desiredState:s,pid:Co(e.pid),ownerPid:Co(e.ownerPid),startedAtMs:Co(e.startedAtMs),updatedAtMs:i,lastBranch:jo(e.lastBranch),logPath:a}}function BR(e){return{version:I_,name:e.name,command:e.command,cwd:e.cwd,ports:[...e.ports],restartOnBranchChange:e.restartOnBranchChange,desiredState:e.desiredState,pid:e.pid??null,ownerPid:e.ownerPid??null,startedAtMs:e.startedAtMs??null,updatedAtMs:e.updatedAtMs,lastBranch:e.lastBranch??null,logPath:e.logPath}}function C_(e,t,r){let n=zl(e,t.name);try{zi($l(n),{recursive:!0});let o=`${n}.tmp`;R_(o,`${JSON.stringify(BR(t))}
|
|
161
|
+
`,"utf8"),NR(o,n)}catch(o){r("dev_services.record_write_failed",{path:n,message:o instanceof Error?o.message:String(o)})}}function Tl(e,t){let r=Pi(t);if(r===void 0)return;let n;try{n=T_(zl(e,r),"utf8")}catch{return}try{return VR(JSON.parse(n))}catch{return}}function HR(e){let t;try{t=AR(Lr(e,"services"))}catch{return[]}let r=[];for(let n of t){if(!n.endsWith(".json"))continue;let o=Tl(e,n.slice(0,-5));o!==void 0&&r.push(o)}return r.sort((n,o)=>n.name.localeCompare(o.name))}function A_(e,t){let r;try{r=T_(Pl(e,t),"utf8")}catch{return}try{let n=JSON.parse(r);if(!ft(n))return;let o=Co(n.atMs);return o===void 0?void 0:{code:typeof n.code=="number"?n.code:null,signal:typeof n.signal=="string"?n.signal:null,atMs:o}}catch{return}}function WR(e){return JSON.stringify(e)}function GR(){return`
|
|
162
|
+
const { spawn } = require('node:child_process');
|
|
163
|
+
const fs = require('node:fs');
|
|
164
|
+
const config = JSON.parse(process.argv[process.argv.length - 1]);
|
|
165
|
+
const child = spawn(config.command, config.args, { cwd: config.cwd, stdio: 'inherit' });
|
|
166
|
+
let done = false;
|
|
167
|
+
function shutdown(signal) {
|
|
168
|
+
if (done) return;
|
|
169
|
+
done = true;
|
|
170
|
+
try { process.kill(-process.pid, signal); }
|
|
171
|
+
catch (_e) { try { child.kill(signal); } catch (_e2) {} }
|
|
172
|
+
}
|
|
173
|
+
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
174
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
175
|
+
process.on('SIGHUP', () => shutdown('SIGTERM'));
|
|
176
|
+
child.on('exit', (code, signal) => {
|
|
177
|
+
clearInterval(watchdog);
|
|
178
|
+
// Record the exit before following the child down, so a crash is
|
|
179
|
+
// explainable from dev_service_status/logs after the fact. Best-effort:
|
|
180
|
+
// never let bookkeeping block teardown.
|
|
181
|
+
try {
|
|
182
|
+
fs.writeFileSync(config.exitStatusPath, JSON.stringify({ code: code, signal: signal, atMs: Date.now() }) + '\\n', 'utf8');
|
|
183
|
+
} catch (_e) {}
|
|
184
|
+
process.removeAllListeners('SIGINT');
|
|
185
|
+
process.removeAllListeners('SIGTERM');
|
|
186
|
+
process.removeAllListeners('SIGHUP');
|
|
187
|
+
// Sweep any grandchildren left in the group (a dev server that forked
|
|
188
|
+
// workers must not leak them past its own death), then follow the child.
|
|
189
|
+
try { process.kill(-process.pid, 'SIGKILL'); } catch (_e) {}
|
|
190
|
+
if (signal) { try { process.kill(process.pid, signal); } catch (_e) {} }
|
|
191
|
+
process.exit(signal ? 1 : code == null ? 0 : code);
|
|
192
|
+
});
|
|
193
|
+
child.on('error', (err) => {
|
|
194
|
+
try {
|
|
195
|
+
fs.writeFileSync(config.exitStatusPath, JSON.stringify({ code: 127, signal: null, atMs: Date.now() }) + '\\n', 'utf8');
|
|
196
|
+
} catch (_e) {}
|
|
197
|
+
process.stderr.write('dev-service spawn failed: ' + (err && err.message) + '\\n');
|
|
198
|
+
process.exit(1);
|
|
199
|
+
});
|
|
200
|
+
const watchdog = setInterval(() => {
|
|
201
|
+
// Inlined devServiceOwnerAlive (keep in sync): the owning runner's death
|
|
202
|
+
// takes the whole service group down - managed services die with the
|
|
203
|
+
// runner BY DESIGN (desired state + reconcile provide the durability).
|
|
204
|
+
// EPERM = alive-but-unsignalable; anything else thrown by kill(pid, 0)
|
|
205
|
+
// means the runner is gone.
|
|
206
|
+
if (config.ownerPid > 0) {
|
|
207
|
+
let alive = true;
|
|
208
|
+
try { process.kill(config.ownerPid, 0); }
|
|
209
|
+
catch (e) { alive = e && e.code === 'EPERM'; }
|
|
210
|
+
if (!alive) {
|
|
211
|
+
try { child.kill('SIGKILL'); } catch (_e) {}
|
|
212
|
+
try { process.kill(-process.pid, 'SIGKILL'); } catch (_e) {}
|
|
213
|
+
process.exit(0);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}, config.pollIntervalMs);
|
|
217
|
+
`.trim()}function KR(e,t){return{command:e,args:["-e",GR(),WR(t)]}}function M_(e,t=r=>process.kill(r,0)){if(e===void 0||e<=1)return!1;try{return t(-e),!0}catch(r){return r?.code==="EPERM"}}function Rl(e,t){if(t.pid===void 0||t.pid<=1)return!1;let r=A_(e,t.name);return r!==void 0&&t.startedAtMs!==void 0&&r.atMs>=t.startedAtMs?!1:M_(t.pid)}async function El(e,t=750,r="127.0.0.1"){return await new Promise(n=>{let o=UR({port:e,host:r}),s=i=>{o.removeAllListeners(),o.destroy(),n(i)};o.setTimeout(t),o.once("connect",()=>s(!0)),o.once("timeout",()=>s(!1)),o.once("error",()=>s(!1))})}async function XR(e,t){let r=Rl(e,t),n=[];for(let s of t.ports)n.push({port:s,listening:r?await El(s):!1});let o=t.desiredState==="stopped"?"stopped":r?n.every(s=>s.listening)?"running":"unhealthy":"exited";return{record:t,liveness:o,portProbes:n,lastExit:A_(e,t.name)}}async function Il(e){let t=[];for(let r of HR(e))t.push(await XR(e,r));return t}function YR(e=process.env){let t=e.SHELL?.trim();return t!==void 0&&t!==""?t:"/bin/sh"}async function N_(e){let t=e.log??E_,r=Pi(e.definition.name);if(r===void 0)return{ok:!1,error:"invalid service name: use 1-64 lowercase letters, digits, ., _ or -"};let n=e.definition.command.trim();if(n==="")return{ok:!1,error:"service command must not be empty"};try{if(!LR(e.definition.cwd).isDirectory())return{ok:!1,error:`cwd is not a directory: ${e.definition.cwd}`}}catch{return{ok:!1,error:`cwd does not exist: ${e.definition.cwd}`}}let o=Tl(e.scopeDir,r);o!==void 0&&Rl(e.scopeDir,o)&&await L_(o.pid,t,r);let s=e.nowMs??Date.now(),i=j_(e.scopeDir,r),a=Pl(e.scopeDir,r),c;try{zi($l(i),{recursive:!0}),zi(Lr(e.scopeDir,"services"),{recursive:!0}),zi($l(a),{recursive:!0}),c=P_(i,"a")}catch(h){return{ok:!1,error:`cannot open service log: ${h instanceof Error?h.message:String(h)}`}}try{Sl(a,{force:!0})}catch{}let u=e.shellPath??YR(),d=KR(e.nodeExecPath??process.execPath,{command:u,args:["-lc",n],cwd:e.definition.cwd,ownerPid:e.ownerPid,pollIntervalMs:e.watchdogPollIntervalMs??500,exitStatusPath:a});try{R_(c,`
|
|
218
|
+
--- linzumi dev-service "${r}" starting at ${new Date(s).toISOString()} (owner pid ${e.ownerPid}) ---
|
|
219
|
+
$ ${n}
|
|
220
|
+
`)}catch{}let l;try{let h=DR(d.command,[...d.args],{cwd:e.definition.cwd,detached:!0,stdio:["ignore",c,c],env:{...process.env,ELECTRON_RUN_AS_NODE:"1"}});h.unref(),l=h.pid}catch(h){return{ok:!1,error:`spawn failed: ${h instanceof Error?h.message:String(h)}`}}finally{try{z_(c)}catch{}}if(l===void 0)return{ok:!1,error:"spawn failed: no pid"};let p={name:r,command:n,cwd:e.definition.cwd,ports:[...new Set(e.definition.ports)].sort((h,f)=>h-f),restartOnBranchChange:e.definition.restartOnBranchChange===!0,desiredState:"running",pid:l,ownerPid:e.ownerPid,startedAtMs:s,updatedAtMs:s,lastBranch:void 0,logPath:i};return C_(e.scopeDir,p,t),t("dev_services.started",{name:r,pid:l,owner_pid:e.ownerPid,cwd:e.definition.cwd,ports:[...p.ports]}),{ok:!0,record:p}}async function L_(e,t,r,n=3e3){if(e===void 0||e<=1)return;try{process.kill(-e,"SIGTERM")}catch{return}let o=Date.now()+n;for(;Date.now()<o;){if(!M_(e))return;await new Promise(s=>setTimeout(s,100))}try{process.kill(-e,"SIGKILL"),t("dev_services.stop_escalated",{name:r,pgid:e})}catch{}}async function Ol(e){let t=e.log??E_,r=Tl(e.scopeDir,e.name);if(r===void 0)return{ok:!1,error:`unknown service: ${e.name}`};Rl(e.scopeDir,r)&&await L_(r.pid,t,r.name);let n={...r,desiredState:"stopped",pid:void 0,ownerPid:void 0,updatedAtMs:e.nowMs??Date.now()};return C_(e.scopeDir,n,t),t("dev_services.stopped",{name:r.name}),{ok:!0,record:n}}async function D_(e){let t=await Ol(e);if(!t.ok)return t;try{Sl(zl(e.scopeDir,t.record.name),{force:!0}),Sl(Pl(e.scopeDir,t.record.name),{force:!0})}catch{}return t}function Z_(e,t,r=16384){let n=Pi(t);if(n===void 0)return;let o=j_(e,n),s;try{s=P_(o,"r");let i=CR(s).size,a=Math.min(i,r),c=Buffer.alloc(a);return MR(s,c,0,a,i-a),c.toString("utf8")}catch{return}finally{if(s!==void 0)try{z_(s)}catch{}}}var XM=10*6e4;function U_(e){return{name:"linzumi",command:e.command??"linzumi",args:[...e.argsPrefix??[],"mcp","server","--api-url",e.kandanUrl,...e.authFilePath===void 0?[]:["--auth-file",e.authFilePath],...e.delegationAuthFilePath===void 0?[]:["--delegation-auth-file",e.delegationAuthFilePath],...e.ownerUsername===void 0?[]:["--owner-username",e.ownerUsername],...e.cwd===void 0?[]:["--cwd",e.cwd],...e.threadId===void 0?[]:["--thread-id",e.threadId],"--mode",e.operatingMode??"text",...e.toolScope===void 0||e.toolScope==="all"?[]:["--tool-scope",e.toolScope],...e.agentSession===!0?["--agent-session"]:[]],env:{...e.accessToken===void 0?{}:{LINZUMI_MCP_ACCESS_TOKEN:e.accessToken},...e.devServices===void 0?{}:{LINZUMI_DEV_SERVICES_SCOPE:e.devServices.scope,LINZUMI_DEV_SERVICES_OWNER_PID:String(e.devServices.ownerPid)},ELECTRON_RUN_AS_NODE:"1"}}}function q_(e){return`${JSON.stringify({mcpServers:{[e.name]:{command:e.command,args:e.args,env:e.env}}},null,2)}
|
|
221
|
+
`}function J_(e){return`[mcp_servers.${e.name}]
|
|
222
|
+
command = ${JSON.stringify(e.command)}
|
|
223
|
+
args = ${QR(e.args)}
|
|
224
|
+
${Object.keys(e.env).length===0?"":`env = ${eE(e.env)}
|
|
225
|
+
`}`}function QR(e){return`[${e.map(t=>JSON.stringify(t)).join(", ")}]`}function eE(e){return`{ ${Object.entries(e).map(([r,n])=>`${r} = ${JSON.stringify(n)}`).join(", ")} }`}var F_=`<linzumi_markdown_media_guidance>
|
|
226
|
+
Some Linzumi users have opted into rich Markdown media rendering. When you are
|
|
227
|
+
writing a visible Linzumi message, channel message, or thread reply, you may use
|
|
228
|
+
these Markdown-compatible media directives:
|
|
229
|
+
|
|
230
|
+
- Audio: ::audio[Label]{src="https://serve.linzumi.com/api/v2/workspaces/<workspace>/channels/<channel>/files/<file>/download?share_token=<token>" caption="Short caption" meta="MP3, 12s" source="Original source"}
|
|
231
|
+
- Video: ::video[Label]{src="https://serve.linzumi.com/api/v2/workspaces/<workspace>/channels/<channel>/files/<file>/download?share_token=<token>" caption="Short caption" meta="MP4, 1080p" poster="https://serve.linzumi.com/api/v2/workspaces/<workspace>/channels/<channel>/files/<poster-file>/download?share_token=<token>" source="Original source"}
|
|
232
|
+
- Image: ::image[Label]{src="https://serve.linzumi.com/api/v2/workspaces/<workspace>/channels/<channel>/files/<file>/download?share_token=<token>" caption="Short caption" meta="PNG, 1200x800" source="Original source"}
|
|
233
|
+
- Markdown image: 
|
|
234
|
+
|
|
235
|
+
<media_rules>
|
|
236
|
+
- Use this syntax only for user-visible media that helps the user inspect or
|
|
237
|
+
play the artifact directly in the message.
|
|
238
|
+
- "src" is required. Every other field is optional.
|
|
239
|
+
- "src" must be a full Linzumi attachment download URL on
|
|
240
|
+
"https://serve.linzumi.com/api/v2/workspaces/.../channels/.../files/.../download".
|
|
241
|
+
Do not use arbitrary external URLs for auto-rendered media.
|
|
242
|
+
- "poster" is optional, video-only, and must use the same full Linzumi
|
|
243
|
+
attachment download URL shape. If poster is omitted, the video still renders
|
|
244
|
+
with the browser's native unloaded video surface.
|
|
245
|
+
- "caption", "meta", and "source" are optional text fields. Keep them short.
|
|
246
|
+
- Use at most 10 media embeds in one message. If there are more artifacts,
|
|
247
|
+
attach them and summarize the rest with ordinary links or text.
|
|
248
|
+
- Do not use root-relative URLs such as "/files/a.mp3", local filesystem paths
|
|
249
|
+
such as "/tmp/a.mp3", "file://" URLs, object-store upload URLs, third-party
|
|
250
|
+
CDN URLs, or guessed attachment URLs.
|
|
251
|
+
- If you created local files that should be attached, upload/attach the files
|
|
252
|
+
first. Then use the returned "message.attachments[].url" absolute URL in
|
|
253
|
+
"src" or "poster". For a single final message that both attaches files and
|
|
254
|
+
embeds them, use a two-step flow: create or target the message with the
|
|
255
|
+
attachments, then edit the same message body with directives that reference
|
|
256
|
+
the returned absolute URLs. When upload/attach returns "target_seq", use that
|
|
257
|
+
value as target.message_seq in linzumi_edit_message for the follow-up
|
|
258
|
+
body-only edit; the returned "message" is the edit event that carries the new
|
|
259
|
+
attachment URLs, and "target_message" is the original target.
|
|
260
|
+
- If you do not yet have a returned absolute attachment URL, mention the file as
|
|
261
|
+
an attachment instead of writing a media directive.
|
|
262
|
+
</media_rules>
|
|
263
|
+
|
|
264
|
+
<media_examples>
|
|
265
|
+
Audio examples:
|
|
266
|
+
|
|
267
|
+
GOOD:
|
|
268
|
+
::audio[Temple bell]{src="https://serve.linzumi.com/api/v2/workspaces/linzumi/channels/general/files/file-123/download?share_token=token" caption="Completion cue used in the demo." meta="MP3, 12s" source="Generated by the agent"}
|
|
269
|
+
Why good: It uses the audio directive, includes the required Linzumi attachment download URL in "src", and keeps optional descriptive fields short.
|
|
270
|
+
|
|
271
|
+
GOOD:
|
|
272
|
+
| Sound | Use | Player |
|
|
273
|
+
| --- | --- | --- |
|
|
274
|
+
| Alert chime | Error state cue | ::audio[Alert chime]{src="https://serve.linzumi.com/api/v2/workspaces/linzumi/channels/general/files/file-124/download?share_token=token" caption="Short, dry chime." meta="WAV, 3s"} |
|
|
275
|
+
Why good: It shows that audio embeds compose inside Markdown tables while still using a trusted Linzumi attachment URL.
|
|
276
|
+
|
|
277
|
+
BAD:
|
|
278
|
+
::audio[Temple bell]{src="/files/temple-bell.mp3" caption="Root-relative URLs are not allowed."}
|
|
279
|
+
Why bad: A root-relative path is not a full returned attachment URL and will not be auto-rendered.
|
|
280
|
+
|
|
281
|
+
BAD:
|
|
282
|
+
::audio[Alert chime]{src="https://cdn.example.com/audio/alert-chime.wav" caption="External CDN media should not auto-render."}
|
|
283
|
+
Why bad: Third-party media URLs can create unwanted automatic fetches for many viewers; link to external sources with ordinary Markdown instead.
|
|
284
|
+
|
|
285
|
+
Video examples:
|
|
286
|
+
|
|
287
|
+
GOOD:
|
|
288
|
+
::video[Flow recording]{src="https://serve.linzumi.com/api/v2/workspaces/linzumi/channels/general/files/file-456/download?share_token=token" caption="Composer flow with media playback." meta="WebM, 44s" poster="https://serve.linzumi.com/api/v2/workspaces/linzumi/channels/general/files/file-789/download?share_token=token"}
|
|
289
|
+
Why good: Both "src" and the optional "poster" point to returned Linzumi attachment download URLs.
|
|
290
|
+
|
|
291
|
+
GOOD:
|
|
292
|
+
| Clip | Notes | Player |
|
|
293
|
+
| --- | --- | --- |
|
|
294
|
+
| Routing demo | Shows the happy path | ::video[Routing demo]{src="https://serve.linzumi.com/api/v2/workspaces/linzumi/channels/general/files/file-457/download?share_token=token" caption="Screen recording of routing." meta="MP4, 1080p"} |
|
|
295
|
+
Why good: It omits "poster", which is allowed, and keeps the video playable inside a table using the required Linzumi URL shape.
|
|
296
|
+
|
|
297
|
+
BAD:
|
|
298
|
+
::video[Flow recording]{src="file:///tmp/flow.webm" caption="file:// URLs are not accessible in Linzumi."}
|
|
299
|
+
Why bad: "file://" URLs point at the agent's machine, not the user's Linzumi attachment, so the renderer will leave the syntax inert.
|
|
300
|
+
|
|
301
|
+
BAD:
|
|
302
|
+
::video[Flow recording]{src="https://uploads.example.com/presigned-put-url" caption="Do not use temporary upload URLs; use the returned Linzumi download URL."}
|
|
303
|
+
Why bad: Upload or object-store URLs are not stable returned Linzumi download URLs and can expire or expose the wrong transport seam.
|
|
304
|
+
|
|
305
|
+
Image examples:
|
|
306
|
+
|
|
307
|
+
GOOD:
|
|
308
|
+
::image[Final UI]{src="https://serve.linzumi.com/api/v2/workspaces/linzumi/channels/general/files/file-abc/download?share_token=token" caption="Final media comparison table." meta="PNG, desktop viewport" source="Playwright screenshot"}
|
|
309
|
+
Why good: It uses the image directive with the required "src" and useful optional caption, meta, and source fields.
|
|
310
|
+
|
|
311
|
+
GOOD:
|
|
312
|
+

|
|
313
|
+
Why good: Markdown image syntax is supported when the URL is the returned Linzumi attachment download URL.
|
|
314
|
+
|
|
315
|
+
BAD:
|
|
316
|
+
::image[Final UI]{src="./artifacts/final.png" caption="Relative paths are not accessible to the user."}
|
|
317
|
+
Why bad: Relative paths describe local workspace files, not uploaded attachments that Linzumi can render for the viewer.
|
|
318
|
+
|
|
319
|
+
BAD:
|
|
320
|
+

|
|
321
|
+
Why bad: External image hosts are intentionally not auto-rendered; attach the image first, then use the returned Linzumi URL.
|
|
322
|
+
</media_examples>
|
|
323
|
+
|
|
324
|
+
<media_reminder>
|
|
325
|
+
Use media directives only after upload/attach returns a Linzumi download URL.
|
|
326
|
+
Keep "src" required, all other fields optional, and never exceed 10 embeds in one message.
|
|
327
|
+
</media_reminder>
|
|
328
|
+
</linzumi_markdown_media_guidance>`;var V_=64;function tE(e){switch(e){case"all":return!0;case"coding":case"onboarding-discovery":return!1}}function rE(e){switch(e){case"voice":return!0;case"text":return!1}}function nE(e){return e.trim().replace(/^:+/,"").replace(/:+$/,"").toLowerCase()}var B_=m.string().min(1).refine(e=>nE(e).length<=V_,{message:`Custom emoji shortcode name must be at most ${V_} characters after trimming surrounding colons.`}),oE=new Map([["api-url",{kind:"value"}],["token",{kind:"value"}],["auth-file",{kind:"value"}],["delegation-auth-file",{kind:"value"}],["workspace",{kind:"value"}],["channel",{kind:"value"}],["owner-username",{kind:"value"}],["mode",{kind:"value"}],["cwd",{kind:"value"}],["thread-id",{kind:"value"}],["format",{kind:"value"}],["command",{kind:"value"}],["tool-scope",{kind:"value"}],["agent-session",{kind:"boolean"}],["include-token",{kind:"boolean"}],["help",{kind:"boolean"}]]);async function Q_(e){let[t,...r]=e;switch(t){case void 0:case"--help":case"-h":process.stdout.write(ev());return;case"server":await sE(r);return;case"config":await hE(r);return;case"doctor":await gE(r);return;default:throw new Error(`unknown linzumi mcp command: ${t}`)}}function ev(){return`Linzumi MCP
|
|
329
|
+
|
|
330
|
+
Usage:
|
|
331
|
+
linzumi mcp server --api-url <url> [--mode voice|text] [--workspace <slug> --channel <slug>]
|
|
332
|
+
linzumi mcp server --api-url <url> --delegation-auth-file <path> [--mode voice|text]
|
|
333
|
+
linzumi mcp config --api-url <url> --format codex|claude-code [--include-token]
|
|
334
|
+
linzumi mcp doctor --api-url <url> [--workspace <slug> --channel <slug>]
|
|
335
|
+
|
|
336
|
+
Tools:
|
|
337
|
+
linzumi_get_message Read one message by scoped seq or Linzumi message URL.
|
|
338
|
+
linzumi_get_thread Read one bounded thread by ID.
|
|
339
|
+
linzumi_get_thread_transcript
|
|
340
|
+
Read a thread's FULL transcript (tool calls, commands,
|
|
341
|
+
diffs) as canonical IR nodes, cursor-paginated.
|
|
342
|
+
linzumi_get_channel Read bounded recent messages and channel metadata.
|
|
343
|
+
linzumi_web_search Search the public web (news, docs, live info).
|
|
344
|
+
linzumi_fetch_url Fetch a public http(s) URL as readable text.
|
|
345
|
+
linzumi_list_ui_targets
|
|
346
|
+
List UI surfaces the user can be asked to open.
|
|
347
|
+
linzumi_open_ui Ask the user (consent toast) to open one UI surface
|
|
348
|
+
in their own Linzumi window.
|
|
349
|
+
linzumi_get_coding_job_metadata
|
|
350
|
+
Read the current coding job goal, plan, and workflow metadata.
|
|
351
|
+
linzumi_rename_coding_job
|
|
352
|
+
Update the coding job thread and workflow-facing title.
|
|
353
|
+
linzumi_upsert_coding_job_plan
|
|
354
|
+
Set or update the coding job goal.
|
|
355
|
+
linzumi_replace_coding_job_plan_steps
|
|
356
|
+
Replace the ordered coding job plan steps.
|
|
357
|
+
linzumi_update_coding_job_plan_step
|
|
358
|
+
Update one coding job plan step status or note.
|
|
359
|
+
linzumi_link_coding_job_pull_request
|
|
360
|
+
Link the coding job to its primary GitHub pull request.
|
|
361
|
+
linzumi_list_vault_secrets
|
|
362
|
+
List vault secret names, descriptions, and owner scope.
|
|
363
|
+
linzumi_list_projects
|
|
364
|
+
List workspace projects with their project ids.
|
|
365
|
+
linzumi_get_project_tasks
|
|
366
|
+
Read a project's task graph: groups, issues, statuses,
|
|
367
|
+
derived readiness, and dependency edges.
|
|
368
|
+
linzumi_create_project_task
|
|
369
|
+
Create a task group or issue in a project.
|
|
370
|
+
linzumi_update_project_task
|
|
371
|
+
Update, transition, reassign, or reorganize a task.
|
|
372
|
+
linzumi_delete_project_task
|
|
373
|
+
Permanently delete a task group or issue.
|
|
374
|
+
linzumi_add_project_task_dependency
|
|
375
|
+
Add a blocked-by edge between two issues (acyclic).
|
|
376
|
+
linzumi_remove_project_task_dependency
|
|
377
|
+
Remove a blocked-by edge between two issues.
|
|
378
|
+
linzumi_get_call_transcript
|
|
379
|
+
Read a completed notetaker call's full transcript.
|
|
380
|
+
linzumi_start_coding_job
|
|
381
|
+
Start a coding job (a project-bound job starts ready
|
|
382
|
+
task items with project_task_id, only after the user
|
|
383
|
+
accepts the offer).
|
|
384
|
+
linzumi_note_project_directory
|
|
385
|
+
Record one discovered local Git project directory.
|
|
386
|
+
linzumi_note_agent_conversation
|
|
387
|
+
Record one discovered Codex or Claude Code conversation.
|
|
388
|
+
linzumi_note_onboarding_discovery_status
|
|
389
|
+
Record onboarding discovery progress or failure.
|
|
390
|
+
linzumi_send_channel_message
|
|
391
|
+
Post a NEW standalone message to the scoped channel
|
|
392
|
+
(not how you reply to the current request).
|
|
393
|
+
linzumi_send_thread_reply
|
|
394
|
+
Post a reply into some OTHER existing thread
|
|
395
|
+
(not how you reply to the current request).
|
|
396
|
+
linzumi_send_dm Send a plain-text DM to a visible user.
|
|
397
|
+
linzumi_dm_owner Send a plain-text DM to the configured owner username.
|
|
398
|
+
linzumi_get_vault_values
|
|
399
|
+
Request approved named vault values for a thread.
|
|
400
|
+
linzumi_upload_files
|
|
401
|
+
Attach generated files and return absolute file URLs
|
|
402
|
+
suitable for Markdown media src/poster attributes.
|
|
403
|
+
linzumi_upload_custom_emoji
|
|
404
|
+
Upload a local image as a workspace custom emoji.
|
|
405
|
+
linzumi_rename_custom_emoji
|
|
406
|
+
Rename an existing workspace custom emoji.
|
|
407
|
+
linzumi_dev_service_start
|
|
408
|
+
Start (or declaratively restart) a named managed dev
|
|
409
|
+
service owned by the runner's dev-service registry.
|
|
410
|
+
linzumi_dev_service_stop
|
|
411
|
+
Stop a managed dev service.
|
|
412
|
+
linzumi_dev_service_status
|
|
413
|
+
List managed dev services with liveness + port health.
|
|
414
|
+
linzumi_dev_service_logs
|
|
415
|
+
Read the tail of a managed dev service's log.
|
|
416
|
+
linzumi_dev_service_remove
|
|
417
|
+
Stop a managed dev service and delete its registration.
|
|
418
|
+
|
|
419
|
+
Auth:
|
|
420
|
+
Uses --token, LINZUMI_MCP_ACCESS_TOKEN, or cached local runner OAuth from linzumi auth.
|
|
421
|
+
Hosted personal agents use --delegation-auth-file with a signed delegation grant.
|
|
422
|
+
`}async function sE(e){let t=Cl(e);if(t.get("help")===!0){process.stdout.write(ev());return}let r=Ml(t,"api-url"),n=await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")}),o=re(t,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,s=Al(re(t,"mode")),i=tv(re(t,"tool-scope")),a=re(t,"cwd")??process.cwd(),c=re(t,"thread-id")??process.env.LINZUMI_THREAD_RUNNER_KANDAN_THREAD_ID,u=xl({kandanUrl:r,accessToken:n.accessToken,authMode:n.mode,operatingMode:s}),d=new bi({name:"linzumi",version:"0.1.0"});fE(d),aE(d,{client:u,toolScope:i,operatingMode:s,cwd:a,kandanUrl:r,defaultThreadId:c,ownerUsername:o,agentSession:t.get("agent-session")===!0,devServices:iE(process.env)}),await d.connect(new ki)}function iE(e){let t=e.LINZUMI_DEV_SERVICES_SCOPE?.trim(),r=Number.parseInt(e.LINZUMI_DEV_SERVICES_OWNER_PID??"",10);if(!(t===void 0||t===""||!Number.isInteger(r)||r<=0))return{scopeDir:O_(t),ownerPid:r}}function aE(e,t){let{client:r,toolScope:n,operatingMode:o,cwd:s,kandanUrl:i,defaultThreadId:a,ownerUsername:c,agentSession:u,devServices:d}=t,l=n==="all"||n==="coding";u&&(e.tool("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.",{body:m.string().min(1).describe("Plain-text reply body to post.")},async p=>E(await r.agentReply({body:p.body}))),e.tool("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()=>E(await r.agentListCodingJobs({}))),e.tool("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).",{channel:m.string().describe("Channel slug to host the job thread."),runner_key:m.string().describe("Runner (computer) to run the job on."),cwd:m.string().describe("Working directory on the runner."),work_description:m.string().min(1).describe("What the job should do - the initial instruction."),model:m.string().optional().describe("Model override (optional)."),model_provider:m.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),execution_mode:m.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional)."),project_task_id:m.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.")},async p=>E(await r.agentStartCodingJob(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),mode:m.enum(["steer","stop"]).optional().describe("Interrupt mode; defaults to 'steer'.")},async p=>E(await r.agentInterruptCodingJob(p))),e.tool("linzumi_send_coding_job_message","Send a message into a coding job thread as the asking user (the job processes it like any human follow-up).",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),body:m.string().min(1).describe("Message body to send.")},async p=>E(await r.agentSendCodingJobMessage(p))),e.tool("linzumi_read_coding_job_thread","Read a coding job's thread (asker-visible history) plus its workflow status metadata.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),limit:m.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:m.number().int().positive().optional().describe("Return replies before this channel seq.")},async p=>E(await r.agentReadCodingJobThread(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),source_seq:m.number().int().positive().describe("Channel seq of the message the approval request rides on."),request_id:m.string().describe("The approval request id."),decision:m.enum(["approve","deny"]).describe("The asker's decision.")},async p=>E(await r.agentResolveJobApproval(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID to archive.")},async p=>E(await r.agentArchiveCodingJob(p))),e.tool("linzumi_unarchive_coding_job","Unarchive a previously archived coding job thread the asking user owns, returning it to the active list.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID to unarchive.")},async p=>E(await r.agentUnarchiveCodingJob(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID."),status:m.enum(["open","closed"]).describe("Replacement lifecycle status ('closed' = done).")},async p=>E(await r.agentSetThreadStatus(p))),e.tool("linzumi_create_channel","Create a new public channel in this workspace as the asking user. The slug is derived from the name.",{name:m.string().min(1).describe("Channel name to create.")},async p=>E(await r.agentCreateChannel(p))),e.tool("linzumi_rename_channel","Rename a channel's display name as the asking user. The channel's URL slug stays stable.",{channel:m.string().describe("Current channel slug to rename."),name:m.string().min(1).describe("New display name.")},async p=>E(await r.agentRenameChannel(p))),e.tool("linzumi_archive_channel","Archive a channel in this workspace as the asking user. History is preserved; the channel leaves the active sidebar.",{channel:m.string().describe("Channel slug to archive.")},async p=>E(await r.agentArchiveChannel(p))),e.tool("linzumi_unarchive_channel","Unarchive a previously archived channel as the asking user.",{channel:m.string().describe("Channel slug to unarchive.")},async p=>E(await r.agentUnarchiveChannel(p))),e.tool("linzumi_add_reaction","Add an emoji reaction to a channel message as the asking user. Accepts unicode emoji or a workspace :shortcode:.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the message to react to."),emoji:m.string().min(1).describe("Emoji to add (unicode or :shortcode:).")},async p=>E(await r.agentAddReaction(p))),e.tool("linzumi_remove_reaction","Remove the asking user's emoji reaction from a channel message.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the reacted message."),emoji:m.string().min(1).describe("Emoji to remove (unicode or :shortcode:).")},async p=>E(await r.agentRemoveReaction(p))),e.tool("linzumi_pin_message","Pin a channel message as the asking user. Thread replies re-point to their root message.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the message to pin.")},async p=>E(await r.agentPinMessage(p))),e.tool("linzumi_unpin_message","Remove a pin from a channel message as the asking user.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the pinned message.")},async p=>E(await r.agentUnpinMessage(p)))),n==="all"&&(e.tool("linzumi_get_message","Read one Linzumi message by scoped message_seq/message_id or a Linzumi message URL, with optional bounded before/after context.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),message_id:m.union([m.string(),m.number()]).optional().describe("Message seq inside the scoped channel."),message_seq:m.union([m.string(),m.number()]).optional().describe("Alias for message_id."),message_url:m.string().optional().describe("Full Linzumi message URL with #message-<seq>."),before:m.number().int().min(0).max(100).optional().describe("Number of visible messages before the target."),after:m.number().int().min(0).max(100).optional().describe("Number of visible messages after the target.")},async p=>E(await r.getMessage(p))),e.tool("linzumi_get_thread","Read one Linzumi thread by thread_id in the scoped channel, including the parent message and bounded replies.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Linzumi thread UUID."),limit:m.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:m.number().int().positive().optional().describe("Return replies before this channel seq.")},async p=>E(await r.getThread(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Linzumi thread UUID."),limit:m.number().int().min(1).max(500).optional().describe("Maximum transcript nodes per page (default 200)."),cursor:m.number().int().positive().optional().describe("Return nodes below this seq (the previous page reply cursor).")},async p=>E(await r.getThreadTranscript(p))),e.tool("linzumi_get_channel","Read scoped Linzumi channel metadata and bounded recent channel messages.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),limit:m.number().int().min(1).max(100).optional().describe("Maximum messages to return."),before_seq:m.number().int().positive().optional().describe("Return messages before this channel seq.")},async p=>E(await r.getChannel(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),query:m.string().min(1).describe("Natural-language or keyword query to retrieve against."),limit:m.number().int().min(1).max(25).optional().describe("Maximum results to return (default 10, server-capped)."),source_types:m.array(m.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:m.string().optional().describe("ISO8601 instant; only content authored at or after this time."),authored_before:m.string().optional().describe("ISO8601 instant; only content authored at or before this time."),repo:m.string().optional().describe("Restrict GitHub-sourced results to one repository by full name (owner/name)."),check_status:m.enum(["pending","success","failed"]).optional().describe("Restrict check and workflow results to one conclusion bucket.")},async p=>E(await r.searchWorkspace(p))),e.tool("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.',{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),question:m.string().min(1).max(2e3).describe("Natural-language question to answer with citations."),channel:m.string().optional().describe("Optional channel slug providing conversational context; never widens access."),allow_cached:m.boolean().optional().describe("Allow serving a cached synthesis when the evidence set is unchanged (default true). Set false to force fresh synthesis.")},async p=>E(await r.askWorkspace(p))),e.tool("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 p=>E(await r.aboutMe(p)))),l&&(e.tool("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.",{query:m.string().min(1).describe("Web search query (natural language or keywords)."),limit:m.number().int().min(1).max(10).optional().describe("Maximum results to return (default 8, server-capped).")},async p=>E(await r.webSearch(p))),e.tool("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.",{url:m.string().min(1).describe("Absolute public http(s) URL to fetch.")},async p=>E(await r.fetchUrl(p)))),n==="all"&&(e.tool("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()=>await X_(r.listUiTargets({}))),e.tool("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.",{kind:m.string().min(1).describe("Target kind from linzumi_list_ui_targets (e.g. settings_workspace, channel, pane_layout)."),args:m.record(m.unknown()).optional().describe("Structured per-kind args from linzumi_list_ui_targets (never a URL - the server computes every path)."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>await X_(r.openUi(Pt(p,a))))),l&&(e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread.")},async p=>E(await r.getCodingJobMetadata(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),title:m.string().min(1).max(100).describe("Concise user-visible title for this coding job.")},async p=>E(await r.renameCodingJob(Pt(p,a)))),e.tool("linzumi_upsert_coding_job_plan","Set or update the current coding job goal. Use this at job start and whenever the goal changes materially.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:m.string().min(1).max(1e4).describe("Concrete user-visible goal for this coding job.")},async p=>E(await r.upsertCodingJobPlan(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:m.string().min(1).max(1e4).optional().describe("Required when no plan exists yet; updates the current coding job goal."),steps:m.array(m.object({title:m.string().min(1).max(255),description:m.string().min(1).max(1e4),status:m.enum(["pending","active","completed","blocked","canceled"]),status_note:m.string().min(1).max(4e3).optional(),completed_debrief:m.string().min(1).max(2e4).optional()})).min(1).max(50).describe("Ordered user-visible plan steps. Completed steps must include completed_debrief.")},async p=>E(await r.replaceCodingJobPlanSteps(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),step_id:m.string().uuid().describe("Step id returned by linzumi_get_coding_job_metadata."),lock_version:m.number().int().positive().describe("Current step lock_version from metadata."),status:m.enum(["pending","active","completed","blocked","canceled"]),status_note:m.string().min(1).max(4e3).optional(),completed_debrief:m.string().min(1).max(2e4).optional().describe("Required when marking a step completed.")},async p=>E(await r.updateCodingJobPlanStep(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),github_repo_owner:m.string().min(1).max(255),github_repo_name:m.string().min(1).max(255),github_pr_number:m.number().int().positive(),github_pr_url:m.string().url(),title:m.string().min(1).max(255),body:m.string().min(1).max(1e5).optional(),head_branch:m.string().min(1).max(255),head_sha:m.string().min(7).max(64),base_branch:m.string().min(1).max(255),base_sha:m.string().min(7).max(64),state:m.enum(["draft","open","closed","merged"]).optional(),is_draft:m.boolean().optional(),review_status:m.enum(["unknown","review_required","approved","changes_requested"]).optional(),source_remote_url:m.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:m.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:m.enum(["unknown","clean","dirty"]).optional(),dirty_summary:m.string().min(1).max(2e3).optional()},async p=>E(await r.linkCodingJobPullRequest(Pt(p,a)))),e.tool("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(" "),{target:m.object({kind:m.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:m.union([m.string(),m.number()]).optional().describe("Required when kind is message_seq."),thread_id:m.string().optional().describe("Thread UUID. Defaults to the active Linzumi thread when the MCP server was launched with one.")}).describe("Attachment target. Do not guess; use new_message when there is no previous assistant message. 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:m.array(m.string().min(1)).min(1).max(16).describe("Local file paths to upload. Paths must be non-hidden supported file types inside the approved workspace or Downloads."),body:m.string().min(1).max(2e4).optional().describe("Required for new_message. 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:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the target thread's channel (when the thread is known) or the authenticated token scope.")},async p=>{let h=W_(p.target,a);try{let f=await dE({client:r,cwd:s,kandanUrl:i,target:h,files:p.files,workspace:p.workspace,channel:p.channel,body:p.body});return E(G_(i,f))}catch(f){throw uE(f)}}),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),target:m.object({message_seq:m.union([m.string(),m.number()]).describe("Exact message seq to edit. After linzumi_upload_files returns target_seq, pass that value here."),thread_id:m.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:m.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 p=>E(G_(i,await r.editMessage({...p,target:W_(p.target,a)}))))),n==="all"&&(e.tool("linzumi_list_vault_secrets","List vault secret names, descriptions, and whether each secret is personal or workspace-owned. Does not return secret values.",{},async p=>E(await r.listVaultSecrets(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await r.listProjects(p))),e.tool("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.`,{project_id:m.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")},async p=>E(await r.getProjectTasks(Pt(p,a)))),e.tool("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.',{project_id:m.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project."),title:m.string().min(1).describe("Task title."),kind:m.enum(["issue","group"]).optional().describe('What to create: "issue" (executable work item, default) or "group" (organizational container).'),description:m.string().optional().describe("Detailed description of the work - written so an engineer (or coding agent) could execute the task from it."),status:m.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('Initial status. Defaults to "todo".'),parent_id:m.string().optional().describe("task_id of the GROUP to place an issue in. Only issues can have a parent."),assignee:m.string().optional().describe("Username of a workspace member to assign."),position:m.number().int().min(0).optional().describe("Sort position. Defaults to appending at the end.")},async p=>E(await r.createProjectTask(Pt(p,a)))),e.tool("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.',{task_id:m.string().describe("task_id of the group or issue to update."),title:m.string().min(1).optional().describe("New title."),description:m.string().nullable().optional().describe("New description. Pass null to clear it."),status:m.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('New status. "done"/"canceled" satisfy dependent tasks; "blocked" is a manual hold.'),status_note:m.string().nullable().optional().describe("Short human-readable note about the current status. Pass null to clear it."),position:m.number().int().min(0).optional().describe("New sort position among siblings."),parent_id:m.string().optional().describe("task_id of the GROUP to move this issue into. Do not combine with clear_parent."),clear_parent:m.boolean().optional().describe("true moves the issue to the top level (no group). Do not combine with parent_id."),assignee:m.string().optional().describe("Username of a workspace member to assign. Do not combine with clear_assignee."),clear_assignee:m.boolean().optional().describe("true removes the assignee. Do not combine with assignee."),lock_version:m.number().int().positive().optional().describe("The task's lock_version from your last read, for compare-and-swap safety.")},async p=>E(await r.updateProjectTask(p))),e.tool("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.`,{task_id:m.string().describe("task_id of the group or issue to delete.")},async p=>E(await r.deleteProjectTask(p))),e.tool("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.',{task_id:m.string().describe("task_id of the DEPENDENT issue (the one that must wait)."),depends_on_task_id:m.string().describe("task_id of the PREREQUISITE issue (the one that must finish first).")},async p=>E(await r.addProjectTaskDependency(p))),e.tool("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.',{task_id:m.string().describe("task_id of the DEPENDENT issue."),depends_on_task_id:m.string().describe("task_id of the PREREQUISITE issue the edge points at.")},async p=>E(await r.removeProjectTaskDependency(p))),e.tool("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).",{call_id:m.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 p=>E(await r.getCallTranscript(p))),u||e.tool("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).",{work_description:m.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:m.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."),channel:m.string().optional().describe("Channel slug to host the job thread. Omit to use this job's own channel."),runner_key:m.string().optional().describe("Runner (computer) to run the job on. Omit to use this job's own computer."),cwd:m.string().optional().describe("Working directory on the runner. Omit to use this job's own folder."),model:m.string().optional().describe("Model override (optional)."),model_provider:m.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),execution_mode:m.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional).")},async p=>E(await r.agentStartCodingJob(Pt(p,a))))),tE(n)&&(e.tool("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:.",{name:B_.describe("Custom emoji shortcode name, with or without surrounding colons."),file:m.string().min(1).describe("Local PNG/WebP/GIF/JPEG file path to upload. Prefer transparent PNG for generated emoji."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await lE({client:r,cwd:s,kandanUrl:i,name:p.name,file:p.file,workspace:p.workspace}))),e.tool("linzumi_rename_custom_emoji","Rename an existing workspace custom emoji. The new name may include surrounding colons; Linzumi stores the normalized shortcode without colons.",{emoji_id:m.union([m.string(),m.number().int().positive()]).describe("Workspace custom emoji id returned by linzumi_upload_custom_emoji or workspace emoji listings."),name:B_.describe("New shortcode name, with or without surrounding colons."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await r.renameCustomEmoji(p)))),e.tool("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()=>({content:[{type:"text",text:F_}]})),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),path:m.string().min(1).describe("Absolute local path to the repository worktree root."),display_name:m.string().optional().describe("Short project label. Defaults to the path basename."),activity_at:m.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),import_key:m.string().optional().describe("Stable dedupe key. Defaults to path."),metadata:m.record(m.unknown()).optional().describe("Small structured metadata such as branch or remote origin.")},async p=>E(await r.noteProjectDirectory(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),source:m.enum(["codex","claude_code"]).describe("Conversation source."),import_key:m.string().min(1).describe("Stable dedupe key, such as a session id or file path."),path:m.string().optional().describe("Absolute local path to the conversation file or directory."),display_name:m.string().optional().describe("Short label for the discovered conversation."),activity_at:m.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),metadata:m.record(m.unknown()).optional().describe("Small structured metadata such as session id or project path.")},async p=>E(await r.noteAgentConversation(p))),e.tool("linzumi_note_onboarding_discovery_status","Record onboarding discovery progress. Call when a search phase starts, checks another place, completes, or fails.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),phase:m.enum(["projects","conversations"]).describe("Discovery phase being reported."),status:m.enum(["starting","running","completed","failed"]).describe("Current phase status."),places_searched:m.number().int().nonnegative().optional().describe("Count of concrete folders/files/known locations checked so far."),message:m.string().optional().describe("Short user-facing status note."),current_place:m.string().optional().describe("Current folder, file, Git command target, or known location being checked."),current_source:m.string().optional().describe("Short machine-readable source label such as git, codex, or claude_code."),last_error:m.string().optional().describe("Short failure detail when status is failed."),metadata:m.record(m.unknown()).optional().describe("Small structured status metadata.")},async p=>E(await r.noteOnboardingDiscoveryStatus(p))),n==="all"&&rE(o)&&(e.tool("linzumi_dm_owner","Send a plain-text DM to the configured Commander owner. Requires dm.write and a visible owner username.",{owner_username:m.string().optional().describe("Owner username. Defaults to LINZUMI_MCP_OWNER_USERNAME or --owner-username."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Source channel slug used to verify owner visibility."),body:m.string().min(1).max(2e4).describe("Plain-text message body to DM.")},async p=>{let h=p.owner_username??c;if(h===void 0)throw new Error("owner_username is required for linzumi_dm_owner");return E(await r.dmOwner({...p,owner_username:h}))}),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),body:m.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 p=>E(await r.sendChannelMessage(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Existing Linzumi thread UUID."),body:m.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 p=>E(await r.sendThreadReply(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Source channel slug used to verify target visibility."),username:m.string().describe("Visible Linzumi username to DM."),body:m.string().min(1).max(2e4).describe("Plain-text message body to DM.")},async p=>E(await r.sendDm(p)))),n==="all"&&e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug used to disambiguate the approval thread when needed."),thread_id:m.string().uuid().describe("Existing Linzumi thread UUID for the inline approval."),env_var_names:m.array(m.string().regex(/^[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:m.string().min(1).max(500).describe("Human-readable reason shown in the approval request."),justification:m.string().min(10).max(1e3).describe("Agent justification shown to the approver.")},async p=>E(await r.getVaultValues(p))),n==="all"&&!u&&d!==void 0&&cE(e,s,d)}function H_(e){return{name:e.record.name,command:e.record.command,cwd:e.record.cwd,ports:[...e.record.ports],restart_on_branch_change:e.record.restartOnBranchChange,desired_state:e.record.desiredState,liveness:e.liveness,port_health:e.portProbes.map(t=>({port:t.port,listening:t.listening})),started_at_ms:e.record.startedAtMs??null,last_exit:e.lastExit===void 0?null:{code:e.lastExit.code,signal:e.lastExit.signal,at_ms:e.lastExit.atMs},log_path:e.record.logPath}}function cE(e,t,r){e.tool("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).",{name:m.string().regex(/^[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:m.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:m.string().optional().describe("Working directory for the service. Defaults to the session cwd."),ports:m.array(m.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:m.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:m.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 o=await N_({scopeDir:r.scopeDir,definition:{name:n.name,command:n.command,cwd:n.cwd??t,ports:n.ports,restartOnBranchChange:n.restart_on_branch_change===!0},ownerPid:r.ownerPid});if(!o.ok)return E({ok:!1,error:o.error});let s=Date.now()+(n.wait_for_ports_ms??15e3),i=o.record.ports.length===0;for(;!i&&Date.now()<s;)i=(await Promise.all(o.record.ports.map(d=>El(d)))).every(d=>d),i||await new Promise(d=>setTimeout(d,250));let c=(await Il(r.scopeDir)).find(u=>u.record.name===o.record.name);return E({ok:!0,service:c===void 0?{name:o.record.name}:H_(c),...c!==void 0&&c.liveness!=="running"?{hint:"The service is not (fully) serving its declared ports yet. Check linzumi_dev_service_logs before assuming it works."}:{}})}),e.tool("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.",{name:m.string().min(1).describe("Service name to stop.")},async n=>{let o=await Ol({scopeDir:r.scopeDir,name:n.name});return E(o.ok?{ok:!0,name:o.record.name,desired_state:"stopped"}:{ok:!1,error:o.error})}),e.tool("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()=>{let n=await Il(r.scopeDir);return E({services:n.map(o=>H_(o))})}),e.tool("linzumi_dev_service_logs","Read the tail of a managed dev service's combined stdout/stderr log.",{name:m.string().min(1).describe("Service name."),max_bytes:m.number().int().min(256).max(65536).optional().describe("Tail size in bytes (default 16384).")},async n=>{let o=Z_(r.scopeDir,n.name,n.max_bytes??16384);return E(o===void 0?{ok:!1,error:`no log for service: ${n.name}`}:{ok:!0,name:n.name,log_tail:o})}),e.tool("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.",{name:m.string().min(1).describe("Service name to remove.")},async n=>{let o=await D_({scopeDir:r.scopeDir,name:n.name});return E(o.ok?{ok:!0,name:o.record.name,removed:!0}:{ok:!1,error:o.error})})}function uE(e){return!(e instanceof Error)||!e.message.includes("channel_required")?e:new Error(`${e.message}. 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:e})}async function dE(e){let t=await Promise.all(e.files.map(i=>kl(e.cwd,i))),r=we(e.target.thread_id),n=await e.client.prepareMessageUploads({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...r===void 0?{}:{thread_id:r},files:t.map(i=>({file_name:i.fileName,content_type:i.contentType,size_bytes:i.sizeBytes}))}),o=$i(n.uploads)??[];if(o.length!==t.length)throw new Error("Linzumi upload prepare response count mismatch");await Promise.all(t.map(async(i,a)=>{let c=zt(o[a]),u=we(c?.upload_url),d=we(c?.upload_method)??"PUT";if(u===void 0)throw new Error("Linzumi upload prepare response missing upload_url");let l=await Y_(i.path),p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength),h=await fetch(Ao(e.kandanUrl,u),{method:d,headers:{"content-type":i.contentType},body:p});if(!h.ok)throw new Error(`Linzumi upload failed for ${i.fileName}: ${h.status} ${h.statusText}`)}));let s=o.map(i=>{let a=we(zt(i)?.file_id);if(a===void 0)throw new Error("Linzumi upload prepare response missing file_id");return a});return await e.client.attachMessageFiles({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...r===void 0?{}:{thread_id:r},target:e.target,...e.body===void 0?{}:{body:e.body},uploaded_file_ids:s})}async function lE(e){let t=await kl(e.cwd,e.file),r=await e.client.prepareCustomEmoji({...e.workspace===void 0?{}:{workspace:e.workspace},name:e.name,file_name:t.fileName,content_type:t.contentType,size_bytes:t.sizeBytes}),n=zt(r.upload),o=we(n?.upload_url),s=we(n?.upload_method)??"PUT";if(o===void 0)throw new Error("Linzumi custom emoji prepare response missing upload_url");let i=await Y_(t.path),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),c=await fetch(Ao(e.kandanUrl,o),{method:s,headers:{"content-type":t.contentType},body:a});if(!c.ok){let l=`${c.status} ${c.statusText}`,h=(await c.text()).trim(),f=h===""?l:(()=>{try{let g=JSON.parse(h);return ft(g)&&typeof g.error=="string"?g.error:h}catch{return h}})();throw new Error(`Linzumi custom emoji upload failed: ${f}`)}let u=await c.json();if(!ft(u))throw new Error("Linzumi custom emoji upload returned non-object JSON");let d=zt(u.custom_emoji);if(d===void 0)throw new Error("Linzumi custom emoji upload response missing custom_emoji");return{ok:!0,workspace:r.workspace,emoji:d,asset_id:we(u.asset_id),id:x_(d?.id),name:we(d?.name),shortcode:we(d?.shortcode),image_url:we(d?.image_url)}}function W_(e,t){if(we(e.thread_id)!==void 0||t===void 0)return e;switch(e.message_seq===void 0){case!1:return{...e,thread_id:t};case!0:switch(we(e.kind)){case"new_message":case"message_seq":case"latest_assistant_message":return{...e,thread_id:t};default:return e}}}function Pt(e,t){return we(e.thread_id)!==void 0||t===void 0?e:{...e,thread_id:t}}function Ao(e,t){try{return new URL(t).toString()}catch{let n=e.replace(/^wss:\/\//,"https://").replace(/^ws:\/\//,"http://");return new URL(t,n).toString()}}function G_(e,t){let r=zt(t.message),n=zt(t.target_message);return r===void 0&&n===void 0?t:{...t,...r===void 0?{}:{message:K_(e,r)},...n===void 0?{}:{target_message:K_(e,n)}}}function K_(e,t){let r=$i(t.attachments);return r===void 0?t:{...t,attachments:r.map(n=>pE(e,n))}}function pE(e,t){let r=zt(t);if(r===void 0)return t;let n=we(r.url),o=zt(r.image_variants);return{...r,...n===void 0?{}:{url:Ao(e,n)},...o===void 0?{}:{image_variants:mE(e,o)}}}function mE(e,t){let r=we(t.inline_url),n=we(t.carousel_url);return{...t,...r===void 0?{}:{inline_url:Ao(e,r)},...n===void 0?{}:{carousel_url:Ao(e,n)}}}function fE(e){e.server.registerCapabilities({resources:{listChanged:!1}}),e.server.setRequestHandler(tn,()=>({resources:[]})),e.server.setRequestHandler(rn,()=>({resourceTemplates:[]}))}async function hE(e){let t=Cl(e),r=Ml(t,"api-url"),n=re(t,"format")??"codex",o=Al(re(t,"mode")),s=t.get("include-token")===!0?(await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")})).accessToken:void 0,i=U_({command:re(t,"command"),kandanUrl:r,accessToken:s,delegationAuthFilePath:re(t,"delegation-auth-file"),ownerUsername:re(t,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,operatingMode:o,toolScope:tv(re(t,"tool-scope"))});switch(n){case"codex":process.stdout.write(J_(i));return;case"claude-code":process.stdout.write(q_(i));return;default:throw new Error("--format must be codex or claude-code")}}async function gE(e){let t=Cl(e),r=Ml(t,"api-url"),n=await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")});switch(n.mode){case"local-runner":{if(!await Vy({kandanUrl:r,accessToken:n.accessToken,workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")}))throw new Error("Linzumi MCP auth validation failed");break}case"personal-agent-delegation":{await xl({kandanUrl:r,accessToken:n.accessToken,authMode:n.mode,operatingMode:Al(re(t,"mode"))}).validateAuth();break}}process.stdout.write(`Linzumi MCP auth OK
|
|
423
|
+
`)}async function jl(e){if(e.delegationAuthFilePath!==void 0){if(e.explicitToken!==void 0||e.authFilePath!==void 0)throw new Error("--delegation-auth-file cannot be combined with --token or --auth-file");return{accessToken:Ky(e.delegationAuthFilePath).accessToken,mode:"personal-agent-delegation"}}return{accessToken:await yE({kandanUrl:e.kandanUrl,explicitToken:e.explicitToken,authFilePath:e.authFilePath,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug}),mode:"local-runner"}}async function yE(e,t={readCachedToken:Si,validateTokenOutcome:Eo,resolveToken:k_}){let r=e.explicitToken??t.readCachedToken(e.kandanUrl,e.authFilePath)?.accessToken;if(r===void 0)throw new Error("missing Linzumi MCP token; run linzumi auth or pass --token");let n=await t.validateTokenOutcome({kandanUrl:e.kandanUrl,accessToken:r,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug});if(n==="usable")return r;let o=n;try{return await t.resolveToken({kandanUrl:e.kandanUrl,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,authFilePath:e.authFilePath})}catch(s){throw new Error(`Linzumi MCP token was rejected by the server and re-mint failed: ${s instanceof Error?s.message:String(s)}`)}}function E(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}async function X_(e){try{return E(await e)}catch(t){let r=t instanceof Error?t.message:String(t),n=r.match(/failed: ([a-z0-9_]+)(?: detail=(.+))?$/);if(n===null)return E({error:r});let[,o,s]=n;return E(s===void 0?{error:o??r}:{error:o??r,detail:s})}}function Cl(e){let t=new Map;for(let r=0;r<e.length;r+=1){let n=e[r];if(n===void 0)continue;if(!n.startsWith("--"))throw new Error(`unexpected argument ${n}`);let o=n.slice(2),s=oE.get(o);if(s===void 0)throw new Error(`unsupported option --${o}`);if(s.kind==="boolean"){t.set(o,!0);continue}let i=e[r+1];if(i===void 0||i.startsWith("--"))throw new Error(`--${o} requires a value`);t.set(o,i),r+=1}return t}function re(e,t){let r=e.get(t);return typeof r=="string"&&r.trim()!==""?r:void 0}function Al(e){switch(e){case void 0:return"text";case"voice":case"text":return e;default:throw new Error("--mode must be voice or text")}}function tv(e){switch(e){case void 0:return"all";case"all":case"coding":case"onboarding-discovery":return e;default:throw new Error("--tool-scope must be all, coding, or onboarding-discovery")}}function Ml(e,t){let r=re(e,t);if(r===void 0)throw new Error(`--${t} is required`);return r}function vE(e){return e[0]==="mcp"?e.slice(1):e}async function bE(e){try{await Q_(vE(e))}catch(t){process.stderr.write(`linzumi mcp server failed: ${t instanceof Error?t.message:String(t)}
|
|
424
|
+
`),process.exitCode=1}}var wE=process.argv[1]!==void 0&&import.meta.url===_E(process.argv[1]).href;wE&&bE(process.argv.slice(2));export{vE as mcpServerEntryArgs,bE as runMcpServerEntry};
|