@sequenzy/mcp 0.0.114 → 0.0.115

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,14 +1,14 @@
1
- var Rz=Object.create;var{getPrototypeOf:kz,defineProperty:d$,getOwnPropertyNames:vz}=Object;var Cz=Object.prototype.hasOwnProperty;function xz(b){return this[b]}var uz,yz,RW=(b,w,$)=>{var W=b!=null&&typeof b==="object";if(W){var Q=w?uz??=new WeakMap:yz??=new WeakMap,G=Q.get(b);if(G)return G}$=b!=null?Rz(kz(b)):{};let X=w||!b||!b.__esModule?d$($,"default",{value:b,enumerable:!0}):$;for(let Y of vz(b))if(!Cz.call(X,Y))d$(X,Y,{get:xz.bind(b,Y),enumerable:!0});if(W)Q.set(b,X);return X};var I=(b,w)=>()=>(w||b((w={exports:{}}).exports,w),w.exports);var hz=(b)=>b;function fz(b,w){this[b]=hz.bind(null,w)}var kW=(b,w)=>{for(var $ in w)d$(b,$,{get:w[$],enumerable:!0,configurable:!0,set:fz.bind(w,$)})};var h1=I((RG)=>{Object.defineProperty(RG,"__esModule",{value:!0});RG.regexpCode=RG.getEsmExportName=RG.getProperty=RG.safeStringify=RG.stringify=RG.strConcat=RG.addCodeArg=RG.str=RG._=RG.nil=RG._Code=RG.Name=RG.IDENTIFIER=RG._CodeOrName=void 0;class d0{}RG._CodeOrName=d0;RG.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class pw extends d0{constructor(b){super();if(!RG.IDENTIFIER.test(b))throw Error("CodeGen: name must be a valid identifier");this.str=b}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}RG.Name=pw;class yb extends d0{constructor(b){super();this._items=typeof b==="string"?[b]:b}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let b=this._items[0];return b===""||b==='""'}get str(){var b;return(b=this._str)!==null&&b!==void 0?b:this._str=this._items.reduce((w,$)=>`${w}${$}`,"")}get names(){var b;return(b=this._names)!==null&&b!==void 0?b:this._names=this._items.reduce((w,$)=>{if($ instanceof pw)w[$.str]=(w[$.str]||0)+1;return w},{})}}RG._Code=yb;RG.nil=new yb("");function _G(b,...w){let $=[b[0]],W=0;while(W<w.length)W6($,w[W]),$.push(b[++W]);return new yb($)}RG._=_G;var $6=new yb("+");function SG(b,...w){let $=[y1(b[0])],W=0;while(W<w.length)$.push($6),W6($,w[W]),$.push($6,y1(b[++W]));return YO($),new yb($)}RG.str=SG;function W6(b,w){if(w instanceof yb)b.push(...w._items);else if(w instanceof pw)b.push(w);else b.push(DO(w))}RG.addCodeArg=W6;function YO(b){let w=1;while(w<b.length-1){if(b[w]===$6){let $=HO(b[w-1],b[w+1]);if($!==void 0){b.splice(w-1,3,$);continue}b[w++]="+"}w++}}function HO(b,w){if(w==='""')return b;if(b==='""')return w;if(typeof b=="string"){if(w instanceof pw||b[b.length-1]!=='"')return;if(typeof w!="string")return`${b.slice(0,-1)}${w}"`;if(w[0]==='"')return b.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!(b instanceof pw))return`"${b}${w.slice(1)}`;return}function JO(b,w){return w.emptyStr()?b:b.emptyStr()?w:SG`${b}${w}`}RG.strConcat=JO;function DO(b){return typeof b=="number"||typeof b=="boolean"||b===null?b:y1(Array.isArray(b)?b.join(","):b)}function zO(b){return new yb(y1(b))}RG.stringify=zO;function y1(b){return JSON.stringify(b).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}RG.safeStringify=y1;function AO(b){return typeof b=="string"&&RG.IDENTIFIER.test(b)?new yb(`.${b}`):_G`[${b}]`}RG.getProperty=AO;function OO(b){if(typeof b=="string"&&RG.IDENTIFIER.test(b))return new yb(`${b}`);throw Error(`CodeGen: invalid export name: ${b}, use explicit $id name mapping`)}RG.getEsmExportName=OO;function qO(b){return new yb(b.toString())}RG.regexpCode=qO});var Y6=I((xG)=>{Object.defineProperty(xG,"__esModule",{value:!0});xG.ValueScope=xG.ValueScopeName=xG.Scope=xG.varKinds=xG.UsedValueState=void 0;var Mb=h1();class vG extends Error{constructor(b){super(`CodeGen: "code" for ${b} not defined`);this.value=b.value}}var r0;(function(b){b[b.Started=0]="Started",b[b.Completed=1]="Completed"})(r0||(xG.UsedValueState=r0={}));xG.varKinds={const:new Mb.Name("const"),let:new Mb.Name("let"),var:new Mb.Name("var")};class G6{constructor({prefixes:b,parent:w}={}){this._names={},this._prefixes=b,this._parent=w}toName(b){return b instanceof Mb.Name?b:this.name(b)}name(b){return new Mb.Name(this._newName(b))}_newName(b){let w=this._names[b]||this._nameGroup(b);return`${b}${w.index++}`}_nameGroup(b){var w,$;if((($=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||$===void 0?void 0:$.has(b))||this._prefixes&&!this._prefixes.has(b))throw Error(`CodeGen: prefix "${b}" is not allowed in this scope`);return this._names[b]={prefix:b,index:0}}}xG.Scope=G6;class X6 extends Mb.Name{constructor(b,w){super(w);this.prefix=b}setValue(b,{property:w,itemIndex:$}){this.value=b,this.scopePath=Mb._`.${new Mb.Name(w)}[${$}]`}}xG.ValueScopeName=X6;var TO=Mb._`\n`;class CG extends G6{constructor(b){super(b);this._values={},this._scope=b.scope,this.opts={...b,_n:b.lines?TO:Mb.nil}}get(){return this._scope}name(b){return new X6(b,this._newName(b))}value(b,w){var $;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName(b),{prefix:Q}=W,G=($=w.key)!==null&&$!==void 0?$:w.ref,X=this._values[Q];if(X){let J=X.get(G);if(J)return J}else X=this._values[Q]=new Map;X.set(G,W);let Y=this._scope[Q]||(this._scope[Q]=[]),H=Y.length;return Y[H]=w.ref,W.setValue(w,{property:Q,itemIndex:H}),W}getValue(b,w){let $=this._values[b];if(!$)return;return $.get(w)}scopeRefs(b,w=this._values){return this._reduceValues(w,($)=>{if($.scopePath===void 0)throw Error(`CodeGen: name "${$}" has no value`);return Mb._`${b}${$.scopePath}`})}scopeCode(b=this._values,w,$){return this._reduceValues(b,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},w,$)}_reduceValues(b,w,$={},W){let Q=Mb.nil;for(let G in b){let X=b[G];if(!X)continue;let Y=$[G]=$[G]||new Map;X.forEach((H)=>{if(Y.has(H))return;Y.set(H,r0.Started);let J=w(H);if(J){let D=this.opts.es5?xG.varKinds.var:xG.varKinds.const;Q=Mb._`${Q}${D} ${H} = ${J};${this.opts._n}`}else if(J=W===null||W===void 0?void 0:W(H))Q=Mb._`${Q}${J}${this.opts._n}`;else throw new vG(H);Y.set(H,r0.Completed)})}return Q}}xG.ValueScope=CG});var u=I((Zb)=>{Object.defineProperty(Zb,"__esModule",{value:!0});Zb.or=Zb.and=Zb.not=Zb.CodeGen=Zb.operators=Zb.varKinds=Zb.ValueScopeName=Zb.ValueScope=Zb.Scope=Zb.Name=Zb.regexpCode=Zb.stringify=Zb.getProperty=Zb.nil=Zb.strConcat=Zb.str=Zb._=void 0;var g=h1(),hb=Y6(),Pw=h1();Object.defineProperty(Zb,"_",{enumerable:!0,get:function(){return Pw._}});Object.defineProperty(Zb,"str",{enumerable:!0,get:function(){return Pw.str}});Object.defineProperty(Zb,"strConcat",{enumerable:!0,get:function(){return Pw.strConcat}});Object.defineProperty(Zb,"nil",{enumerable:!0,get:function(){return Pw.nil}});Object.defineProperty(Zb,"getProperty",{enumerable:!0,get:function(){return Pw.getProperty}});Object.defineProperty(Zb,"stringify",{enumerable:!0,get:function(){return Pw.stringify}});Object.defineProperty(Zb,"regexpCode",{enumerable:!0,get:function(){return Pw.regexpCode}});Object.defineProperty(Zb,"Name",{enumerable:!0,get:function(){return Pw.Name}});var $$=Y6();Object.defineProperty(Zb,"Scope",{enumerable:!0,get:function(){return $$.Scope}});Object.defineProperty(Zb,"ValueScope",{enumerable:!0,get:function(){return $$.ValueScope}});Object.defineProperty(Zb,"ValueScopeName",{enumerable:!0,get:function(){return $$.ValueScopeName}});Object.defineProperty(Zb,"varKinds",{enumerable:!0,get:function(){return $$.varKinds}});Zb.operators={GT:new g._Code(">"),GTE:new g._Code(">="),LT:new g._Code("<"),LTE:new g._Code("<="),EQ:new g._Code("==="),NEQ:new g._Code("!=="),NOT:new g._Code("!"),OR:new g._Code("||"),AND:new g._Code("&&"),ADD:new g._Code("+")};class Mw{optimizeNodes(){return this}optimizeNames(b,w){return this}}class yG extends Mw{constructor(b,w,$){super();this.varKind=b,this.name=w,this.rhs=$}render({es5:b,_n:w}){let $=b?hb.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${W};`+w}optimizeNames(b,w){if(!b[this.name.str])return;if(this.rhs)this.rhs=dw(this.rhs,b,w);return this}get names(){return this.rhs instanceof g._CodeOrName?this.rhs.names:{}}}class D6 extends Mw{constructor(b,w,$){super();this.lhs=b,this.rhs=w,this.sideEffects=$}render({_n:b}){return`${this.lhs} = ${this.rhs};`+b}optimizeNames(b,w){if(this.lhs instanceof g.Name&&!b[this.lhs.str]&&!this.sideEffects)return;return this.rhs=dw(this.rhs,b,w),this}get names(){let b=this.lhs instanceof g.Name?{}:{...this.lhs.names};return w$(b,this.rhs)}}class hG extends D6{constructor(b,w,$,W){super(b,$,W);this.op=w}render({_n:b}){return`${this.lhs} ${this.op}= ${this.rhs};`+b}}class fG extends Mw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`${this.label}:`+b}}class cG extends Mw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`break${this.label?` ${this.label}`:""};`+b}}class gG extends Mw{constructor(b){super();this.error=b}render({_n:b}){return`throw ${this.error};`+b}get names(){return this.error.names}}class mG extends Mw{constructor(b){super();this.code=b}render({_n:b}){return`${this.code};`+b}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(b,w){return this.code=dw(this.code,b,w),this}get names(){return this.code instanceof g._CodeOrName?this.code.names:{}}}class W$ extends Mw{constructor(b=[]){super();this.nodes=b}render(b){return this.nodes.reduce((w,$)=>w+$.render(b),"")}optimizeNodes(){let{nodes:b}=this,w=b.length;while(w--){let $=b[w].optimizeNodes();if(Array.isArray($))b.splice(w,1,...$);else if($)b[w]=$;else b.splice(w,1)}return b.length>0?this:void 0}optimizeNames(b,w){let{nodes:$}=this,W=$.length;while(W--){let Q=$[W];if(Q.optimizeNames(b,w))continue;RO(b,Q.names),$.splice(W,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((b,w)=>Rw(b,w.names),{})}}class Zw extends W${render(b){return"{"+b._n+super.render(b)+"}"+b._n}}class nG extends W${}class f1 extends Zw{}f1.kind="else";class Ww extends Zw{constructor(b,w){super(w);this.condition=b}render(b){let w=`if(${this.condition})`+super.render(b);if(this.else)w+="else "+this.else.render(b);return w}optimizeNodes(){super.optimizeNodes();let b=this.condition;if(b===!0)return this.nodes;let w=this.else;if(w){let $=w.optimizeNodes();w=this.else=Array.isArray($)?new f1($):$}if(w){if(b===!1)return w instanceof Ww?w:w.nodes;if(this.nodes.length)return this;return new Ww(dG(b),w instanceof Ww?[w]:w.nodes)}if(b===!1||!this.nodes.length)return;return this}optimizeNames(b,w){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(b,w),!(super.optimizeNames(b,w)||this.else))return;return this.condition=dw(this.condition,b,w),this}get names(){let b=super.names;if(w$(b,this.condition),this.else)Rw(b,this.else.names);return b}}Ww.kind="if";class ow extends Zw{}ow.kind="for";class lG extends ow{constructor(b){super();this.iteration=b}render(b){return`for(${this.iteration})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iteration=dw(this.iteration,b,w),this}get names(){return Rw(super.names,this.iteration.names)}}class iG extends ow{constructor(b,w,$,W){super();this.varKind=b,this.name=w,this.from=$,this.to=W}render(b){let w=b.es5?hb.varKinds.var:this.varKind,{name:$,from:W,to:Q}=this;return`for(${w} ${$}=${W}; ${$}<${Q}; ${$}++)`+super.render(b)}get names(){let b=w$(super.names,this.from);return w$(b,this.to)}}class H6 extends ow{constructor(b,w,$,W){super();this.loop=b,this.varKind=w,this.name=$,this.iterable=W}render(b){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iterable=dw(this.iterable,b,w),this}get names(){return Rw(super.names,this.iterable.names)}}class e0 extends Zw{constructor(b,w,$){super();this.name=b,this.args=w,this.async=$}render(b){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(b)}}e0.kind="func";class s0 extends W${render(b){return"return "+super.render(b)}}s0.kind="return";class pG extends Zw{render(b){let w="try"+super.render(b);if(this.catch)w+=this.catch.render(b);if(this.finally)w+=this.finally.render(b);return w}optimizeNodes(){var b,w;return super.optimizeNodes(),(b=this.catch)===null||b===void 0||b.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(b,w){var $,W;return super.optimizeNames(b,w),($=this.catch)===null||$===void 0||$.optimizeNames(b,w),(W=this.finally)===null||W===void 0||W.optimizeNames(b,w),this}get names(){let b=super.names;if(this.catch)Rw(b,this.catch.names);if(this.finally)Rw(b,this.finally.names);return b}}class a0 extends Zw{constructor(b){super();this.error=b}render(b){return`catch(${this.error})`+super.render(b)}}a0.kind="catch";class b$ extends Zw{render(b){return"finally"+super.render(b)}}b$.kind="finally";class oG{constructor(b,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
2
- `:""},this._extScope=b,this._scope=new hb.Scope({parent:b}),this._nodes=[new nG]}toString(){return this._root.render(this.opts)}name(b){return this._scope.name(b)}scopeName(b){return this._extScope.name(b)}scopeValue(b,w){let $=this._extScope.value(b,w);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(b,w){return this._extScope.getValue(b,w)}scopeRefs(b){return this._extScope.scopeRefs(b,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(b,w,$,W){let Q=this._scope.toName(w);if($!==void 0&&W)this._constants[Q.str]=$;return this._leafNode(new yG(b,Q,$)),Q}const(b,w,$){return this._def(hb.varKinds.const,b,w,$)}let(b,w,$){return this._def(hb.varKinds.let,b,w,$)}var(b,w,$){return this._def(hb.varKinds.var,b,w,$)}assign(b,w,$){return this._leafNode(new D6(b,w,$))}add(b,w){return this._leafNode(new hG(b,Zb.operators.ADD,w))}code(b){if(typeof b=="function")b();else if(b!==g.nil)this._leafNode(new mG(b));return this}object(...b){let w=["{"];for(let[$,W]of b){if(w.length>1)w.push(",");if(w.push($),$!==W||this.opts.es5)w.push(":"),(0,g.addCodeArg)(w,W)}return w.push("}"),new g._Code(w)}if(b,w,$){if(this._blockNode(new Ww(b)),w&&$)this.code(w).else().code($).endIf();else if(w)this.code(w).endIf();else if($)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(b){return this._elseNode(new Ww(b))}else(){return this._elseNode(new f1)}endIf(){return this._endBlockNode(Ww,f1)}_for(b,w){if(this._blockNode(b),w)this.code(w).endFor();return this}for(b,w){return this._for(new lG(b),w)}forRange(b,w,$,W,Q=this.opts.es5?hb.varKinds.var:hb.varKinds.let){let G=this._scope.toName(b);return this._for(new iG(Q,G,w,$),()=>W(G))}forOf(b,w,$,W=hb.varKinds.const){let Q=this._scope.toName(b);if(this.opts.es5){let G=w instanceof g.Name?w:this.var("_arr",w);return this.forRange("_i",0,g._`${G}.length`,(X)=>{this.var(Q,g._`${G}[${X}]`),$(Q)})}return this._for(new H6("of",W,Q,w),()=>$(Q))}forIn(b,w,$,W=this.opts.es5?hb.varKinds.var:hb.varKinds.const){if(this.opts.ownProperties)return this.forOf(b,g._`Object.keys(${w})`,$);let Q=this._scope.toName(b);return this._for(new H6("in",W,Q,w),()=>$(Q))}endFor(){return this._endBlockNode(ow)}label(b){return this._leafNode(new fG(b))}break(b){return this._leafNode(new cG(b))}return(b){let w=new s0;if(this._blockNode(w),this.code(b),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(s0)}try(b,w,$){if(!w&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new pG;if(this._blockNode(W),this.code(b),w){let Q=this.name("e");this._currNode=W.catch=new a0(Q),w(Q)}if($)this._currNode=W.finally=new b$,this.code($);return this._endBlockNode(a0,b$)}throw(b){return this._leafNode(new gG(b))}block(b,w){if(this._blockStarts.push(this._nodes.length),b)this.code(b).endBlock(w);return this}endBlock(b){let w=this._blockStarts.pop();if(w===void 0)throw Error("CodeGen: not in self-balancing block");let $=this._nodes.length-w;if($<0||b!==void 0&&$!==b)throw Error(`CodeGen: wrong number of nodes: ${$} vs ${b} expected`);return this._nodes.length=w,this}func(b,w=g.nil,$,W){if(this._blockNode(new e0(b,w,$)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(e0)}optimize(b=1){while(b-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(b){return this._currNode.nodes.push(b),this}_blockNode(b){this._currNode.nodes.push(b),this._nodes.push(b)}_endBlockNode(b,w){let $=this._currNode;if($ instanceof b||w&&$ instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${b.kind}/${w.kind}`:b.kind}"`)}_elseNode(b){let w=this._currNode;if(!(w instanceof Ww))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=b,this}get _root(){return this._nodes[0]}get _currNode(){let b=this._nodes;return b[b.length-1]}set _currNode(b){let w=this._nodes;w[w.length-1]=b}}Zb.CodeGen=oG;function Rw(b,w){for(let $ in w)b[$]=(b[$]||0)+(w[$]||0);return b}function w$(b,w){return w instanceof g._CodeOrName?Rw(b,w.names):b}function dw(b,w,$){if(b instanceof g.Name)return W(b);if(!Q(b))return b;return new g._Code(b._items.reduce((G,X)=>{if(X instanceof g.Name)X=W(X);if(X instanceof g._Code)G.push(...X._items);else G.push(X);return G},[]));function W(G){let X=$[G.str];if(X===void 0||w[G.str]!==1)return G;return delete w[G.str],X}function Q(G){return G instanceof g._Code&&G._items.some((X)=>X instanceof g.Name&&w[X.str]===1&&$[X.str]!==void 0)}}function RO(b,w){for(let $ in w)b[$]=(b[$]||0)-(w[$]||0)}function dG(b){return typeof b=="boolean"||typeof b=="number"||b===null?!b:g._`!${J6(b)}`}Zb.not=dG;var kO=tG(Zb.operators.AND);function vO(...b){return b.reduce(kO)}Zb.and=vO;var CO=tG(Zb.operators.OR);function xO(...b){return b.reduce(CO)}Zb.or=xO;function tG(b){return(w,$)=>w===g.nil?$:$===g.nil?w:g._`${J6(w)} ${b} ${J6($)}`}function J6(b){return b instanceof g.Name?b:g._`(${b})`}});var l=I((QX)=>{Object.defineProperty(QX,"__esModule",{value:!0});QX.checkStrictMode=QX.getErrorPath=QX.Type=QX.useFunc=QX.setEvaluated=QX.evaluatedPropsToName=QX.mergeEvaluated=QX.eachItem=QX.unescapeJsonPointer=QX.escapeJsonPointer=QX.escapeFragment=QX.unescapeFragment=QX.schemaRefOrVal=QX.schemaHasRulesButRef=QX.schemaHasRules=QX.checkUnknownRules=QX.alwaysValidSchema=QX.toHash=void 0;var d=u(),fO=h1();function cO(b){let w={};for(let $ of b)w[$]=!0;return w}QX.toHash=cO;function gO(b,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return aG(b,w),!bX(w,b.self.RULES.all)}QX.alwaysValidSchema=gO;function aG(b,w=b.schema){let{opts:$,self:W}=b;if(!$.strictSchema)return;if(typeof w==="boolean")return;let Q=W.RULES.keywords;for(let G in w)if(!Q[G])WX(b,`unknown keyword: "${G}"`)}QX.checkUnknownRules=aG;function bX(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if(w[$])return!0;return!1}QX.schemaHasRules=bX;function mO(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if($!=="$ref"&&w.all[$])return!0;return!1}QX.schemaHasRulesButRef=mO;function nO({topSchemaRef:b,schemaPath:w},$,W,Q){if(!Q){if(typeof $=="number"||typeof $=="boolean")return $;if(typeof $=="string")return d._`${$}`}return d._`${b}${w}${(0,d.getProperty)(W)}`}QX.schemaRefOrVal=nO;function lO(b){return wX(decodeURIComponent(b))}QX.unescapeFragment=lO;function iO(b){return encodeURIComponent(A6(b))}QX.escapeFragment=iO;function A6(b){if(typeof b=="number")return`${b}`;return b.replace(/~/g,"~0").replace(/\//g,"~1")}QX.escapeJsonPointer=A6;function wX(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}QX.unescapeJsonPointer=wX;function pO(b,w){if(Array.isArray(b))for(let $ of b)w($);else w(b)}QX.eachItem=pO;function eG({mergeNames:b,mergeToName:w,mergeValues:$,resultToName:W}){return(Q,G,X,Y)=>{let H=X===void 0?G:X instanceof d.Name?(G instanceof d.Name?b(Q,G,X):w(Q,G,X),X):G instanceof d.Name?(w(Q,X,G),G):$(G,X);return Y===d.Name&&!(H instanceof d.Name)?W(Q,H):H}}QX.mergeEvaluated={props:eG({mergeNames:(b,w,$)=>b.if(d._`${$} !== true && ${w} !== undefined`,()=>{b.if(d._`${w} === true`,()=>b.assign($,!0),()=>b.assign($,d._`${$} || {}`).code(d._`Object.assign(${$}, ${w})`))}),mergeToName:(b,w,$)=>b.if(d._`${$} !== true`,()=>{if(w===!0)b.assign($,!0);else b.assign($,d._`${$} || {}`),O6(b,$,w)}),mergeValues:(b,w)=>b===!0?!0:{...b,...w},resultToName:$X}),items:eG({mergeNames:(b,w,$)=>b.if(d._`${$} !== true && ${w} !== undefined`,()=>b.assign($,d._`${w} === true ? true : ${$} > ${w} ? ${$} : ${w}`)),mergeToName:(b,w,$)=>b.if(d._`${$} !== true`,()=>b.assign($,w===!0?!0:d._`${$} > ${w} ? ${$} : ${w}`)),mergeValues:(b,w)=>b===!0?!0:Math.max(b,w),resultToName:(b,w)=>b.var("items",w)})};function $X(b,w){if(w===!0)return b.var("props",!0);let $=b.var("props",d._`{}`);if(w!==void 0)O6(b,$,w);return $}QX.evaluatedPropsToName=$X;function O6(b,w,$){Object.keys($).forEach((W)=>b.assign(d._`${w}${(0,d.getProperty)(W)}`,!0))}QX.setEvaluated=O6;var sG={};function oO(b,w){return b.scopeValue("func",{ref:w,code:sG[w.code]||(sG[w.code]=new fO._Code(w.code))})}QX.useFunc=oO;var z6;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(z6||(QX.Type=z6={}));function dO(b,w,$){if(b instanceof d.Name){let W=w===z6.Num;return $?W?d._`"[" + ${b} + "]"`:d._`"['" + ${b} + "']"`:W?d._`"/" + ${b}`:d._`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,d.getProperty)(b).toString():"/"+A6(b)}QX.getErrorPath=dO;function WX(b,w,$=b.opts.strictSchema){if(!$)return;if(w=`strict mode: ${w}`,$===!0)throw Error(w);b.self.logger.warn(w)}QX.checkStrictMode=WX});var Qw=I((XX)=>{Object.defineProperty(XX,"__esModule",{value:!0});var Lb=u(),Aq={data:new Lb.Name("data"),valCxt:new Lb.Name("valCxt"),instancePath:new Lb.Name("instancePath"),parentData:new Lb.Name("parentData"),parentDataProperty:new Lb.Name("parentDataProperty"),rootData:new Lb.Name("rootData"),dynamicAnchors:new Lb.Name("dynamicAnchors"),vErrors:new Lb.Name("vErrors"),errors:new Lb.Name("errors"),this:new Lb.Name("this"),self:new Lb.Name("self"),scope:new Lb.Name("scope"),json:new Lb.Name("json"),jsonPos:new Lb.Name("jsonPos"),jsonLen:new Lb.Name("jsonLen"),jsonPart:new Lb.Name("jsonPart")};XX.default=Aq});var c1=I((DX)=>{Object.defineProperty(DX,"__esModule",{value:!0});DX.extendErrors=DX.resetErrorsCount=DX.reportExtraError=DX.reportError=DX.keyword$DataError=DX.keywordError=void 0;var m=u(),G$=l(),Bb=Qw();DX.keywordError={message:({keyword:b})=>m.str`must pass "${b}" keyword validation`};DX.keyword$DataError={message:({keyword:b,schemaType:w})=>w?m.str`"${b}" keyword must be ${w} ($data)`:m.str`"${b}" keyword is invalid ($data)`};function qq(b,w=DX.keywordError,$,W){let{it:Q}=b,{gen:G,compositeRule:X,allErrors:Y}=Q,H=JX(b,w,$);if(W!==null&&W!==void 0?W:X||Y)YX(G,H);else HX(Q,m._`[${H}]`)}DX.reportError=qq;function Lq(b,w=DX.keywordError,$){let{it:W}=b,{gen:Q,compositeRule:G,allErrors:X}=W,Y=JX(b,w,$);if(YX(Q,Y),!(G||X))HX(W,Bb.default.vErrors)}DX.reportExtraError=Lq;function Uq(b,w){b.assign(Bb.default.errors,w),b.if(m._`${Bb.default.vErrors} !== null`,()=>b.if(w,()=>b.assign(m._`${Bb.default.vErrors}.length`,w),()=>b.assign(Bb.default.vErrors,null)))}DX.resetErrorsCount=Uq;function Bq({gen:b,keyword:w,schemaValue:$,data:W,errsCount:Q,it:G}){if(Q===void 0)throw Error("ajv implementation error");let X=b.name("err");b.forRange("i",Q,Bb.default.errors,(Y)=>{if(b.const(X,m._`${Bb.default.vErrors}[${Y}]`),b.if(m._`${X}.instancePath === undefined`,()=>b.assign(m._`${X}.instancePath`,(0,m.strConcat)(Bb.default.instancePath,G.errorPath))),b.assign(m._`${X}.schemaPath`,m.str`${G.errSchemaPath}/${w}`),G.opts.verbose)b.assign(m._`${X}.schema`,$),b.assign(m._`${X}.data`,W)})}DX.extendErrors=Bq;function YX(b,w){let $=b.const("err",w);b.if(m._`${Bb.default.vErrors} === null`,()=>b.assign(Bb.default.vErrors,m._`[${$}]`),m._`${Bb.default.vErrors}.push(${$})`),b.code(m._`${Bb.default.errors}++`)}function HX(b,w){let{gen:$,validateName:W,schemaEnv:Q}=b;if(Q.$async)$.throw(m._`new ${b.ValidationError}(${w})`);else $.assign(m._`${W}.errors`,w),$.return(!1)}var kw={keyword:new m.Name("keyword"),schemaPath:new m.Name("schemaPath"),params:new m.Name("params"),propertyName:new m.Name("propertyName"),message:new m.Name("message"),schema:new m.Name("schema"),parentSchema:new m.Name("parentSchema")};function JX(b,w,$){let{createErrors:W}=b.it;if(W===!1)return m._`{}`;return Fq(b,w,$)}function Fq(b,w,$={}){let{gen:W,it:Q}=b,G=[Kq(Q,$),Pq(b,$)];return Mq(b,w,G),W.object(...G)}function Kq({errorPath:b},{instancePath:w}){let $=w?m.str`${b}${(0,G$.getErrorPath)(w,G$.Type.Str)}`:b;return[Bb.default.instancePath,(0,m.strConcat)(Bb.default.instancePath,$)]}function Pq({keyword:b,it:{errSchemaPath:w}},{schemaPath:$,parentSchema:W}){let Q=W?w:m.str`${w}/${b}`;if($)Q=m.str`${Q}${(0,G$.getErrorPath)($,G$.Type.Str)}`;return[kw.schemaPath,Q]}function Mq(b,{params:w,message:$},W){let{keyword:Q,data:G,schemaValue:X,it:Y}=b,{opts:H,propertyName:J,topSchemaRef:D,schemaPath:z}=Y;if(W.push([kw.keyword,Q],[kw.params,typeof w=="function"?w(b):w||m._`{}`]),H.messages)W.push([kw.message,typeof $=="function"?$(b):$]);if(H.verbose)W.push([kw.schema,X],[kw.parentSchema,m._`${D}${z}`],[Bb.default.data,G]);if(J)W.push([kw.propertyName,J])}});var LX=I((OX)=>{Object.defineProperty(OX,"__esModule",{value:!0});OX.boolOrEmptySchema=OX.topBoolOrEmptySchema=void 0;var Nq=c1(),Tq=u(),Eq=Qw(),_q={message:"boolean schema is false"};function Sq(b){let{gen:w,schema:$,validateName:W}=b;if($===!1)AX(b,!1);else if(typeof $=="object"&&$.$async===!0)w.return(Eq.default.data);else w.assign(Tq._`${W}.errors`,null),w.return(!0)}OX.topBoolOrEmptySchema=Sq;function Rq(b,w){let{gen:$,schema:W}=b;if(W===!1)$.var(w,!1),AX(b);else $.var(w,!0)}OX.boolOrEmptySchema=Rq;function AX(b,w){let{gen:$,data:W}=b,Q={gen:$,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:b};(0,Nq.reportError)(Q,_q,void 0,w)}});var L6=I((UX)=>{Object.defineProperty(UX,"__esModule",{value:!0});UX.getRules=UX.isJSONType=void 0;var vq=["string","number","integer","boolean","null","object","array"],Cq=new Set(vq);function xq(b){return typeof b=="string"&&Cq.has(b)}UX.isJSONType=xq;function uq(){let b={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...b,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},b.number,b.string,b.array,b.object],post:{rules:[]},all:{},keywords:{}}}UX.getRules=uq});var U6=I((PX)=>{Object.defineProperty(PX,"__esModule",{value:!0});PX.shouldUseRule=PX.shouldUseGroup=PX.schemaHasRulesForType=void 0;function hq({schema:b,self:w},$){let W=w.RULES.types[$];return W&&W!==!0&&FX(b,W)}PX.schemaHasRulesForType=hq;function FX(b,w){return w.rules.some(($)=>KX(b,$))}PX.shouldUseGroup=FX;function KX(b,w){var $;return b[w.keyword]!==void 0||(($=w.definition.implements)===null||$===void 0?void 0:$.some((W)=>b[W]!==void 0))}PX.shouldUseRule=KX});var g1=I((VX)=>{Object.defineProperty(VX,"__esModule",{value:!0});VX.reportTypeError=VX.checkDataTypes=VX.checkDataType=VX.coerceAndCheckDataType=VX.getJSONTypes=VX.getSchemaTypes=VX.DataType=void 0;var gq=L6(),mq=U6(),nq=c1(),C=u(),ZX=l(),tw;(function(b){b[b.Correct=0]="Correct",b[b.Wrong=1]="Wrong"})(tw||(VX.DataType=tw={}));function lq(b){let w=jX(b.type);if(w.includes("null")){if(b.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!w.length&&b.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(b.nullable===!0)w.push("null")}return w}VX.getSchemaTypes=lq;function jX(b){let w=Array.isArray(b)?b:b?[b]:[];if(w.every(gq.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}VX.getJSONTypes=jX;function iq(b,w){let{gen:$,data:W,opts:Q}=b,G=pq(w,Q.coerceTypes),X=w.length>0&&!(G.length===0&&w.length===1&&(0,mq.schemaHasRulesForType)(b,w[0]));if(X){let Y=F6(w,W,Q.strictNumbers,tw.Wrong);$.if(Y,()=>{if(G.length)oq(b,w,G);else K6(b)})}return X}VX.coerceAndCheckDataType=iq;var IX=new Set(["string","number","integer","boolean","null"]);function pq(b,w){return w?b.filter(($)=>IX.has($)||w==="array"&&$==="array"):[]}function oq(b,w,$){let{gen:W,data:Q,opts:G}=b,X=W.let("dataType",C._`typeof ${Q}`),Y=W.let("coerced",C._`undefined`);if(G.coerceTypes==="array")W.if(C._`${X} == 'object' && Array.isArray(${Q}) && ${Q}.length == 1`,()=>W.assign(Q,C._`${Q}[0]`).assign(X,C._`typeof ${Q}`).if(F6(w,Q,G.strictNumbers),()=>W.assign(Y,Q)));W.if(C._`${Y} !== undefined`);for(let J of $)if(IX.has(J)||J==="array"&&G.coerceTypes==="array")H(J);W.else(),K6(b),W.endIf(),W.if(C._`${Y} !== undefined`,()=>{W.assign(Q,Y),dq(b,Y)});function H(J){switch(J){case"string":W.elseIf(C._`${X} == "number" || ${X} == "boolean"`).assign(Y,C._`"" + ${Q}`).elseIf(C._`${Q} === null`).assign(Y,C._`""`);return;case"number":W.elseIf(C._`${X} == "boolean" || ${Q} === null
3
- || (${X} == "string" && ${Q} && ${Q} == +${Q})`).assign(Y,C._`+${Q}`);return;case"integer":W.elseIf(C._`${X} === "boolean" || ${Q} === null
4
- || (${X} === "string" && ${Q} && ${Q} == +${Q} && !(${Q} % 1))`).assign(Y,C._`+${Q}`);return;case"boolean":W.elseIf(C._`${Q} === "false" || ${Q} === 0 || ${Q} === null`).assign(Y,!1).elseIf(C._`${Q} === "true" || ${Q} === 1`).assign(Y,!0);return;case"null":W.elseIf(C._`${Q} === "" || ${Q} === 0 || ${Q} === false`),W.assign(Y,null);return;case"array":W.elseIf(C._`${X} === "string" || ${X} === "number"
5
- || ${X} === "boolean" || ${Q} === null`).assign(Y,C._`[${Q}]`)}}}function dq({gen:b,parentData:w,parentDataProperty:$},W){b.if(C._`${w} !== undefined`,()=>b.assign(C._`${w}[${$}]`,W))}function B6(b,w,$,W=tw.Correct){let Q=W===tw.Correct?C.operators.EQ:C.operators.NEQ,G;switch(b){case"null":return C._`${w} ${Q} null`;case"array":G=C._`Array.isArray(${w})`;break;case"object":G=C._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":G=X(C._`!(${w} % 1) && !isNaN(${w})`);break;case"number":G=X();break;default:return C._`typeof ${w} ${Q} ${b}`}return W===tw.Correct?G:(0,C.not)(G);function X(Y=C.nil){return(0,C.and)(C._`typeof ${w} == "number"`,Y,$?C._`isFinite(${w})`:C.nil)}}VX.checkDataType=B6;function F6(b,w,$,W){if(b.length===1)return B6(b[0],w,$,W);let Q,G=(0,ZX.toHash)(b);if(G.array&&G.object){let X=C._`typeof ${w} != "object"`;Q=G.null?X:C._`!${w} || ${X}`,delete G.null,delete G.array,delete G.object}else Q=C.nil;if(G.number)delete G.integer;for(let X in G)Q=(0,C.and)(Q,B6(X,w,$,W));return Q}VX.checkDataTypes=F6;var tq={message:({schema:b})=>`must be ${b}`,params:({schema:b,schemaValue:w})=>typeof b=="string"?C._`{type: ${b}}`:C._`{type: ${w}}`};function K6(b){let w=rq(b);(0,nq.reportError)(w,tq)}VX.reportTypeError=K6;function rq(b){let{gen:w,data:$,schema:W}=b,Q=(0,ZX.schemaRefOrVal)(b,W,"type");return{gen:w,keyword:"type",data:$,schema:W.type,schemaCode:Q,schemaValue:Q,parentSchema:W,params:{},it:b}}});var SX=I((EX)=>{Object.defineProperty(EX,"__esModule",{value:!0});EX.assignDefaults=void 0;var rw=u(),WL=l();function QL(b,w){let{properties:$,items:W}=b.schema;if(w==="object"&&$)for(let Q in $)TX(b,Q,$[Q].default);else if(w==="array"&&Array.isArray(W))W.forEach((Q,G)=>TX(b,G,Q.default))}EX.assignDefaults=QL;function TX(b,w,$){let{gen:W,compositeRule:Q,data:G,opts:X}=b;if($===void 0)return;let Y=rw._`${G}${(0,rw.getProperty)(w)}`;if(Q){(0,WL.checkStrictMode)(b,`default is ignored for: ${Y}`);return}let H=rw._`${Y} === undefined`;if(X.useDefaults==="empty")H=rw._`${H} || ${Y} === null || ${Y} === ""`;W.if(H,rw._`${Y} = ${(0,rw.stringify)($)}`)}});var vb=I((vX)=>{Object.defineProperty(vX,"__esModule",{value:!0});vX.validateUnion=vX.validateArray=vX.usePattern=vX.callValidateCode=vX.schemaProperties=vX.allSchemaProperties=vX.noPropertyInData=vX.propertyInData=vX.isOwnProperty=vX.hasPropFunc=vX.reportMissingProp=vX.checkMissingProp=vX.checkReportMissingProp=void 0;var a=u(),P6=l(),jw=Qw(),GL=l();function XL(b,w){let{gen:$,data:W,it:Q}=b;$.if(Z6($,W,w,Q.opts.ownProperties),()=>{b.setParams({missingProperty:a._`${w}`},!0),b.error()})}vX.checkReportMissingProp=XL;function YL({gen:b,data:w,it:{opts:$}},W,Q){return(0,a.or)(...W.map((G)=>(0,a.and)(Z6(b,w,G,$.ownProperties),a._`${Q} = ${G}`)))}vX.checkMissingProp=YL;function HL(b,w){b.setParams({missingProperty:w},!0),b.error()}vX.reportMissingProp=HL;function RX(b){return b.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:a._`Object.prototype.hasOwnProperty`})}vX.hasPropFunc=RX;function M6(b,w,$){return a._`${RX(b)}.call(${w}, ${$})`}vX.isOwnProperty=M6;function JL(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} !== undefined`;return W?a._`${Q} && ${M6(b,w,$)}`:Q}vX.propertyInData=JL;function Z6(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} === undefined`;return W?(0,a.or)(Q,(0,a.not)(M6(b,w,$))):Q}vX.noPropertyInData=Z6;function kX(b){return b?Object.keys(b).filter((w)=>w!=="__proto__"):[]}vX.allSchemaProperties=kX;function DL(b,w){return kX(w).filter(($)=>!(0,P6.alwaysValidSchema)(b,w[$]))}vX.schemaProperties=DL;function zL({schemaCode:b,data:w,it:{gen:$,topSchemaRef:W,schemaPath:Q,errorPath:G},it:X},Y,H,J){let D=J?a._`${b}, ${w}, ${W}${Q}`:w,z=[[jw.default.instancePath,(0,a.strConcat)(jw.default.instancePath,G)],[jw.default.parentData,X.parentData],[jw.default.parentDataProperty,X.parentDataProperty],[jw.default.rootData,jw.default.rootData]];if(X.opts.dynamicRef)z.push([jw.default.dynamicAnchors,jw.default.dynamicAnchors]);let O=a._`${D}, ${$.object(...z)}`;return H!==a.nil?a._`${Y}.call(${H}, ${O})`:a._`${Y}(${O})`}vX.callValidateCode=zL;var AL=a._`new RegExp`;function OL({gen:b,it:{opts:w}},$){let W=w.unicodeRegExp?"u":"",{regExp:Q}=w.code,G=Q($,W);return b.scopeValue("pattern",{key:G.toString(),ref:G,code:a._`${Q.code==="new RegExp"?AL:(0,GL.useFunc)(b,Q)}(${$}, ${W})`})}vX.usePattern=OL;function qL(b){let{gen:w,data:$,keyword:W,it:Q}=b,G=w.name("valid");if(Q.allErrors){let Y=w.let("valid",!0);return X(()=>w.assign(Y,!1)),Y}return w.var(G,!0),X(()=>w.break()),G;function X(Y){let H=w.const("len",a._`${$}.length`);w.forRange("i",0,H,(J)=>{b.subschema({keyword:W,dataProp:J,dataPropType:P6.Type.Num},G),w.if((0,a.not)(G),Y)})}}vX.validateArray=qL;function LL(b){let{gen:w,schema:$,keyword:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((H)=>(0,P6.alwaysValidSchema)(Q,H))&&!Q.opts.unevaluated)return;let X=w.let("valid",!1),Y=w.name("_valid");w.block(()=>$.forEach((H,J)=>{let D=b.subschema({keyword:W,schemaProp:J,compositeRule:!0},Y);if(w.assign(X,a._`${X} || ${Y}`),!b.mergeValidEvaluated(D,Y))w.if((0,a.not)(X))})),b.result(X,()=>b.reset(),()=>b.error(!0))}vX.validateUnion=LL});var fX=I((yX)=>{Object.defineProperty(yX,"__esModule",{value:!0});yX.validateKeywordUsage=yX.validSchemaType=yX.funcKeywordCode=yX.macroKeywordCode=void 0;var Fb=u(),vw=Qw(),EL=vb(),_L=c1();function SL(b,w){let{gen:$,keyword:W,schema:Q,parentSchema:G,it:X}=b,Y=w.macro.call(X.self,Q,G,X),H=uX($,W,Y);if(X.opts.validateSchema!==!1)X.self.validateSchema(Y,!0);let J=$.name("valid");b.subschema({schema:Y,schemaPath:Fb.nil,errSchemaPath:`${X.errSchemaPath}/${W}`,topSchemaRef:H,compositeRule:!0},J),b.pass(J,()=>b.error(!0))}yX.macroKeywordCode=SL;function RL(b,w){var $;let{gen:W,keyword:Q,schema:G,parentSchema:X,$data:Y,it:H}=b;vL(H,w);let J=!Y&&w.compile?w.compile.call(H.self,G,X,H):w.validate,D=uX(W,Q,J),z=W.let("valid");b.block$data(z,O),b.ok(($=w.valid)!==null&&$!==void 0?$:z);function O(){if(w.errors===!1){if(K(),w.modifying)xX(b);Z(()=>b.error())}else{let M=w.async?q():B();if(w.modifying)xX(b);Z(()=>kL(b,M))}}function q(){let M=W.let("ruleErrs",null);return W.try(()=>K(Fb._`await `),(k)=>W.assign(z,!1).if(Fb._`${k} instanceof ${H.ValidationError}`,()=>W.assign(M,Fb._`${k}.errors`),()=>W.throw(k))),M}function B(){let M=Fb._`${D}.errors`;return W.assign(M,null),K(Fb.nil),M}function K(M=w.async?Fb._`await `:Fb.nil){let k=H.opts.passContext?vw.default.this:vw.default.self,S=!(("compile"in w)&&!Y||w.schema===!1);W.assign(z,Fb._`${M}${(0,EL.callValidateCode)(b,D,k,S)}`,w.modifying)}function Z(M){var k;W.if((0,Fb.not)((k=w.valid)!==null&&k!==void 0?k:z),M)}}yX.funcKeywordCode=RL;function xX(b){let{gen:w,data:$,it:W}=b;w.if(W.parentData,()=>w.assign($,Fb._`${W.parentData}[${W.parentDataProperty}]`))}function kL(b,w){let{gen:$}=b;$.if(Fb._`Array.isArray(${w})`,()=>{$.assign(vw.default.vErrors,Fb._`${vw.default.vErrors} === null ? ${w} : ${vw.default.vErrors}.concat(${w})`).assign(vw.default.errors,Fb._`${vw.default.vErrors}.length`),(0,_L.extendErrors)(b)},()=>b.error())}function vL({schemaEnv:b},w){if(w.async&&!b.$async)throw Error("async keyword in sync schema")}function uX(b,w,$){if($===void 0)throw Error(`keyword "${w}" failed to compile`);return b.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,Fb.stringify)($)})}function CL(b,w,$=!1){return!w.length||w.some((W)=>W==="array"?Array.isArray(b):W==="object"?b&&typeof b=="object"&&!Array.isArray(b):typeof b==W||$&&typeof b>"u")}yX.validSchemaType=CL;function xL({schema:b,opts:w,self:$,errSchemaPath:W},Q,G){if(Array.isArray(Q.keyword)?!Q.keyword.includes(G):Q.keyword!==G)throw Error("ajv implementation error");let X=Q.dependencies;if(X===null||X===void 0?void 0:X.some((Y)=>!Object.prototype.hasOwnProperty.call(b,Y)))throw Error(`parent schema must have dependencies of ${G}: ${X.join(",")}`);if(Q.validateSchema){if(!Q.validateSchema(b[G])){let H=`keyword "${G}" value is invalid at path "${W}": `+$.errorsText(Q.validateSchema.errors);if(w.validateSchema==="log")$.logger.error(H);else throw Error(H)}}}yX.validateKeywordUsage=xL});var nX=I((gX)=>{Object.defineProperty(gX,"__esModule",{value:!0});gX.extendSubschemaMode=gX.extendSubschemaData=gX.getSubschema=void 0;var db=u(),cX=l();function fL(b,{keyword:w,schemaProp:$,schema:W,schemaPath:Q,errSchemaPath:G,topSchemaRef:X}){if(w!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let Y=b.schema[w];return $===void 0?{schema:Y,schemaPath:db._`${b.schemaPath}${(0,db.getProperty)(w)}`,errSchemaPath:`${b.errSchemaPath}/${w}`}:{schema:Y[$],schemaPath:db._`${b.schemaPath}${(0,db.getProperty)(w)}${(0,db.getProperty)($)}`,errSchemaPath:`${b.errSchemaPath}/${w}/${(0,cX.escapeFragment)($)}`}}if(W!==void 0){if(Q===void 0||G===void 0||X===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:Q,topSchemaRef:X,errSchemaPath:G}}throw Error('either "keyword" or "schema" must be passed')}gX.getSubschema=fL;function cL(b,w,{dataProp:$,dataPropType:W,data:Q,dataTypes:G,propertyName:X}){if(Q!==void 0&&$!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:Y}=w;if($!==void 0){let{errorPath:J,dataPathArr:D,opts:z}=w,O=Y.let("data",db._`${w.data}${(0,db.getProperty)($)}`,!0);H(O),b.errorPath=db.str`${J}${(0,cX.getErrorPath)($,W,z.jsPropertySyntax)}`,b.parentDataProperty=db._`${$}`,b.dataPathArr=[...D,b.parentDataProperty]}if(Q!==void 0){let J=Q instanceof db.Name?Q:Y.let("data",Q,!0);if(H(J),X!==void 0)b.propertyName=X}if(G)b.dataTypes=G;function H(J){b.data=J,b.dataLevel=w.dataLevel+1,b.dataTypes=[],w.definedProperties=new Set,b.parentData=w.data,b.dataNames=[...w.dataNames,J]}}gX.extendSubschemaData=cL;function gL(b,{jtdDiscriminator:w,jtdMetadata:$,compositeRule:W,createErrors:Q,allErrors:G}){if(W!==void 0)b.compositeRule=W;if(Q!==void 0)b.createErrors=Q;if(G!==void 0)b.allErrors=G;b.jtdDiscriminator=w,b.jtdMetadata=$}gX.extendSubschemaMode=gL});var j6=I((uT,lX)=>{lX.exports=function b(w,$){if(w===$)return!0;if(w&&$&&typeof w=="object"&&typeof $=="object"){if(w.constructor!==$.constructor)return!1;var W,Q,G;if(Array.isArray(w)){if(W=w.length,W!=$.length)return!1;for(Q=W;Q--!==0;)if(!b(w[Q],$[Q]))return!1;return!0}if(w.constructor===RegExp)return w.source===$.source&&w.flags===$.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===$.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===$.toString();if(G=Object.keys(w),W=G.length,W!==Object.keys($).length)return!1;for(Q=W;Q--!==0;)if(!Object.prototype.hasOwnProperty.call($,G[Q]))return!1;for(Q=W;Q--!==0;){var X=G[Q];if(!b(w[X],$[X]))return!1}return!0}return w!==w&&$!==$}});var pX=I((yT,iX)=>{var Iw=iX.exports=function(b,w,$){if(typeof w=="function")$=w,w={};$=w.cb||$;var W=typeof $=="function"?$:$.pre||function(){},Q=$.post||function(){};X$(w,W,Q,b,"",b)};Iw.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Iw.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Iw.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Iw.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 X$(b,w,$,W,Q,G,X,Y,H,J){if(W&&typeof W=="object"&&!Array.isArray(W)){w(W,Q,G,X,Y,H,J);for(var D in W){var z=W[D];if(Array.isArray(z)){if(D in Iw.arrayKeywords)for(var O=0;O<z.length;O++)X$(b,w,$,z[O],Q+"/"+D+"/"+O,G,Q,D,W,O)}else if(D in Iw.propsKeywords){if(z&&typeof z=="object")for(var q in z)X$(b,w,$,z[q],Q+"/"+D+"/"+lL(q),G,Q,D,W,q)}else if(D in Iw.keywords||b.allKeys&&!(D in Iw.skipKeywords))X$(b,w,$,z,Q+"/"+D,G,Q,D,W)}$(W,Q,G,X,Y,H,J)}}function lL(b){return b.replace(/~/g,"~0").replace(/\//g,"~1")}});var m1=I((rX)=>{Object.defineProperty(rX,"__esModule",{value:!0});rX.getSchemaRefs=rX.resolveUrl=rX.normalizeId=rX._getFullPath=rX.getFullPath=rX.inlineRef=void 0;var iL=l(),pL=j6(),oL=pX(),dL=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function tL(b,w=!0){if(typeof b=="boolean")return!0;if(w===!0)return!I6(b);if(!w)return!1;return oX(b)<=w}rX.inlineRef=tL;var rL=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function I6(b){for(let w in b){if(rL.has(w))return!0;let $=b[w];if(Array.isArray($)&&$.some(I6))return!0;if(typeof $=="object"&&I6($))return!0}return!1}function oX(b){let w=0;for(let $ in b){if($==="$ref")return 1/0;if(w++,dL.has($))continue;if(typeof b[$]=="object")(0,iL.eachItem)(b[$],(W)=>w+=oX(W));if(w===1/0)return 1/0}return w}function dX(b,w="",$){if($!==!1)w=ew(w);let W=b.parse(w);return tX(b,W)}rX.getFullPath=dX;function tX(b,w){return b.serialize(w).split("#")[0]+"#"}rX._getFullPath=tX;var eL=/#\/?$/;function ew(b){return b?b.replace(eL,""):""}rX.normalizeId=ew;function sL(b,w,$){return $=ew($),b.resolve(w,$)}rX.resolveUrl=sL;var aL=/^[a-z_][-a-z0-9._]*$/i;function b3(b,w){if(typeof b=="boolean")return{};let{schemaId:$,uriResolver:W}=this.opts,Q=ew(b[$]||w),G={"":Q},X=dX(W,Q,!1),Y={},H=new Set;return oL(b,{allKeys:!0},(z,O,q,B)=>{if(B===void 0)return;let K=X+O,Z=G[B];if(typeof z[$]=="string")Z=M.call(this,z[$]);k.call(this,z.$anchor),k.call(this,z.$dynamicAnchor),G[O]=Z;function M(S){let h=this.opts.uriResolver.resolve;if(S=ew(Z?h(Z,S):S),H.has(S))throw D(S);H.add(S);let R=this.refs[S];if(typeof R=="string")R=this.refs[R];if(typeof R=="object")J(z,R.schema,S);else if(S!==ew(K))if(S[0]==="#")J(z,Y[S],S),Y[S]=z;else this.refs[S]=K;return S}function k(S){if(typeof S=="string"){if(!aL.test(S))throw Error(`invalid anchor "${S}"`);M.call(this,`#${S}`)}}}),Y;function J(z,O,q){if(O!==void 0&&!pL(z,O))throw D(q)}function D(z){return Error(`reference "${z}" resolves to more than one schema`)}}rX.getSchemaRefs=b3});var i1=I((AY)=>{Object.defineProperty(AY,"__esModule",{value:!0});AY.getData=AY.KeywordCxt=AY.validateFunctionCode=void 0;var $Y=LX(),sX=g1(),N6=U6(),Y$=g1(),X3=SX(),l1=fX(),V6=nX(),E=u(),v=Qw(),Y3=m1(),Gw=l(),n1=c1();function H3(b){if(GY(b)){if(XY(b),QY(b)){z3(b);return}}WY(b,()=>(0,$Y.topBoolOrEmptySchema)(b))}AY.validateFunctionCode=H3;function WY({gen:b,validateName:w,schema:$,schemaEnv:W,opts:Q},G){if(Q.code.es5)b.func(w,E._`${v.default.data}, ${v.default.valCxt}`,W.$async,()=>{b.code(E._`"use strict"; ${aX($,Q)}`),D3(b,Q),b.code(G)});else b.func(w,E._`${v.default.data}, ${J3(Q)}`,W.$async,()=>b.code(aX($,Q)).code(G))}function J3(b){return E._`{${v.default.instancePath}="", ${v.default.parentData}, ${v.default.parentDataProperty}, ${v.default.rootData}=${v.default.data}${b.dynamicRef?E._`, ${v.default.dynamicAnchors}={}`:E.nil}}={}`}function D3(b,w){b.if(v.default.valCxt,()=>{if(b.var(v.default.instancePath,E._`${v.default.valCxt}.${v.default.instancePath}`),b.var(v.default.parentData,E._`${v.default.valCxt}.${v.default.parentData}`),b.var(v.default.parentDataProperty,E._`${v.default.valCxt}.${v.default.parentDataProperty}`),b.var(v.default.rootData,E._`${v.default.valCxt}.${v.default.rootData}`),w.dynamicRef)b.var(v.default.dynamicAnchors,E._`${v.default.valCxt}.${v.default.dynamicAnchors}`)},()=>{if(b.var(v.default.instancePath,E._`""`),b.var(v.default.parentData,E._`undefined`),b.var(v.default.parentDataProperty,E._`undefined`),b.var(v.default.rootData,v.default.data),w.dynamicRef)b.var(v.default.dynamicAnchors,E._`{}`)})}function z3(b){let{schema:w,opts:$,gen:W}=b;WY(b,()=>{if($.$comment&&w.$comment)HY(b);if(U3(b),W.let(v.default.vErrors,null),W.let(v.default.errors,0),$.unevaluated)A3(b);YY(b),K3(b)});return}function A3(b){let{gen:w,validateName:$}=b;b.evaluated=w.const("evaluated",E._`${$}.evaluated`),w.if(E._`${b.evaluated}.dynamicProps`,()=>w.assign(E._`${b.evaluated}.props`,E._`undefined`)),w.if(E._`${b.evaluated}.dynamicItems`,()=>w.assign(E._`${b.evaluated}.items`,E._`undefined`))}function aX(b,w){let $=typeof b=="object"&&b[w.schemaId];return $&&(w.code.source||w.code.process)?E._`/*# sourceURL=${$} */`:E.nil}function O3(b,w){if(GY(b)){if(XY(b),QY(b)){q3(b,w);return}}(0,$Y.boolOrEmptySchema)(b,w)}function QY({schema:b,self:w}){if(typeof b=="boolean")return!b;for(let $ in b)if(w.RULES.all[$])return!0;return!1}function GY(b){return typeof b.schema!="boolean"}function q3(b,w){let{schema:$,gen:W,opts:Q}=b;if(Q.$comment&&$.$comment)HY(b);B3(b),F3(b);let G=W.const("_errs",v.default.errors);YY(b,G),W.var(w,E._`${G} === ${v.default.errors}`)}function XY(b){(0,Gw.checkUnknownRules)(b),L3(b)}function YY(b,w){if(b.opts.jtd)return bY(b,[],!1,w);let $=(0,sX.getSchemaTypes)(b.schema),W=(0,sX.coerceAndCheckDataType)(b,$);bY(b,$,!W,w)}function L3(b){let{schema:w,errSchemaPath:$,opts:W,self:Q}=b;if(w.$ref&&W.ignoreKeywordsWithRef&&(0,Gw.schemaHasRulesButRef)(w,Q.RULES))Q.logger.warn(`$ref: keywords ignored in schema at path "${$}"`)}function U3(b){let{schema:w,opts:$}=b;if(w.default!==void 0&&$.useDefaults&&$.strictSchema)(0,Gw.checkStrictMode)(b,"default is ignored in the schema root")}function B3(b){let w=b.schema[b.opts.schemaId];if(w)b.baseId=(0,Y3.resolveUrl)(b.opts.uriResolver,b.baseId,w)}function F3(b){if(b.schema.$async&&!b.schemaEnv.$async)throw Error("async schema in sync schema")}function HY({gen:b,schemaEnv:w,schema:$,errSchemaPath:W,opts:Q}){let G=$.$comment;if(Q.$comment===!0)b.code(E._`${v.default.self}.logger.log(${G})`);else if(typeof Q.$comment=="function"){let X=E.str`${W}/$comment`,Y=b.scopeValue("root",{ref:w.root});b.code(E._`${v.default.self}.opts.$comment(${G}, ${X}, ${Y}.schema)`)}}function K3(b){let{gen:w,schemaEnv:$,validateName:W,ValidationError:Q,opts:G}=b;if($.$async)w.if(E._`${v.default.errors} === 0`,()=>w.return(v.default.data),()=>w.throw(E._`new ${Q}(${v.default.vErrors})`));else{if(w.assign(E._`${W}.errors`,v.default.vErrors),G.unevaluated)P3(b);w.return(E._`${v.default.errors} === 0`)}}function P3({gen:b,evaluated:w,props:$,items:W}){if($ instanceof E.Name)b.assign(E._`${w}.props`,$);if(W instanceof E.Name)b.assign(E._`${w}.items`,W)}function bY(b,w,$,W){let{gen:Q,schema:G,data:X,allErrors:Y,opts:H,self:J}=b,{RULES:D}=J;if(G.$ref&&(H.ignoreKeywordsWithRef||!(0,Gw.schemaHasRulesButRef)(G,D))){Q.block(()=>DY(b,"$ref",D.all.$ref.definition));return}if(!H.jtd)M3(b,w);Q.block(()=>{for(let O of D.rules)z(O);z(D.post)});function z(O){if(!(0,N6.shouldUseGroup)(G,O))return;if(O.type){if(Q.if((0,Y$.checkDataType)(O.type,X,H.strictNumbers)),wY(b,O),w.length===1&&w[0]===O.type&&$)Q.else(),(0,Y$.reportTypeError)(b);Q.endIf()}else wY(b,O);if(!Y)Q.if(E._`${v.default.errors} === ${W||0}`)}}function wY(b,w){let{gen:$,schema:W,opts:{useDefaults:Q}}=b;if(Q)(0,X3.assignDefaults)(b,w.type);$.block(()=>{for(let G of w.rules)if((0,N6.shouldUseRule)(W,G))DY(b,G.keyword,G.definition,w.type)})}function M3(b,w){if(b.schemaEnv.meta||!b.opts.strictTypes)return;if(Z3(b,w),!b.opts.allowUnionTypes)j3(b,w);I3(b,b.dataTypes)}function Z3(b,w){if(!w.length)return;if(!b.dataTypes.length){b.dataTypes=w;return}w.forEach(($)=>{if(!JY(b.dataTypes,$))T6(b,`type "${$}" not allowed by context "${b.dataTypes.join(",")}"`)}),N3(b,w)}function j3(b,w){if(w.length>1&&!(w.length===2&&w.includes("null")))T6(b,"use allowUnionTypes to allow union type keyword")}function I3(b,w){let $=b.self.RULES.all;for(let W in $){let Q=$[W];if(typeof Q=="object"&&(0,N6.shouldUseRule)(b.schema,Q)){let{type:G}=Q.definition;if(G.length&&!G.some((X)=>V3(w,X)))T6(b,`missing type "${G.join(",")}" for keyword "${W}"`)}}}function V3(b,w){return b.includes(w)||w==="number"&&b.includes("integer")}function JY(b,w){return b.includes(w)||w==="integer"&&b.includes("number")}function N3(b,w){let $=[];for(let W of b.dataTypes)if(JY(w,W))$.push(W);else if(w.includes("integer")&&W==="number")$.push("integer");b.dataTypes=$}function T6(b,w){let $=b.schemaEnv.baseId+b.errSchemaPath;w+=` at "${$}" (strictTypes)`,(0,Gw.checkStrictMode)(b,w,b.opts.strictTypes)}class E6{constructor(b,w,$){if((0,l1.validateKeywordUsage)(b,w,$),this.gen=b.gen,this.allErrors=b.allErrors,this.keyword=$,this.data=b.data,this.schema=b.schema[$],this.$data=w.$data&&b.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Gw.schemaRefOrVal)(b,this.schema,$,this.$data),this.schemaType=w.schemaType,this.parentSchema=b.schema,this.params={},this.it=b,this.def=w,this.$data)this.schemaCode=b.gen.const("vSchema",zY(this.$data,b));else if(this.schemaCode=this.schemaValue,!(0,l1.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${$} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=b.gen.const("_errs",v.default.errors)}result(b,w,$){this.failResult((0,E.not)(b),w,$)}failResult(b,w,$){if(this.gen.if(b),$)$();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(b,w){this.failResult((0,E.not)(b),void 0,w)}fail(b){if(b===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(b),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(b){if(!this.$data)return this.fail(b);let{schemaCode:w}=this;this.fail(E._`${w} !== undefined && (${(0,E.or)(this.invalid$data(),b)})`)}error(b,w,$){if(w){this.setParams(w),this._error(b,$),this.setParams({});return}this._error(b,$)}_error(b,w){(b?n1.reportExtraError:n1.reportError)(this,this.def.error,w)}$dataError(){(0,n1.reportError)(this,this.def.$dataError||n1.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,n1.resetErrorsCount)(this.gen,this.errsCount)}ok(b){if(!this.allErrors)this.gen.if(b)}setParams(b,w){if(w)Object.assign(this.params,b);else this.params=b}block$data(b,w,$=E.nil){this.gen.block(()=>{this.check$data(b,$),w()})}check$data(b=E.nil,w=E.nil){if(!this.$data)return;let{gen:$,schemaCode:W,schemaType:Q,def:G}=this;if($.if((0,E.or)(E._`${W} === undefined`,w)),b!==E.nil)$.assign(b,!0);if(Q.length||G.validateSchema){if($.elseIf(this.invalid$data()),this.$dataError(),b!==E.nil)$.assign(b,!1)}$.else()}invalid$data(){let{gen:b,schemaCode:w,schemaType:$,def:W,it:Q}=this;return(0,E.or)(G(),X());function G(){if($.length){if(!(w instanceof E.Name))throw Error("ajv implementation error");let Y=Array.isArray($)?$:[$];return E._`${(0,Y$.checkDataTypes)(Y,w,Q.opts.strictNumbers,Y$.DataType.Wrong)}`}return E.nil}function X(){if(W.validateSchema){let Y=b.scopeValue("validate$data",{ref:W.validateSchema});return E._`!${Y}(${w})`}return E.nil}}subschema(b,w){let $=(0,V6.getSubschema)(this.it,b);(0,V6.extendSubschemaData)($,this.it,b),(0,V6.extendSubschemaMode)($,b);let W={...this.it,...$,items:void 0,props:void 0};return O3(W,w),W}mergeEvaluated(b,w){let{it:$,gen:W}=this;if(!$.opts.unevaluated)return;if($.props!==!0&&b.props!==void 0)$.props=Gw.mergeEvaluated.props(W,b.props,$.props,w);if($.items!==!0&&b.items!==void 0)$.items=Gw.mergeEvaluated.items(W,b.items,$.items,w)}mergeValidEvaluated(b,w){let{it:$,gen:W}=this;if($.opts.unevaluated&&($.props!==!0||$.items!==!0))return W.if(w,()=>this.mergeEvaluated(b,E.Name)),!0}}AY.KeywordCxt=E6;function DY(b,w,$,W){let Q=new E6(b,$,w);if("code"in $)$.code(Q,W);else if(Q.$data&&$.validate)(0,l1.funcKeywordCode)(Q,$);else if("macro"in $)(0,l1.macroKeywordCode)(Q,$);else if($.compile||$.validate)(0,l1.funcKeywordCode)(Q,$)}var T3=/^\/(?:[^~]|~0|~1)*$/,E3=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function zY(b,{dataLevel:w,dataNames:$,dataPathArr:W}){let Q,G;if(b==="")return v.default.rootData;if(b[0]==="/"){if(!T3.test(b))throw Error(`Invalid JSON-pointer: ${b}`);Q=b,G=v.default.rootData}else{let J=E3.exec(b);if(!J)throw Error(`Invalid JSON-pointer: ${b}`);let D=+J[1];if(Q=J[2],Q==="#"){if(D>=w)throw Error(H("property/index",D));return W[w-D]}if(D>w)throw Error(H("data",D));if(G=$[w-D],!Q)return G}let X=G,Y=Q.split("/");for(let J of Y)if(J)G=E._`${G}${(0,E.getProperty)((0,Gw.unescapeJsonPointer)(J))}`,X=E._`${X} && ${G}`;return X;function H(J,D){return`Cannot access ${J} ${D} levels up, current level is ${w}`}}AY.getData=zY});var H$=I((LY)=>{Object.defineProperty(LY,"__esModule",{value:!0});class qY extends Error{constructor(b){super("validation failed");this.errors=b,this.ajv=this.validation=!0}}LY.default=qY});var p1=I((BY)=>{Object.defineProperty(BY,"__esModule",{value:!0});var _6=m1();class UY extends Error{constructor(b,w,$,W){super(W||`can't resolve reference ${$} from id ${w}`);this.missingRef=(0,_6.resolveUrl)(b,w,$),this.missingSchema=(0,_6.normalizeId)((0,_6.getFullPath)(b,this.missingRef))}}BY.default=UY});var D$=I((PY)=>{Object.defineProperty(PY,"__esModule",{value:!0});PY.resolveSchema=PY.getCompilingSchema=PY.resolveRef=PY.compileSchema=PY.SchemaEnv=void 0;var fb=u(),v3=H$(),Cw=Qw(),cb=m1(),FY=l(),C3=i1();class o1{constructor(b){var w;this.refs={},this.dynamicAnchors={};let $;if(typeof b.schema=="object")$=b.schema;this.schema=b.schema,this.schemaId=b.schemaId,this.root=b.root||this,this.baseId=(w=b.baseId)!==null&&w!==void 0?w:(0,cb.normalizeId)($===null||$===void 0?void 0:$[b.schemaId||"$id"]),this.schemaPath=b.schemaPath,this.localRefs=b.localRefs,this.meta=b.meta,this.$async=$===null||$===void 0?void 0:$.$async,this.refs={}}}PY.SchemaEnv=o1;function R6(b){let w=KY.call(this,b);if(w)return w;let $=(0,cb.getFullPath)(this.opts.uriResolver,b.root.baseId),{es5:W,lines:Q}=this.opts.code,{ownProperties:G}=this.opts,X=new fb.CodeGen(this.scope,{es5:W,lines:Q,ownProperties:G}),Y;if(b.$async)Y=X.scopeValue("Error",{ref:v3.default,code:fb._`require("ajv/dist/runtime/validation_error").default`});let H=X.scopeName("validate");b.validateName=H;let J={gen:X,allErrors:this.opts.allErrors,data:Cw.default.data,parentData:Cw.default.parentData,parentDataProperty:Cw.default.parentDataProperty,dataNames:[Cw.default.data],dataPathArr:[fb.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:X.scopeValue("schema",this.opts.code.source===!0?{ref:b.schema,code:(0,fb.stringify)(b.schema)}:{ref:b.schema}),validateName:H,ValidationError:Y,schema:b.schema,schemaEnv:b,rootId:$,baseId:b.baseId||$,schemaPath:fb.nil,errSchemaPath:b.schemaPath||(this.opts.jtd?"":"#"),errorPath:fb._`""`,opts:this.opts,self:this},D;try{this._compilations.add(b),(0,C3.validateFunctionCode)(J),X.optimize(this.opts.code.optimize);let z=X.toString();if(D=`${X.scopeRefs(Cw.default.scope)}return ${z}`,this.opts.code.process)D=this.opts.code.process(D,b);let q=Function(`${Cw.default.self}`,`${Cw.default.scope}`,D)(this,this.scope.get());if(this.scope.value(H,{ref:q}),q.errors=null,q.schema=b.schema,q.schemaEnv=b,b.$async)q.$async=!0;if(this.opts.code.source===!0)q.source={validateName:H,validateCode:z,scopeValues:X._values};if(this.opts.unevaluated){let{props:B,items:K}=J;if(q.evaluated={props:B instanceof fb.Name?void 0:B,items:K instanceof fb.Name?void 0:K,dynamicProps:B instanceof fb.Name,dynamicItems:K instanceof fb.Name},q.source)q.source.evaluated=(0,fb.stringify)(q.evaluated)}return b.validate=q,b}catch(z){if(delete b.validate,delete b.validateName,D)this.logger.error("Error compiling schema, function code:",D);throw z}finally{this._compilations.delete(b)}}PY.compileSchema=R6;function x3(b,w,$){var W;$=(0,cb.resolveUrl)(this.opts.uriResolver,w,$);let Q=b.refs[$];if(Q)return Q;let G=h3.call(this,b,$);if(G===void 0){let X=(W=b.localRefs)===null||W===void 0?void 0:W[$],{schemaId:Y}=this.opts;if(X)G=new o1({schema:X,schemaId:Y,root:b,baseId:w})}if(G===void 0)return;return b.refs[$]=u3.call(this,G)}PY.resolveRef=x3;function u3(b){if((0,cb.inlineRef)(b.schema,this.opts.inlineRefs))return b.schema;return b.validate?b:R6.call(this,b)}function KY(b){for(let w of this._compilations)if(y3(w,b))return w}PY.getCompilingSchema=KY;function y3(b,w){return b.schema===w.schema&&b.root===w.root&&b.baseId===w.baseId}function h3(b,w){let $;while(typeof($=this.refs[w])=="string")w=$;return $||this.schemas[w]||J$.call(this,b,w)}function J$(b,w){let $=this.opts.uriResolver.parse(w),W=(0,cb._getFullPath)(this.opts.uriResolver,$),Q=(0,cb.getFullPath)(this.opts.uriResolver,b.baseId,void 0);if(Object.keys(b.schema).length>0&&W===Q)return S6.call(this,$,b);let G=(0,cb.normalizeId)(W),X=this.refs[G]||this.schemas[G];if(typeof X=="string"){let Y=J$.call(this,b,X);if(typeof(Y===null||Y===void 0?void 0:Y.schema)!=="object")return;return S6.call(this,$,Y)}if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;if(!X.validate)R6.call(this,X);if(G===(0,cb.normalizeId)(w)){let{schema:Y}=X,{schemaId:H}=this.opts,J=Y[H];if(J)Q=(0,cb.resolveUrl)(this.opts.uriResolver,Q,J);return new o1({schema:Y,schemaId:H,root:b,baseId:Q})}return S6.call(this,$,X)}PY.resolveSchema=J$;var f3=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function S6(b,{baseId:w,schema:$,root:W}){var Q;if(((Q=b.fragment)===null||Q===void 0?void 0:Q[0])!=="/")return;for(let Y of b.fragment.slice(1).split("/")){if(typeof $==="boolean")return;let H=$[(0,FY.unescapeFragment)(Y)];if(H===void 0)return;$=H;let J=typeof $==="object"&&$[this.opts.schemaId];if(!f3.has(Y)&&J)w=(0,cb.resolveUrl)(this.opts.uriResolver,w,J)}let G;if(typeof $!="boolean"&&$.$ref&&!(0,FY.schemaHasRulesButRef)($,this.RULES)){let Y=(0,cb.resolveUrl)(this.opts.uriResolver,w,$.$ref);G=J$.call(this,W,Y)}let{schemaId:X}=this.opts;if(G=G||new o1({schema:$,schemaId:X,root:W,baseId:w}),G.schema!==G.root.schema)return G;return}});var ZY=I((nT,l3)=>{l3.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 v6=I((lT,NY)=>{var i3=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),IY=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 k6(b){let w="",$=0,W=0;for(W=0;W<b.length;W++){if($=b[W].charCodeAt(0),$===48)continue;if(!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";w+=b[W];break}for(W+=1;W<b.length;W++){if($=b[W].charCodeAt(0),!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";w+=b[W]}return w}var p3=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function jY(b){return b.length=0,!0}function o3(b,w,$){if(b.length){let W=k6(b);if(W!=="")w.push(W);else return $.error=!0,!1;b.length=0}return!0}function d3(b){let w=0,$={error:!1,address:"",zone:""},W=[],Q=[],G=!1,X=!1,Y=o3;for(let H=0;H<b.length;H++){let J=b[H];if(J==="["||J==="]")continue;if(J===":"){if(G===!0)X=!0;if(!Y(Q,W,$))break;if(++w>7){$.error=!0;break}if(H>0&&b[H-1]===":")G=!0;W.push(":");continue}else if(J==="%"){if(!Y(Q,W,$))break;Y=jY}else{Q.push(J);continue}}if(Q.length)if(Y===jY)$.zone=Q.join("");else if(X)W.push(Q.join(""));else W.push(k6(Q));return $.address=W.join(""),$}function VY(b){if(t3(b,":")<2)return{host:b,isIPV6:!1};let w=d3(b);if(!w.error){let{address:$,address:W}=w;if(w.zone)$+="%"+w.zone,W+="%25"+w.zone;return{host:$,isIPV6:!0,escapedHost:W}}else return{host:b,isIPV6:!1}}function t3(b,w){let $=0;for(let W=0;W<b.length;W++)if(b[W]===w)$++;return $}function r3(b){let w=b,$=[],W=-1,Q=0;while(Q=w.length){if(Q===1)if(w===".")break;else if(w==="/"){$.push("/");break}else{$.push(w);break}else if(Q===2){if(w[0]==="."){if(w[1]===".")break;else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."||w[1]==="/"){$.push("/");break}}}else if(Q===3){if(w==="/.."){if($.length!==0)$.pop();$.push("/");break}}if(w[0]==="."){if(w[1]==="."){if(w[2]==="/"){w=w.slice(3);continue}}else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."){if(w[2]==="/"){w=w.slice(2);continue}else if(w[2]==="."){if(w[3]==="/"){if(w=w.slice(3),$.length!==0)$.pop();continue}}}}if((W=w.indexOf("/",1))===-1){$.push(w);break}else $.push(w.slice(0,W)),w=w.slice(W)}return $.join("")}function e3(b,w){let $=w!==!0?escape:unescape;if(b.scheme!==void 0)b.scheme=$(b.scheme);if(b.userinfo!==void 0)b.userinfo=$(b.userinfo);if(b.host!==void 0)b.host=$(b.host);if(b.path!==void 0)b.path=$(b.path);if(b.query!==void 0)b.query=$(b.query);if(b.fragment!==void 0)b.fragment=$(b.fragment);return b}function s3(b){let w=[];if(b.userinfo!==void 0)w.push(b.userinfo),w.push("@");if(b.host!==void 0){let $=unescape(b.host);if(!IY($)){let W=VY($);if(W.isIPV6===!0)$=`[${W.escapedHost}]`;else $=b.host}w.push($)}if(typeof b.port==="number"||typeof b.port==="string")w.push(":"),w.push(String(b.port));return w.length?w.join(""):void 0}NY.exports={nonSimpleDomain:p3,recomposeAuthority:s3,normalizeComponentEncoding:e3,removeDotSegments:r3,isIPv4:IY,isUUID:i3,normalizeIPv6:VY,stringArrayToHexStripped:k6}});var RY=I((iT,SY)=>{var{isUUID:a3}=v6(),bU=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,wU=["http","https","ws","wss","urn","urn:uuid"];function $U(b){return wU.indexOf(b)!==-1}function C6(b){if(b.secure===!0)return!0;else if(b.secure===!1)return!1;else if(b.scheme)return b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S");else return!1}function TY(b){if(!b.host)b.error=b.error||"HTTP URIs must have a host.";return b}function EY(b){let w=String(b.scheme).toLowerCase()==="https";if(b.port===(w?443:80)||b.port==="")b.port=void 0;if(!b.path)b.path="/";return b}function WU(b){return b.secure=C6(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function QU(b){if(b.port===(C6(b)?443:80)||b.port==="")b.port=void 0;if(typeof b.secure==="boolean")b.scheme=b.secure?"wss":"ws",b.secure=void 0;if(b.resourceName){let[w,$]=b.resourceName.split("?");b.path=w&&w!=="/"?w:void 0,b.query=$,b.resourceName=void 0}return b.fragment=void 0,b}function GU(b,w){if(!b.path)return b.error="URN can not be parsed",b;let $=b.path.match(bU);if($){let W=w.scheme||b.scheme||"urn";b.nid=$[1].toLowerCase(),b.nss=$[2];let Q=`${W}:${w.nid||b.nid}`,G=x6(Q);if(b.path=void 0,G)b=G.parse(b,w)}else b.error=b.error||"URN can not be parsed.";return b}function XU(b,w){if(b.nid===void 0)throw Error("URN without nid cannot be serialized");let $=w.scheme||b.scheme||"urn",W=b.nid.toLowerCase(),Q=`${$}:${w.nid||W}`,G=x6(Q);if(G)b=G.serialize(b,w);let X=b,Y=b.nss;return X.path=`${W||w.nid}:${Y}`,w.skipEscape=!0,X}function YU(b,w){let $=b;if($.uuid=$.nss,$.nss=void 0,!w.tolerant&&(!$.uuid||!a3($.uuid)))$.error=$.error||"UUID is not valid.";return $}function HU(b){let w=b;return w.nss=(b.uuid||"").toLowerCase(),w}var _Y={scheme:"http",domainHost:!0,parse:TY,serialize:EY},JU={scheme:"https",domainHost:_Y.domainHost,parse:TY,serialize:EY},z$={scheme:"ws",domainHost:!0,parse:WU,serialize:QU},DU={scheme:"wss",domainHost:z$.domainHost,parse:z$.parse,serialize:z$.serialize},zU={scheme:"urn",parse:GU,serialize:XU,skipNormalize:!0},AU={scheme:"urn:uuid",parse:YU,serialize:HU,skipNormalize:!0},A$={http:_Y,https:JU,ws:z$,wss:DU,urn:zU,"urn:uuid":AU};Object.setPrototypeOf(A$,null);function x6(b){return b&&(A$[b]||A$[b.toLowerCase()])||void 0}SY.exports={wsIsSecure:C6,SCHEMES:A$,isValidSchemeName:$U,getSchemeHandler:x6}});var CY=I((pT,q$)=>{var{normalizeIPv6:OU,removeDotSegments:d1,recomposeAuthority:qU,normalizeComponentEncoding:O$,isIPv4:LU,nonSimpleDomain:UU}=v6(),{SCHEMES:BU,getSchemeHandler:kY}=RY();function FU(b,w){if(typeof b==="string")b=tb(Xw(b,w),w);else if(typeof b==="object")b=Xw(tb(b,w),w);return b}function KU(b,w,$){let W=$?Object.assign({scheme:"null"},$):{scheme:"null"},Q=vY(Xw(b,W),Xw(w,W),W,!0);return W.skipEscape=!0,tb(Q,W)}function vY(b,w,$,W){let Q={};if(!W)b=Xw(tb(b,$),$),w=Xw(tb(w,$),$);if($=$||{},!$.tolerant&&w.scheme)Q.scheme=w.scheme,Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port,Q.path=d1(w.path||""),Q.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port,Q.path=d1(w.path||""),Q.query=w.query;else{if(!w.path)if(Q.path=b.path,w.query!==void 0)Q.query=w.query;else Q.query=b.query;else{if(w.path[0]==="/")Q.path=d1(w.path);else{if((b.userinfo!==void 0||b.host!==void 0||b.port!==void 0)&&!b.path)Q.path="/"+w.path;else if(!b.path)Q.path=w.path;else Q.path=b.path.slice(0,b.path.lastIndexOf("/")+1)+w.path;Q.path=d1(Q.path)}Q.query=w.query}Q.userinfo=b.userinfo,Q.host=b.host,Q.port=b.port}Q.scheme=b.scheme}return Q.fragment=w.fragment,Q}function PU(b,w,$){if(typeof b==="string")b=unescape(b),b=tb(O$(Xw(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=tb(O$(b,!0),{...$,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=tb(O$(Xw(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=tb(O$(w,!0),{...$,skipEscape:!0});return b.toLowerCase()===w.toLowerCase()}function tb(b,w){let $={host:b.host,scheme:b.scheme,userinfo:b.userinfo,port:b.port,path:b.path,query:b.query,nid:b.nid,nss:b.nss,uuid:b.uuid,fragment:b.fragment,reference:b.reference,resourceName:b.resourceName,secure:b.secure,error:""},W=Object.assign({},w),Q=[],G=kY(W.scheme||$.scheme);if(G&&G.serialize)G.serialize($,W);if($.path!==void 0)if(!W.skipEscape){if($.path=escape($.path),$.scheme!==void 0)$.path=$.path.split("%3A").join(":")}else $.path=unescape($.path);if(W.reference!=="suffix"&&$.scheme)Q.push($.scheme,":");let X=qU($);if(X!==void 0){if(W.reference!=="suffix")Q.push("//");if(Q.push(X),$.path&&$.path[0]!=="/")Q.push("/")}if($.path!==void 0){let Y=$.path;if(!W.absolutePath&&(!G||!G.absolutePath))Y=d1(Y);if(X===void 0&&Y[0]==="/"&&Y[1]==="/")Y="/%2F"+Y.slice(2);Q.push(Y)}if($.query!==void 0)Q.push("?",$.query);if($.fragment!==void 0)Q.push("#",$.fragment);return Q.join("")}var MU=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Xw(b,w){let $=Object.assign({},w),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},Q=!1;if($.reference==="suffix")if($.scheme)b=$.scheme+":"+b;else b="//"+b;let G=b.match(MU);if(G){if(W.scheme=G[1],W.userinfo=G[3],W.host=G[4],W.port=parseInt(G[5],10),W.path=G[6]||"",W.query=G[7],W.fragment=G[8],isNaN(W.port))W.port=G[5];if(W.host)if(LU(W.host)===!1){let H=OU(W.host);W.host=H.host.toLowerCase(),Q=H.isIPV6}else Q=!0;if(W.scheme===void 0&&W.userinfo===void 0&&W.host===void 0&&W.port===void 0&&W.query===void 0&&!W.path)W.reference="same-document";else if(W.scheme===void 0)W.reference="relative";else if(W.fragment===void 0)W.reference="absolute";else W.reference="uri";if($.reference&&$.reference!=="suffix"&&$.reference!==W.reference)W.error=W.error||"URI is not a "+$.reference+" reference.";let X=kY($.scheme||W.scheme);if(!$.unicodeSupport&&(!X||!X.unicodeSupport)){if(W.host&&($.domainHost||X&&X.domainHost)&&Q===!1&&UU(W.host))try{W.host=URL.domainToASCII(W.host.toLowerCase())}catch(Y){W.error=W.error||"Host's domain name can not be converted to ASCII: "+Y}}if(!X||X&&!X.skipNormalize){if(b.indexOf("%")!==-1){if(W.scheme!==void 0)W.scheme=unescape(W.scheme);if(W.host!==void 0)W.host=unescape(W.host)}if(W.path)W.path=escape(unescape(W.path));if(W.fragment)W.fragment=encodeURI(decodeURIComponent(W.fragment))}if(X&&X.parse)X.parse(W,$)}else W.error=W.error||"URI can not be parsed.";return W}var u6={SCHEMES:BU,normalize:FU,resolve:KU,resolveComponent:vY,equal:PU,serialize:tb,parse:Xw};q$.exports=u6;q$.exports.default=u6;q$.exports.fastUri=u6});var yY=I((uY)=>{Object.defineProperty(uY,"__esModule",{value:!0});var xY=CY();xY.code='require("ajv/dist/runtime/uri").default';uY.default=xY});var iY=I((Yw)=>{Object.defineProperty(Yw,"__esModule",{value:!0});Yw.CodeGen=Yw.Name=Yw.nil=Yw.stringify=Yw.str=Yw._=Yw.KeywordCxt=void 0;var jU=i1();Object.defineProperty(Yw,"KeywordCxt",{enumerable:!0,get:function(){return jU.KeywordCxt}});var sw=u();Object.defineProperty(Yw,"_",{enumerable:!0,get:function(){return sw._}});Object.defineProperty(Yw,"str",{enumerable:!0,get:function(){return sw.str}});Object.defineProperty(Yw,"stringify",{enumerable:!0,get:function(){return sw.stringify}});Object.defineProperty(Yw,"nil",{enumerable:!0,get:function(){return sw.nil}});Object.defineProperty(Yw,"Name",{enumerable:!0,get:function(){return sw.Name}});Object.defineProperty(Yw,"CodeGen",{enumerable:!0,get:function(){return sw.CodeGen}});var IU=H$(),mY=p1(),VU=L6(),t1=D$(),NU=u(),r1=m1(),L$=g1(),h6=l(),hY=ZY(),TU=yY(),nY=(b,w)=>new RegExp(b,w);nY.code="new RegExp";var EU=["removeAdditional","useDefaults","coerceTypes"],_U=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),SU={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."},RU={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},fY=200;function kU(b){var w,$,W,Q,G,X,Y,H,J,D,z,O,q,B,K,Z,M,k,S,h,R,pb,sb,i$,p$;let D1=b.strict,o$=(w=b.code)===null||w===void 0?void 0:w.optimize,_W=o$===!0||o$===void 0?1:o$||0,SW=(W=($=b.code)===null||$===void 0?void 0:$.regExp)!==null&&W!==void 0?W:nY,Sz=(Q=b.uriResolver)!==null&&Q!==void 0?Q:TU.default;return{strictSchema:(X=(G=b.strictSchema)!==null&&G!==void 0?G:D1)!==null&&X!==void 0?X:!0,strictNumbers:(H=(Y=b.strictNumbers)!==null&&Y!==void 0?Y:D1)!==null&&H!==void 0?H:!0,strictTypes:(D=(J=b.strictTypes)!==null&&J!==void 0?J:D1)!==null&&D!==void 0?D:"log",strictTuples:(O=(z=b.strictTuples)!==null&&z!==void 0?z:D1)!==null&&O!==void 0?O:"log",strictRequired:(B=(q=b.strictRequired)!==null&&q!==void 0?q:D1)!==null&&B!==void 0?B:!1,code:b.code?{...b.code,optimize:_W,regExp:SW}:{optimize:_W,regExp:SW},loopRequired:(K=b.loopRequired)!==null&&K!==void 0?K:fY,loopEnum:(Z=b.loopEnum)!==null&&Z!==void 0?Z:fY,meta:(M=b.meta)!==null&&M!==void 0?M:!0,messages:(k=b.messages)!==null&&k!==void 0?k:!0,inlineRefs:(S=b.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(h=b.schemaId)!==null&&h!==void 0?h:"$id",addUsedSchema:(R=b.addUsedSchema)!==null&&R!==void 0?R:!0,validateSchema:(pb=b.validateSchema)!==null&&pb!==void 0?pb:!0,validateFormats:(sb=b.validateFormats)!==null&&sb!==void 0?sb:!0,unicodeRegExp:(i$=b.unicodeRegExp)!==null&&i$!==void 0?i$:!0,int32range:(p$=b.int32range)!==null&&p$!==void 0?p$:!0,uriResolver:Sz}}class U${constructor(b={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,b=this.opts={...b,...kU(b)};let{es5:w,lines:$}=this.opts.code;this.scope=new NU.ValueScope({scope:{},prefixes:_U,es5:w,lines:$}),this.logger=hU(b.logger);let W=b.validateFormats;if(b.validateFormats=!1,this.RULES=(0,VU.getRules)(),cY.call(this,SU,b,"NOT SUPPORTED"),cY.call(this,RU,b,"DEPRECATED","warn"),this._metaOpts=uU.call(this),b.formats)CU.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),b.keywords)xU.call(this,b.keywords);if(typeof b.meta=="object")this.addMetaSchema(b.meta);vU.call(this),b.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:b,meta:w,schemaId:$}=this.opts,W=hY;if($==="id")W={...hY},W.id=W.$id,delete W.$id;if(w&&b)this.addMetaSchema(W,W[$],!1)}defaultMeta(){let{meta:b,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof b=="object"?b[w]||b:void 0}validate(b,w){let $;if(typeof b=="string"){if($=this.getSchema(b),!$)throw Error(`no schema with key or ref "${b}"`)}else $=this.compile(b);let W=$(w);if(!("$async"in $))this.errors=$.errors;return W}compile(b,w){let $=this._addSchema(b,w);return $.validate||this._compileSchemaEnv($)}compileAsync(b,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:$}=this.opts;return W.call(this,b,w);async function W(J,D){await Q.call(this,J.$schema);let z=this._addSchema(J,D);return z.validate||G.call(this,z)}async function Q(J){if(J&&!this.getSchema(J))await W.call(this,{$ref:J},!0)}async function G(J){try{return this._compileSchemaEnv(J)}catch(D){if(!(D instanceof mY.default))throw D;return X.call(this,D),await Y.call(this,D.missingSchema),G.call(this,J)}}function X({missingSchema:J,missingRef:D}){if(this.refs[J])throw Error(`AnySchema ${J} is loaded but ${D} cannot be resolved`)}async function Y(J){let D=await H.call(this,J);if(!this.refs[J])await Q.call(this,D.$schema);if(!this.refs[J])this.addSchema(D,J,w)}async function H(J){let D=this._loading[J];if(D)return D;try{return await(this._loading[J]=$(J))}finally{delete this._loading[J]}}}addSchema(b,w,$,W=this.opts.validateSchema){if(Array.isArray(b)){for(let G of b)this.addSchema(G,void 0,$,W);return this}let Q;if(typeof b==="object"){let{schemaId:G}=this.opts;if(Q=b[G],Q!==void 0&&typeof Q!="string")throw Error(`schema ${G} must be string`)}return w=(0,r1.normalizeId)(w||Q),this._checkUnique(w),this.schemas[w]=this._addSchema(b,$,w,W,!0),this}addMetaSchema(b,w,$=this.opts.validateSchema){return this.addSchema(b,w,!0,$),this}validateSchema(b,w){if(typeof b=="boolean")return!0;let $;if($=b.$schema,$!==void 0&&typeof $!="string")throw Error("$schema must be a string");if($=$||this.opts.defaultMeta||this.defaultMeta(),!$)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate($,b);if(!W&&w){let Q="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(Q);else throw Error(Q)}return W}getSchema(b){let w;while(typeof(w=gY.call(this,b))=="string")b=w;if(w===void 0){let{schemaId:$}=this.opts,W=new t1.SchemaEnv({schema:{},schemaId:$});if(w=t1.resolveSchema.call(this,W,b),!w)return;this.refs[b]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema(b){if(b instanceof RegExp)return this._removeAllSchemas(this.schemas,b),this._removeAllSchemas(this.refs,b),this;switch(typeof b){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=gY.call(this,b);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[b],delete this.refs[b],this}case"object":{let w=b;this._cache.delete(w);let $=b[this.opts.schemaId];if($)$=(0,r1.normalizeId)($),delete this.schemas[$],delete this.refs[$];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(b){for(let w of b)this.addKeyword(w);return this}addKeyword(b,w){let $;if(typeof b=="string"){if($=b,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=$}else if(typeof b=="object"&&w===void 0){if(w=b,$=w.keyword,Array.isArray($)&&!$.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(cU.call(this,$,w),!w)return(0,h6.eachItem)($,(Q)=>y6.call(this,Q)),this;mU.call(this,w);let W={...w,type:(0,L$.getJSONTypes)(w.type),schemaType:(0,L$.getJSONTypes)(w.schemaType)};return(0,h6.eachItem)($,W.type.length===0?(Q)=>y6.call(this,Q,W):(Q)=>W.type.forEach((G)=>y6.call(this,Q,W,G))),this}getKeyword(b){let w=this.RULES.all[b];return typeof w=="object"?w.definition:!!w}removeKeyword(b){let{RULES:w}=this;delete w.keywords[b],delete w.all[b];for(let $ of w.rules){let W=$.rules.findIndex((Q)=>Q.keyword===b);if(W>=0)$.rules.splice(W,1)}return this}addFormat(b,w){if(typeof w=="string")w=new RegExp(w);return this.formats[b]=w,this}errorsText(b=this.errors,{separator:w=", ",dataVar:$="data"}={}){if(!b||b.length===0)return"No errors";return b.map((W)=>`${$}${W.instancePath} ${W.message}`).reduce((W,Q)=>W+w+Q)}$dataMetaSchema(b,w){let $=this.RULES.all;b=JSON.parse(JSON.stringify(b));for(let W of w){let Q=W.split("/").slice(1),G=b;for(let X of Q)G=G[X];for(let X in $){let Y=$[X];if(typeof Y!="object")continue;let{$data:H}=Y.definition,J=G[X];if(H&&J)G[X]=lY(J)}}return b}_removeAllSchemas(b,w){for(let $ in b){let W=b[$];if(!w||w.test($)){if(typeof W=="string")delete b[$];else if(W&&!W.meta)this._cache.delete(W.schema),delete b[$]}}}_addSchema(b,w,$,W=this.opts.validateSchema,Q=this.opts.addUsedSchema){let G,{schemaId:X}=this.opts;if(typeof b=="object")G=b[X];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof b!="boolean")throw Error("schema must be object or boolean");let Y=this._cache.get(b);if(Y!==void 0)return Y;$=(0,r1.normalizeId)(G||$);let H=r1.getSchemaRefs.call(this,b,$);if(Y=new t1.SchemaEnv({schema:b,schemaId:X,meta:w,baseId:$,localRefs:H}),this._cache.set(Y.schema,Y),Q&&!$.startsWith("#")){if($)this._checkUnique($);this.refs[$]=Y}if(W)this.validateSchema(b,!0);return Y}_checkUnique(b){if(this.schemas[b]||this.refs[b])throw Error(`schema with key or id "${b}" already exists`)}_compileSchemaEnv(b){if(b.meta)this._compileMetaSchema(b);else t1.compileSchema.call(this,b);if(!b.validate)throw Error("ajv implementation error");return b.validate}_compileMetaSchema(b){let w=this.opts;this.opts=this._metaOpts;try{t1.compileSchema.call(this,b)}finally{this.opts=w}}}U$.ValidationError=IU.default;U$.MissingRefError=mY.default;Yw.default=U$;function cY(b,w,$,W="error"){for(let Q in b){let G=Q;if(G in w)this.logger[W](`${$}: option ${Q}. ${b[G]}`)}}function gY(b){return b=(0,r1.normalizeId)(b),this.schemas[b]||this.refs[b]}function vU(){let b=this.opts.schemas;if(!b)return;if(Array.isArray(b))this.addSchema(b);else for(let w in b)this.addSchema(b[w],w)}function CU(){for(let b in this.opts.formats){let w=this.opts.formats[b];if(w)this.addFormat(b,w)}}function xU(b){if(Array.isArray(b)){this.addVocabulary(b);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in b){let $=b[w];if(!$.keyword)$.keyword=w;this.addKeyword($)}}function uU(){let b={...this.opts};for(let w of EU)delete b[w];return b}var yU={log(){},warn(){},error(){}};function hU(b){if(b===!1)return yU;if(b===void 0)return console;if(b.log&&b.warn&&b.error)return b;throw Error("logger must implement log, warn and error methods")}var fU=/^[a-z_$][a-z0-9_$:-]*$/i;function cU(b,w){let{RULES:$}=this;if((0,h6.eachItem)(b,(W)=>{if($.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!fU.test(W))throw Error(`Keyword ${W} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function y6(b,w,$){var W;let Q=w===null||w===void 0?void 0:w.post;if($&&Q)throw Error('keyword with "post" flag cannot have "type"');let{RULES:G}=this,X=Q?G.post:G.rules.find(({type:H})=>H===$);if(!X)X={type:$,rules:[]},G.rules.push(X);if(G.keywords[b]=!0,!w)return;let Y={keyword:b,definition:{...w,type:(0,L$.getJSONTypes)(w.type),schemaType:(0,L$.getJSONTypes)(w.schemaType)}};if(w.before)gU.call(this,X,Y,w.before);else X.rules.push(Y);G.all[b]=Y,(W=w.implements)===null||W===void 0||W.forEach((H)=>this.addKeyword(H))}function gU(b,w,$){let W=b.rules.findIndex((Q)=>Q.keyword===$);if(W>=0)b.rules.splice(W,0,w);else b.rules.push(w),this.logger.warn(`rule ${$} is not defined`)}function mU(b){let{metaSchema:w}=b;if(w===void 0)return;if(b.$data&&this.opts.$data)w=lY(w);b.validateSchema=this.compile(w,!0)}var nU={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function lY(b){return{anyOf:[b,nU]}}});var oY=I((pY)=>{Object.defineProperty(pY,"__esModule",{value:!0});var pU={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};pY.default=pU});var aY=I((eY)=>{Object.defineProperty(eY,"__esModule",{value:!0});eY.callRef=eY.getValidate=void 0;var dU=p1(),dY=vb(),jb=u(),aw=Qw(),tY=D$(),B$=l(),tU={keyword:"$ref",schemaType:"string",code(b){let{gen:w,schema:$,it:W}=b,{baseId:Q,schemaEnv:G,validateName:X,opts:Y,self:H}=W,{root:J}=G;if(($==="#"||$==="#/")&&Q===J.baseId)return z();let D=tY.resolveRef.call(H,J,Q,$);if(D===void 0)throw new dU.default(W.opts.uriResolver,Q,$);if(D instanceof tY.SchemaEnv)return O(D);return q(D);function z(){if(G===J)return F$(b,X,G,G.$async);let B=w.scopeValue("root",{ref:J});return F$(b,jb._`${B}.validate`,J,J.$async)}function O(B){let K=rY(b,B);F$(b,K,B,B.$async)}function q(B){let K=w.scopeValue("schema",Y.code.source===!0?{ref:B,code:(0,jb.stringify)(B)}:{ref:B}),Z=w.name("valid"),M=b.subschema({schema:B,dataTypes:[],schemaPath:jb.nil,topSchemaRef:K,errSchemaPath:$},Z);b.mergeEvaluated(M),b.ok(Z)}}};function rY(b,w){let{gen:$}=b;return w.validate?$.scopeValue("validate",{ref:w.validate}):jb._`${$.scopeValue("wrapper",{ref:w})}.validate`}eY.getValidate=rY;function F$(b,w,$,W){let{gen:Q,it:G}=b,{allErrors:X,schemaEnv:Y,opts:H}=G,J=H.passContext?aw.default.this:jb.nil;if(W)D();else z();function D(){if(!Y.$async)throw Error("async schema referenced by sync schema");let B=Q.let("valid");Q.try(()=>{if(Q.code(jb._`await ${(0,dY.callValidateCode)(b,w,J)}`),q(w),!X)Q.assign(B,!0)},(K)=>{if(Q.if(jb._`!(${K} instanceof ${G.ValidationError})`,()=>Q.throw(K)),O(K),!X)Q.assign(B,!1)}),b.ok(B)}function z(){b.result((0,dY.callValidateCode)(b,w,J),()=>q(w),()=>O(w))}function O(B){let K=jb._`${B}.errors`;Q.assign(aw.default.vErrors,jb._`${aw.default.vErrors} === null ? ${K} : ${aw.default.vErrors}.concat(${K})`),Q.assign(aw.default.errors,jb._`${aw.default.vErrors}.length`)}function q(B){var K;if(!G.opts.unevaluated)return;let Z=(K=$===null||$===void 0?void 0:$.validate)===null||K===void 0?void 0:K.evaluated;if(G.props!==!0)if(Z&&!Z.dynamicProps){if(Z.props!==void 0)G.props=B$.mergeEvaluated.props(Q,Z.props,G.props)}else{let M=Q.var("props",jb._`${B}.evaluated.props`);G.props=B$.mergeEvaluated.props(Q,M,G.props,jb.Name)}if(G.items!==!0)if(Z&&!Z.dynamicItems){if(Z.items!==void 0)G.items=B$.mergeEvaluated.items(Q,Z.items,G.items)}else{let M=Q.var("items",jb._`${B}.evaluated.items`);G.items=B$.mergeEvaluated.items(Q,M,G.items,jb.Name)}}}eY.callRef=F$;eY.default=tU});var wH=I((bH)=>{Object.defineProperty(bH,"__esModule",{value:!0});var sU=oY(),aU=aY(),bB=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",sU.default,aU.default];bH.default=bB});var WH=I(($H)=>{Object.defineProperty($H,"__esModule",{value:!0});var K$=u(),Vw=K$.operators,P$={maximum:{okStr:"<=",ok:Vw.LTE,fail:Vw.GT},minimum:{okStr:">=",ok:Vw.GTE,fail:Vw.LT},exclusiveMaximum:{okStr:"<",ok:Vw.LT,fail:Vw.GTE},exclusiveMinimum:{okStr:">",ok:Vw.GT,fail:Vw.LTE}},$B={message:({keyword:b,schemaCode:w})=>K$.str`must be ${P$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>K$._`{comparison: ${P$[b].okStr}, limit: ${w}}`},WB={keyword:Object.keys(P$),type:"number",schemaType:"number",$data:!0,error:$B,code(b){let{keyword:w,data:$,schemaCode:W}=b;b.fail$data(K$._`${$} ${P$[w].fail} ${W} || isNaN(${$})`)}};$H.default=WB});var GH=I((QH)=>{Object.defineProperty(QH,"__esModule",{value:!0});var e1=u(),GB={message:({schemaCode:b})=>e1.str`must be multiple of ${b}`,params:({schemaCode:b})=>e1._`{multipleOf: ${b}}`},XB={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:GB,code(b){let{gen:w,data:$,schemaCode:W,it:Q}=b,G=Q.opts.multipleOfPrecision,X=w.let("res"),Y=G?e1._`Math.abs(Math.round(${X}) - ${X}) > 1e-${G}`:e1._`${X} !== parseInt(${X})`;b.fail$data(e1._`(${W} === 0 || (${X} = ${$}/${W}, ${Y}))`)}};QH.default=XB});var HH=I((YH)=>{Object.defineProperty(YH,"__esModule",{value:!0});function XH(b){let w=b.length,$=0,W=0,Q;while(W<w)if($++,Q=b.charCodeAt(W++),Q>=55296&&Q<=56319&&W<w){if(Q=b.charCodeAt(W),(Q&64512)===56320)W++}return $}YH.default=XH;XH.code='require("ajv/dist/runtime/ucs2length").default'});var DH=I((JH)=>{Object.defineProperty(JH,"__esModule",{value:!0});var xw=u(),JB=l(),DB=HH(),zB={message({keyword:b,schemaCode:w}){let $=b==="maxLength"?"more":"fewer";return xw.str`must NOT have ${$} than ${w} characters`},params:({schemaCode:b})=>xw._`{limit: ${b}}`},AB={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:zB,code(b){let{keyword:w,data:$,schemaCode:W,it:Q}=b,G=w==="maxLength"?xw.operators.GT:xw.operators.LT,X=Q.opts.unicode===!1?xw._`${$}.length`:xw._`${(0,JB.useFunc)(b.gen,DB.default)}(${$})`;b.fail$data(xw._`${X} ${G} ${W}`)}};JH.default=AB});var AH=I((zH)=>{Object.defineProperty(zH,"__esModule",{value:!0});var qB=vb(),M$=u(),LB={message:({schemaCode:b})=>M$.str`must match pattern "${b}"`,params:({schemaCode:b})=>M$._`{pattern: ${b}}`},UB={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:LB,code(b){let{data:w,$data:$,schema:W,schemaCode:Q,it:G}=b,X=G.opts.unicodeRegExp?"u":"",Y=$?M$._`(new RegExp(${Q}, ${X}))`:(0,qB.usePattern)(b,W);b.fail$data(M$._`!${Y}.test(${w})`)}};zH.default=UB});var qH=I((OH)=>{Object.defineProperty(OH,"__esModule",{value:!0});var s1=u(),FB={message({keyword:b,schemaCode:w}){let $=b==="maxProperties"?"more":"fewer";return s1.str`must NOT have ${$} than ${w} properties`},params:({schemaCode:b})=>s1._`{limit: ${b}}`},KB={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:FB,code(b){let{keyword:w,data:$,schemaCode:W}=b,Q=w==="maxProperties"?s1.operators.GT:s1.operators.LT;b.fail$data(s1._`Object.keys(${$}).length ${Q} ${W}`)}};OH.default=KB});var UH=I((LH)=>{Object.defineProperty(LH,"__esModule",{value:!0});var a1=vb(),b0=u(),MB=l(),ZB={message:({params:{missingProperty:b}})=>b0.str`must have required property '${b}'`,params:({params:{missingProperty:b}})=>b0._`{missingProperty: ${b}}`},jB={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ZB,code(b){let{gen:w,schema:$,schemaCode:W,data:Q,$data:G,it:X}=b,{opts:Y}=X;if(!G&&$.length===0)return;let H=$.length>=Y.loopRequired;if(X.allErrors)J();else D();if(Y.strictRequired){let q=b.parentSchema.properties,{definedProperties:B}=b.it;for(let K of $)if((q===null||q===void 0?void 0:q[K])===void 0&&!B.has(K)){let Z=X.schemaEnv.baseId+X.errSchemaPath,M=`required property "${K}" is not defined at "${Z}" (strictRequired)`;(0,MB.checkStrictMode)(X,M,X.opts.strictRequired)}}function J(){if(H||G)b.block$data(b0.nil,z);else for(let q of $)(0,a1.checkReportMissingProp)(b,q)}function D(){let q=w.let("missing");if(H||G){let B=w.let("valid",!0);b.block$data(B,()=>O(q,B)),b.ok(B)}else w.if((0,a1.checkMissingProp)(b,$,q)),(0,a1.reportMissingProp)(b,q),w.else()}function z(){w.forOf("prop",W,(q)=>{b.setParams({missingProperty:q}),w.if((0,a1.noPropertyInData)(w,Q,q,Y.ownProperties),()=>b.error())})}function O(q,B){b.setParams({missingProperty:q}),w.forOf(q,W,()=>{w.assign(B,(0,a1.propertyInData)(w,Q,q,Y.ownProperties)),w.if((0,b0.not)(B),()=>{b.error(),w.break()})},b0.nil)}}};LH.default=jB});var FH=I((BH)=>{Object.defineProperty(BH,"__esModule",{value:!0});var w0=u(),VB={message({keyword:b,schemaCode:w}){let $=b==="maxItems"?"more":"fewer";return w0.str`must NOT have ${$} than ${w} items`},params:({schemaCode:b})=>w0._`{limit: ${b}}`},NB={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:VB,code(b){let{keyword:w,data:$,schemaCode:W}=b,Q=w==="maxItems"?w0.operators.GT:w0.operators.LT;b.fail$data(w0._`${$}.length ${Q} ${W}`)}};BH.default=NB});var Z$=I((PH)=>{Object.defineProperty(PH,"__esModule",{value:!0});var KH=j6();KH.code='require("ajv/dist/runtime/equal").default';PH.default=KH});var ZH=I((MH)=>{Object.defineProperty(MH,"__esModule",{value:!0});var f6=g1(),qb=u(),_B=l(),SB=Z$(),RB={message:({params:{i:b,j:w}})=>qb.str`must NOT have duplicate items (items ## ${w} and ${b} are identical)`,params:({params:{i:b,j:w}})=>qb._`{i: ${b}, j: ${w}}`},kB={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:RB,code(b){let{gen:w,data:$,$data:W,schema:Q,parentSchema:G,schemaCode:X,it:Y}=b;if(!W&&!Q)return;let H=w.let("valid"),J=G.items?(0,f6.getSchemaTypes)(G.items):[];b.block$data(H,D,qb._`${X} === false`),b.ok(H);function D(){let B=w.let("i",qb._`${$}.length`),K=w.let("j");b.setParams({i:B,j:K}),w.assign(H,!0),w.if(qb._`${B} > 1`,()=>(z()?O:q)(B,K))}function z(){return J.length>0&&!J.some((B)=>B==="object"||B==="array")}function O(B,K){let Z=w.name("item"),M=(0,f6.checkDataTypes)(J,Z,Y.opts.strictNumbers,f6.DataType.Wrong),k=w.const("indices",qb._`{}`);w.for(qb._`;${B}--;`,()=>{if(w.let(Z,qb._`${$}[${B}]`),w.if(M,qb._`continue`),J.length>1)w.if(qb._`typeof ${Z} == "string"`,qb._`${Z} += "_"`);w.if(qb._`typeof ${k}[${Z}] == "number"`,()=>{w.assign(K,qb._`${k}[${Z}]`),b.error(),w.assign(H,!1).break()}).code(qb._`${k}[${Z}] = ${B}`)})}function q(B,K){let Z=(0,_B.useFunc)(w,SB.default),M=w.name("outer");w.label(M).for(qb._`;${B}--;`,()=>w.for(qb._`${K} = ${B}; ${K}--;`,()=>w.if(qb._`${Z}(${$}[${B}], ${$}[${K}])`,()=>{b.error(),w.assign(H,!1).break(M)})))}}};MH.default=kB});var IH=I((jH)=>{Object.defineProperty(jH,"__esModule",{value:!0});var c6=u(),CB=l(),xB=Z$(),uB={message:"must be equal to constant",params:({schemaCode:b})=>c6._`{allowedValue: ${b}}`},yB={keyword:"const",$data:!0,error:uB,code(b){let{gen:w,data:$,$data:W,schemaCode:Q,schema:G}=b;if(W||G&&typeof G=="object")b.fail$data(c6._`!${(0,CB.useFunc)(w,xB.default)}(${$}, ${Q})`);else b.fail(c6._`${G} !== ${$}`)}};jH.default=yB});var NH=I((VH)=>{Object.defineProperty(VH,"__esModule",{value:!0});var $0=u(),fB=l(),cB=Z$(),gB={message:"must be equal to one of the allowed values",params:({schemaCode:b})=>$0._`{allowedValues: ${b}}`},mB={keyword:"enum",schemaType:"array",$data:!0,error:gB,code(b){let{gen:w,data:$,$data:W,schema:Q,schemaCode:G,it:X}=b;if(!W&&Q.length===0)throw Error("enum must have non-empty array");let Y=Q.length>=X.opts.loopEnum,H,J=()=>H!==null&&H!==void 0?H:H=(0,fB.useFunc)(w,cB.default),D;if(Y||W)D=w.let("valid"),b.block$data(D,z);else{if(!Array.isArray(Q))throw Error("ajv implementation error");let q=w.const("vSchema",G);D=(0,$0.or)(...Q.map((B,K)=>O(q,K)))}b.pass(D);function z(){w.assign(D,!1),w.forOf("v",G,(q)=>w.if($0._`${J()}(${$}, ${q})`,()=>w.assign(D,!0).break()))}function O(q,B){let K=Q[B];return typeof K==="object"&&K!==null?$0._`${J()}(${$}, ${q}[${B}])`:$0._`${$} === ${K}`}}};VH.default=mB});var EH=I((TH)=>{Object.defineProperty(TH,"__esModule",{value:!0});var lB=WH(),iB=GH(),pB=DH(),oB=AH(),dB=qH(),tB=UH(),rB=FH(),eB=ZH(),sB=IH(),aB=NH(),bF=[lB.default,iB.default,pB.default,oB.default,dB.default,tB.default,rB.default,eB.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},sB.default,aB.default];TH.default=bF});var m6=I((SH)=>{Object.defineProperty(SH,"__esModule",{value:!0});SH.validateAdditionalItems=void 0;var uw=u(),g6=l(),$F={message:({params:{len:b}})=>uw.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>uw._`{limit: ${b}}`},WF={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:$F,code(b){let{parentSchema:w,it:$}=b,{items:W}=w;if(!Array.isArray(W)){(0,g6.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}_H(b,W)}};function _H(b,w){let{gen:$,schema:W,data:Q,keyword:G,it:X}=b;X.items=!0;let Y=$.const("len",uw._`${Q}.length`);if(W===!1)b.setParams({len:w.length}),b.pass(uw._`${Y} <= ${w.length}`);else if(typeof W=="object"&&!(0,g6.alwaysValidSchema)(X,W)){let J=$.var("valid",uw._`${Y} <= ${w.length}`);$.if((0,uw.not)(J),()=>H(J)),b.ok(J)}function H(J){$.forRange("i",w.length,Y,(D)=>{if(b.subschema({keyword:G,dataProp:D,dataPropType:g6.Type.Num},J),!X.allErrors)$.if((0,uw.not)(J),()=>$.break())})}}SH.validateAdditionalItems=_H;SH.default=WF});var n6=I((CH)=>{Object.defineProperty(CH,"__esModule",{value:!0});CH.validateTuple=void 0;var kH=u(),j$=l(),GF=vb(),XF={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(b){let{schema:w,it:$}=b;if(Array.isArray(w))return vH(b,"additionalItems",w);if($.items=!0,(0,j$.alwaysValidSchema)($,w))return;b.ok((0,GF.validateArray)(b))}};function vH(b,w,$=b.schema){let{gen:W,parentSchema:Q,data:G,keyword:X,it:Y}=b;if(D(Q),Y.opts.unevaluated&&$.length&&Y.items!==!0)Y.items=j$.mergeEvaluated.items(W,$.length,Y.items);let H=W.name("valid"),J=W.const("len",kH._`${G}.length`);$.forEach((z,O)=>{if((0,j$.alwaysValidSchema)(Y,z))return;W.if(kH._`${J} > ${O}`,()=>b.subschema({keyword:X,schemaProp:O,dataProp:O},H)),b.ok(H)});function D(z){let{opts:O,errSchemaPath:q}=Y,B=$.length,K=B===z.minItems&&(B===z.maxItems||z[w]===!1);if(O.strictTuples&&!K){let Z=`"${X}" is ${B}-tuple, but minItems or maxItems/${w} are not specified or different at path "${q}"`;(0,j$.checkStrictMode)(Y,Z,O.strictTuples)}}}CH.validateTuple=vH;CH.default=XF});var yH=I((uH)=>{Object.defineProperty(uH,"__esModule",{value:!0});var HF=n6(),JF={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(b)=>(0,HF.validateTuple)(b,"items")};uH.default=JF});var cH=I((fH)=>{Object.defineProperty(fH,"__esModule",{value:!0});var hH=u(),zF=l(),AF=vb(),OF=m6(),qF={message:({params:{len:b}})=>hH.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>hH._`{limit: ${b}}`},LF={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:qF,code(b){let{schema:w,parentSchema:$,it:W}=b,{prefixItems:Q}=$;if(W.items=!0,(0,zF.alwaysValidSchema)(W,w))return;if(Q)(0,OF.validateAdditionalItems)(b,Q);else b.ok((0,AF.validateArray)(b))}};fH.default=LF});var mH=I((gH)=>{Object.defineProperty(gH,"__esModule",{value:!0});var Cb=u(),I$=l(),BF={message:({params:{min:b,max:w}})=>w===void 0?Cb.str`must contain at least ${b} valid item(s)`:Cb.str`must contain at least ${b} and no more than ${w} valid item(s)`,params:({params:{min:b,max:w}})=>w===void 0?Cb._`{minContains: ${b}}`:Cb._`{minContains: ${b}, maxContains: ${w}}`},FF={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:BF,code(b){let{gen:w,schema:$,parentSchema:W,data:Q,it:G}=b,X,Y,{minContains:H,maxContains:J}=W;if(G.opts.next)X=H===void 0?1:H,Y=J;else X=1;let D=w.const("len",Cb._`${Q}.length`);if(b.setParams({min:X,max:Y}),Y===void 0&&X===0){(0,I$.checkStrictMode)(G,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(Y!==void 0&&X>Y){(0,I$.checkStrictMode)(G,'"minContains" > "maxContains" is always invalid'),b.fail();return}if((0,I$.alwaysValidSchema)(G,$)){let K=Cb._`${D} >= ${X}`;if(Y!==void 0)K=Cb._`${K} && ${D} <= ${Y}`;b.pass(K);return}G.items=!0;let z=w.name("valid");if(Y===void 0&&X===1)q(z,()=>w.if(z,()=>w.break()));else if(X===0){if(w.let(z,!0),Y!==void 0)w.if(Cb._`${Q}.length > 0`,O)}else w.let(z,!1),O();b.result(z,()=>b.reset());function O(){let K=w.name("_valid"),Z=w.let("count",0);q(K,()=>w.if(K,()=>B(Z)))}function q(K,Z){w.forRange("i",0,D,(M)=>{b.subschema({keyword:"contains",dataProp:M,dataPropType:I$.Type.Num,compositeRule:!0},K),Z()})}function B(K){if(w.code(Cb._`${K}++`),Y===void 0)w.if(Cb._`${K} >= ${X}`,()=>w.assign(z,!0).break());else if(w.if(Cb._`${K} > ${Y}`,()=>w.assign(z,!1).break()),X===1)w.assign(z,!0);else w.if(Cb._`${K} >= ${X}`,()=>w.assign(z,!0))}}};gH.default=FF});var dH=I((iH)=>{Object.defineProperty(iH,"__esModule",{value:!0});iH.validateSchemaDeps=iH.validatePropertyDeps=iH.error=void 0;var l6=u(),PF=l(),W0=vb();iH.error={message:({params:{property:b,depsCount:w,deps:$}})=>{let W=w===1?"property":"properties";return l6.str`must have ${W} ${$} when property ${b} is present`},params:({params:{property:b,depsCount:w,deps:$,missingProperty:W}})=>l6._`{property: ${b},
1
+ var xz=Object.create;var{getPrototypeOf:yz,defineProperty:d$,getOwnPropertyNames:hz}=Object;var fz=Object.prototype.hasOwnProperty;function cz(b){return this[b]}var nz,gz,RW=(b,w,$)=>{var W=b!=null&&typeof b==="object";if(W){var Q=w?nz??=new WeakMap:gz??=new WeakMap,G=Q.get(b);if(G)return G}$=b!=null?xz(yz(b)):{};let D=w||!b||!b.__esModule?d$($,"default",{value:b,enumerable:!0}):$;for(let X of hz(b))if(!fz.call(D,X))d$(D,X,{get:cz.bind(b,X),enumerable:!0});if(W)Q.set(b,D);return D};var j=(b,w)=>()=>(w||b((w={exports:{}}).exports,w),w.exports);var mz=(b)=>b;function iz(b,w){this[b]=mz.bind(null,w)}var vW=(b,w)=>{for(var $ in w)d$(b,$,{get:w[$],enumerable:!0,configurable:!0,set:iz.bind(w,$)})};var h1=j((RG)=>{Object.defineProperty(RG,"__esModule",{value:!0});RG.regexpCode=RG.getEsmExportName=RG.getProperty=RG.safeStringify=RG.stringify=RG.strConcat=RG.addCodeArg=RG.str=RG._=RG.nil=RG._Code=RG.Name=RG.IDENTIFIER=RG._CodeOrName=void 0;class d0{}RG._CodeOrName=d0;RG.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class pw extends d0{constructor(b){super();if(!RG.IDENTIFIER.test(b))throw Error("CodeGen: name must be a valid identifier");this.str=b}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}RG.Name=pw;class hb extends d0{constructor(b){super();this._items=typeof b==="string"?[b]:b}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let b=this._items[0];return b===""||b==='""'}get str(){var b;return(b=this._str)!==null&&b!==void 0?b:this._str=this._items.reduce((w,$)=>`${w}${$}`,"")}get names(){var b;return(b=this._names)!==null&&b!==void 0?b:this._names=this._items.reduce((w,$)=>{if($ instanceof pw)w[$.str]=(w[$.str]||0)+1;return w},{})}}RG._Code=hb;RG.nil=new hb("");function _G(b,...w){let $=[b[0]],W=0;while(W<w.length)W6($,w[W]),$.push(b[++W]);return new hb($)}RG._=_G;var $6=new hb("+");function SG(b,...w){let $=[y1(b[0])],W=0;while(W<w.length)$.push($6),W6($,w[W]),$.push($6,y1(b[++W]));return AO($),new hb($)}RG.str=SG;function W6(b,w){if(w instanceof hb)b.push(...w._items);else if(w instanceof pw)b.push(w);else b.push(LO(w))}RG.addCodeArg=W6;function AO(b){let w=1;while(w<b.length-1){if(b[w]===$6){let $=OO(b[w-1],b[w+1]);if($!==void 0){b.splice(w-1,3,$);continue}b[w++]="+"}w++}}function OO(b,w){if(w==='""')return b;if(b==='""')return w;if(typeof b=="string"){if(w instanceof pw||b[b.length-1]!=='"')return;if(typeof w!="string")return`${b.slice(0,-1)}${w}"`;if(w[0]==='"')return b.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!(b instanceof pw))return`"${b}${w.slice(1)}`;return}function qO(b,w){return w.emptyStr()?b:b.emptyStr()?w:SG`${b}${w}`}RG.strConcat=qO;function LO(b){return typeof b=="number"||typeof b=="boolean"||b===null?b:y1(Array.isArray(b)?b.join(","):b)}function UO(b){return new hb(y1(b))}RG.stringify=UO;function y1(b){return JSON.stringify(b).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}RG.safeStringify=y1;function BO(b){return typeof b=="string"&&RG.IDENTIFIER.test(b)?new hb(`.${b}`):_G`[${b}]`}RG.getProperty=BO;function PO(b){if(typeof b=="string"&&RG.IDENTIFIER.test(b))return new hb(`${b}`);throw Error(`CodeGen: invalid export name: ${b}, use explicit $id name mapping`)}RG.getEsmExportName=PO;function FO(b){return new hb(b.toString())}RG.regexpCode=FO});var X6=j((uG)=>{Object.defineProperty(uG,"__esModule",{value:!0});uG.ValueScope=uG.ValueScopeName=uG.Scope=uG.varKinds=uG.UsedValueState=void 0;var Ib=h1();class kG extends Error{constructor(b){super(`CodeGen: "code" for ${b} not defined`);this.value=b.value}}var r0;(function(b){b[b.Started=0]="Started",b[b.Completed=1]="Completed"})(r0||(uG.UsedValueState=r0={}));uG.varKinds={const:new Ib.Name("const"),let:new Ib.Name("let"),var:new Ib.Name("var")};class G6{constructor({prefixes:b,parent:w}={}){this._names={},this._prefixes=b,this._parent=w}toName(b){return b instanceof Ib.Name?b:this.name(b)}name(b){return new Ib.Name(this._newName(b))}_newName(b){let w=this._names[b]||this._nameGroup(b);return`${b}${w.index++}`}_nameGroup(b){var w,$;if((($=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||$===void 0?void 0:$.has(b))||this._prefixes&&!this._prefixes.has(b))throw Error(`CodeGen: prefix "${b}" is not allowed in this scope`);return this._names[b]={prefix:b,index:0}}}uG.Scope=G6;class D6 extends Ib.Name{constructor(b,w){super(w);this.prefix=b}setValue(b,{property:w,itemIndex:$}){this.value=b,this.scopePath=Ib._`.${new Ib.Name(w)}[${$}]`}}uG.ValueScopeName=D6;var vO=Ib._`\n`;class CG extends G6{constructor(b){super(b);this._values={},this._scope=b.scope,this.opts={...b,_n:b.lines?vO:Ib.nil}}get(){return this._scope}name(b){return new D6(b,this._newName(b))}value(b,w){var $;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName(b),{prefix:Q}=W,G=($=w.key)!==null&&$!==void 0?$:w.ref,D=this._values[Q];if(D){let H=D.get(G);if(H)return H}else D=this._values[Q]=new Map;D.set(G,W);let X=this._scope[Q]||(this._scope[Q]=[]),Y=X.length;return X[Y]=w.ref,W.setValue(w,{property:Q,itemIndex:Y}),W}getValue(b,w){let $=this._values[b];if(!$)return;return $.get(w)}scopeRefs(b,w=this._values){return this._reduceValues(w,($)=>{if($.scopePath===void 0)throw Error(`CodeGen: name "${$}" has no value`);return Ib._`${b}${$.scopePath}`})}scopeCode(b=this._values,w,$){return this._reduceValues(b,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},w,$)}_reduceValues(b,w,$={},W){let Q=Ib.nil;for(let G in b){let D=b[G];if(!D)continue;let X=$[G]=$[G]||new Map;D.forEach((Y)=>{if(X.has(Y))return;X.set(Y,r0.Started);let H=w(Y);if(H){let J=this.opts.es5?uG.varKinds.var:uG.varKinds.const;Q=Ib._`${Q}${J} ${Y} = ${H};${this.opts._n}`}else if(H=W===null||W===void 0?void 0:W(Y))Q=Ib._`${Q}${H}${this.opts._n}`;else throw new kG(Y);X.set(Y,r0.Completed)})}return Q}}uG.ValueScope=CG});var x=j((Zb)=>{Object.defineProperty(Zb,"__esModule",{value:!0});Zb.or=Zb.and=Zb.not=Zb.CodeGen=Zb.operators=Zb.varKinds=Zb.ValueScopeName=Zb.ValueScope=Zb.Scope=Zb.Name=Zb.regexpCode=Zb.stringify=Zb.getProperty=Zb.nil=Zb.strConcat=Zb.str=Zb._=void 0;var n=h1(),fb=X6(),Kw=h1();Object.defineProperty(Zb,"_",{enumerable:!0,get:function(){return Kw._}});Object.defineProperty(Zb,"str",{enumerable:!0,get:function(){return Kw.str}});Object.defineProperty(Zb,"strConcat",{enumerable:!0,get:function(){return Kw.strConcat}});Object.defineProperty(Zb,"nil",{enumerable:!0,get:function(){return Kw.nil}});Object.defineProperty(Zb,"getProperty",{enumerable:!0,get:function(){return Kw.getProperty}});Object.defineProperty(Zb,"stringify",{enumerable:!0,get:function(){return Kw.stringify}});Object.defineProperty(Zb,"regexpCode",{enumerable:!0,get:function(){return Kw.regexpCode}});Object.defineProperty(Zb,"Name",{enumerable:!0,get:function(){return Kw.Name}});var $$=X6();Object.defineProperty(Zb,"Scope",{enumerable:!0,get:function(){return $$.Scope}});Object.defineProperty(Zb,"ValueScope",{enumerable:!0,get:function(){return $$.ValueScope}});Object.defineProperty(Zb,"ValueScopeName",{enumerable:!0,get:function(){return $$.ValueScopeName}});Object.defineProperty(Zb,"varKinds",{enumerable:!0,get:function(){return $$.varKinds}});Zb.operators={GT:new n._Code(">"),GTE:new n._Code(">="),LT:new n._Code("<"),LTE:new n._Code("<="),EQ:new n._Code("==="),NEQ:new n._Code("!=="),NOT:new n._Code("!"),OR:new n._Code("||"),AND:new n._Code("&&"),ADD:new n._Code("+")};class Mw{optimizeNodes(){return this}optimizeNames(b,w){return this}}class yG extends Mw{constructor(b,w,$){super();this.varKind=b,this.name=w,this.rhs=$}render({es5:b,_n:w}){let $=b?fb.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${W};`+w}optimizeNames(b,w){if(!b[this.name.str])return;if(this.rhs)this.rhs=dw(this.rhs,b,w);return this}get names(){return this.rhs instanceof n._CodeOrName?this.rhs.names:{}}}class J6 extends Mw{constructor(b,w,$){super();this.lhs=b,this.rhs=w,this.sideEffects=$}render({_n:b}){return`${this.lhs} = ${this.rhs};`+b}optimizeNames(b,w){if(this.lhs instanceof n.Name&&!b[this.lhs.str]&&!this.sideEffects)return;return this.rhs=dw(this.rhs,b,w),this}get names(){let b=this.lhs instanceof n.Name?{}:{...this.lhs.names};return w$(b,this.rhs)}}class hG extends J6{constructor(b,w,$,W){super(b,$,W);this.op=w}render({_n:b}){return`${this.lhs} ${this.op}= ${this.rhs};`+b}}class fG extends Mw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`${this.label}:`+b}}class cG extends Mw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`break${this.label?` ${this.label}`:""};`+b}}class nG extends Mw{constructor(b){super();this.error=b}render({_n:b}){return`throw ${this.error};`+b}get names(){return this.error.names}}class gG extends Mw{constructor(b){super();this.code=b}render({_n:b}){return`${this.code};`+b}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(b,w){return this.code=dw(this.code,b,w),this}get names(){return this.code instanceof n._CodeOrName?this.code.names:{}}}class W$ extends Mw{constructor(b=[]){super();this.nodes=b}render(b){return this.nodes.reduce((w,$)=>w+$.render(b),"")}optimizeNodes(){let{nodes:b}=this,w=b.length;while(w--){let $=b[w].optimizeNodes();if(Array.isArray($))b.splice(w,1,...$);else if($)b[w]=$;else b.splice(w,1)}return b.length>0?this:void 0}optimizeNames(b,w){let{nodes:$}=this,W=$.length;while(W--){let Q=$[W];if(Q.optimizeNames(b,w))continue;xO(b,Q.names),$.splice(W,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((b,w)=>Rw(b,w.names),{})}}class Iw extends W${render(b){return"{"+b._n+super.render(b)+"}"+b._n}}class mG extends W${}class f1 extends Iw{}f1.kind="else";class Ww extends Iw{constructor(b,w){super(w);this.condition=b}render(b){let w=`if(${this.condition})`+super.render(b);if(this.else)w+="else "+this.else.render(b);return w}optimizeNodes(){super.optimizeNodes();let b=this.condition;if(b===!0)return this.nodes;let w=this.else;if(w){let $=w.optimizeNodes();w=this.else=Array.isArray($)?new f1($):$}if(w){if(b===!1)return w instanceof Ww?w:w.nodes;if(this.nodes.length)return this;return new Ww(dG(b),w instanceof Ww?[w]:w.nodes)}if(b===!1||!this.nodes.length)return;return this}optimizeNames(b,w){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(b,w),!(super.optimizeNames(b,w)||this.else))return;return this.condition=dw(this.condition,b,w),this}get names(){let b=super.names;if(w$(b,this.condition),this.else)Rw(b,this.else.names);return b}}Ww.kind="if";class ow extends Iw{}ow.kind="for";class iG extends ow{constructor(b){super();this.iteration=b}render(b){return`for(${this.iteration})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iteration=dw(this.iteration,b,w),this}get names(){return Rw(super.names,this.iteration.names)}}class lG extends ow{constructor(b,w,$,W){super();this.varKind=b,this.name=w,this.from=$,this.to=W}render(b){let w=b.es5?fb.varKinds.var:this.varKind,{name:$,from:W,to:Q}=this;return`for(${w} ${$}=${W}; ${$}<${Q}; ${$}++)`+super.render(b)}get names(){let b=w$(super.names,this.from);return w$(b,this.to)}}class Y6 extends ow{constructor(b,w,$,W){super();this.loop=b,this.varKind=w,this.name=$,this.iterable=W}render(b){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iterable=dw(this.iterable,b,w),this}get names(){return Rw(super.names,this.iterable.names)}}class e0 extends Iw{constructor(b,w,$){super();this.name=b,this.args=w,this.async=$}render(b){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(b)}}e0.kind="func";class s0 extends W${render(b){return"return "+super.render(b)}}s0.kind="return";class pG extends Iw{render(b){let w="try"+super.render(b);if(this.catch)w+=this.catch.render(b);if(this.finally)w+=this.finally.render(b);return w}optimizeNodes(){var b,w;return super.optimizeNodes(),(b=this.catch)===null||b===void 0||b.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(b,w){var $,W;return super.optimizeNames(b,w),($=this.catch)===null||$===void 0||$.optimizeNames(b,w),(W=this.finally)===null||W===void 0||W.optimizeNames(b,w),this}get names(){let b=super.names;if(this.catch)Rw(b,this.catch.names);if(this.finally)Rw(b,this.finally.names);return b}}class a0 extends Iw{constructor(b){super();this.error=b}render(b){return`catch(${this.error})`+super.render(b)}}a0.kind="catch";class b$ extends Iw{render(b){return"finally"+super.render(b)}}b$.kind="finally";class oG{constructor(b,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
2
+ `:""},this._extScope=b,this._scope=new fb.Scope({parent:b}),this._nodes=[new mG]}toString(){return this._root.render(this.opts)}name(b){return this._scope.name(b)}scopeName(b){return this._extScope.name(b)}scopeValue(b,w){let $=this._extScope.value(b,w);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(b,w){return this._extScope.getValue(b,w)}scopeRefs(b){return this._extScope.scopeRefs(b,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(b,w,$,W){let Q=this._scope.toName(w);if($!==void 0&&W)this._constants[Q.str]=$;return this._leafNode(new yG(b,Q,$)),Q}const(b,w,$){return this._def(fb.varKinds.const,b,w,$)}let(b,w,$){return this._def(fb.varKinds.let,b,w,$)}var(b,w,$){return this._def(fb.varKinds.var,b,w,$)}assign(b,w,$){return this._leafNode(new J6(b,w,$))}add(b,w){return this._leafNode(new hG(b,Zb.operators.ADD,w))}code(b){if(typeof b=="function")b();else if(b!==n.nil)this._leafNode(new gG(b));return this}object(...b){let w=["{"];for(let[$,W]of b){if(w.length>1)w.push(",");if(w.push($),$!==W||this.opts.es5)w.push(":"),(0,n.addCodeArg)(w,W)}return w.push("}"),new n._Code(w)}if(b,w,$){if(this._blockNode(new Ww(b)),w&&$)this.code(w).else().code($).endIf();else if(w)this.code(w).endIf();else if($)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(b){return this._elseNode(new Ww(b))}else(){return this._elseNode(new f1)}endIf(){return this._endBlockNode(Ww,f1)}_for(b,w){if(this._blockNode(b),w)this.code(w).endFor();return this}for(b,w){return this._for(new iG(b),w)}forRange(b,w,$,W,Q=this.opts.es5?fb.varKinds.var:fb.varKinds.let){let G=this._scope.toName(b);return this._for(new lG(Q,G,w,$),()=>W(G))}forOf(b,w,$,W=fb.varKinds.const){let Q=this._scope.toName(b);if(this.opts.es5){let G=w instanceof n.Name?w:this.var("_arr",w);return this.forRange("_i",0,n._`${G}.length`,(D)=>{this.var(Q,n._`${G}[${D}]`),$(Q)})}return this._for(new Y6("of",W,Q,w),()=>$(Q))}forIn(b,w,$,W=this.opts.es5?fb.varKinds.var:fb.varKinds.const){if(this.opts.ownProperties)return this.forOf(b,n._`Object.keys(${w})`,$);let Q=this._scope.toName(b);return this._for(new Y6("in",W,Q,w),()=>$(Q))}endFor(){return this._endBlockNode(ow)}label(b){return this._leafNode(new fG(b))}break(b){return this._leafNode(new cG(b))}return(b){let w=new s0;if(this._blockNode(w),this.code(b),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(s0)}try(b,w,$){if(!w&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new pG;if(this._blockNode(W),this.code(b),w){let Q=this.name("e");this._currNode=W.catch=new a0(Q),w(Q)}if($)this._currNode=W.finally=new b$,this.code($);return this._endBlockNode(a0,b$)}throw(b){return this._leafNode(new nG(b))}block(b,w){if(this._blockStarts.push(this._nodes.length),b)this.code(b).endBlock(w);return this}endBlock(b){let w=this._blockStarts.pop();if(w===void 0)throw Error("CodeGen: not in self-balancing block");let $=this._nodes.length-w;if($<0||b!==void 0&&$!==b)throw Error(`CodeGen: wrong number of nodes: ${$} vs ${b} expected`);return this._nodes.length=w,this}func(b,w=n.nil,$,W){if(this._blockNode(new e0(b,w,$)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(e0)}optimize(b=1){while(b-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(b){return this._currNode.nodes.push(b),this}_blockNode(b){this._currNode.nodes.push(b),this._nodes.push(b)}_endBlockNode(b,w){let $=this._currNode;if($ instanceof b||w&&$ instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${b.kind}/${w.kind}`:b.kind}"`)}_elseNode(b){let w=this._currNode;if(!(w instanceof Ww))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=b,this}get _root(){return this._nodes[0]}get _currNode(){let b=this._nodes;return b[b.length-1]}set _currNode(b){let w=this._nodes;w[w.length-1]=b}}Zb.CodeGen=oG;function Rw(b,w){for(let $ in w)b[$]=(b[$]||0)+(w[$]||0);return b}function w$(b,w){return w instanceof n._CodeOrName?Rw(b,w.names):b}function dw(b,w,$){if(b instanceof n.Name)return W(b);if(!Q(b))return b;return new n._Code(b._items.reduce((G,D)=>{if(D instanceof n.Name)D=W(D);if(D instanceof n._Code)G.push(...D._items);else G.push(D);return G},[]));function W(G){let D=$[G.str];if(D===void 0||w[G.str]!==1)return G;return delete w[G.str],D}function Q(G){return G instanceof n._Code&&G._items.some((D)=>D instanceof n.Name&&w[D.str]===1&&$[D.str]!==void 0)}}function xO(b,w){for(let $ in w)b[$]=(b[$]||0)-(w[$]||0)}function dG(b){return typeof b=="boolean"||typeof b=="number"||b===null?!b:n._`!${H6(b)}`}Zb.not=dG;var yO=tG(Zb.operators.AND);function hO(...b){return b.reduce(yO)}Zb.and=hO;var fO=tG(Zb.operators.OR);function cO(...b){return b.reduce(fO)}Zb.or=cO;function tG(b){return(w,$)=>w===n.nil?$:$===n.nil?w:n._`${H6(w)} ${b} ${H6($)}`}function H6(b){return b instanceof n.Name?b:n._`(${b})`}});var i=j((QD)=>{Object.defineProperty(QD,"__esModule",{value:!0});QD.checkStrictMode=QD.getErrorPath=QD.Type=QD.useFunc=QD.setEvaluated=QD.evaluatedPropsToName=QD.mergeEvaluated=QD.eachItem=QD.unescapeJsonPointer=QD.escapeJsonPointer=QD.escapeFragment=QD.unescapeFragment=QD.schemaRefOrVal=QD.schemaHasRulesButRef=QD.schemaHasRules=QD.checkUnknownRules=QD.alwaysValidSchema=QD.toHash=void 0;var t=x(),iO=h1();function lO(b){let w={};for(let $ of b)w[$]=!0;return w}QD.toHash=lO;function pO(b,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return aG(b,w),!bD(w,b.self.RULES.all)}QD.alwaysValidSchema=pO;function aG(b,w=b.schema){let{opts:$,self:W}=b;if(!$.strictSchema)return;if(typeof w==="boolean")return;let Q=W.RULES.keywords;for(let G in w)if(!Q[G])WD(b,`unknown keyword: "${G}"`)}QD.checkUnknownRules=aG;function bD(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if(w[$])return!0;return!1}QD.schemaHasRules=bD;function oO(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if($!=="$ref"&&w.all[$])return!0;return!1}QD.schemaHasRulesButRef=oO;function dO({topSchemaRef:b,schemaPath:w},$,W,Q){if(!Q){if(typeof $=="number"||typeof $=="boolean")return $;if(typeof $=="string")return t._`${$}`}return t._`${b}${w}${(0,t.getProperty)(W)}`}QD.schemaRefOrVal=dO;function tO(b){return wD(decodeURIComponent(b))}QD.unescapeFragment=tO;function rO(b){return encodeURIComponent(A6(b))}QD.escapeFragment=rO;function A6(b){if(typeof b=="number")return`${b}`;return b.replace(/~/g,"~0").replace(/\//g,"~1")}QD.escapeJsonPointer=A6;function wD(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}QD.unescapeJsonPointer=wD;function eO(b,w){if(Array.isArray(b))for(let $ of b)w($);else w(b)}QD.eachItem=eO;function eG({mergeNames:b,mergeToName:w,mergeValues:$,resultToName:W}){return(Q,G,D,X)=>{let Y=D===void 0?G:D instanceof t.Name?(G instanceof t.Name?b(Q,G,D):w(Q,G,D),D):G instanceof t.Name?(w(Q,D,G),G):$(G,D);return X===t.Name&&!(Y instanceof t.Name)?W(Q,Y):Y}}QD.mergeEvaluated={props:eG({mergeNames:(b,w,$)=>b.if(t._`${$} !== true && ${w} !== undefined`,()=>{b.if(t._`${w} === true`,()=>b.assign($,!0),()=>b.assign($,t._`${$} || {}`).code(t._`Object.assign(${$}, ${w})`))}),mergeToName:(b,w,$)=>b.if(t._`${$} !== true`,()=>{if(w===!0)b.assign($,!0);else b.assign($,t._`${$} || {}`),O6(b,$,w)}),mergeValues:(b,w)=>b===!0?!0:{...b,...w},resultToName:$D}),items:eG({mergeNames:(b,w,$)=>b.if(t._`${$} !== true && ${w} !== undefined`,()=>b.assign($,t._`${w} === true ? true : ${$} > ${w} ? ${$} : ${w}`)),mergeToName:(b,w,$)=>b.if(t._`${$} !== true`,()=>b.assign($,w===!0?!0:t._`${$} > ${w} ? ${$} : ${w}`)),mergeValues:(b,w)=>b===!0?!0:Math.max(b,w),resultToName:(b,w)=>b.var("items",w)})};function $D(b,w){if(w===!0)return b.var("props",!0);let $=b.var("props",t._`{}`);if(w!==void 0)O6(b,$,w);return $}QD.evaluatedPropsToName=$D;function O6(b,w,$){Object.keys($).forEach((W)=>b.assign(t._`${w}${(0,t.getProperty)(W)}`,!0))}QD.setEvaluated=O6;var sG={};function sO(b,w){return b.scopeValue("func",{ref:w,code:sG[w.code]||(sG[w.code]=new iO._Code(w.code))})}QD.useFunc=sO;var z6;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(z6||(QD.Type=z6={}));function aO(b,w,$){if(b instanceof t.Name){let W=w===z6.Num;return $?W?t._`"[" + ${b} + "]"`:t._`"['" + ${b} + "']"`:W?t._`"/" + ${b}`:t._`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,t.getProperty)(b).toString():"/"+A6(b)}QD.getErrorPath=aO;function WD(b,w,$=b.opts.strictSchema){if(!$)return;if(w=`strict mode: ${w}`,$===!0)throw Error(w);b.self.logger.warn(w)}QD.checkStrictMode=WD});var Qw=j((DD)=>{Object.defineProperty(DD,"__esModule",{value:!0});var Lb=x(),Bq={data:new Lb.Name("data"),valCxt:new Lb.Name("valCxt"),instancePath:new Lb.Name("instancePath"),parentData:new Lb.Name("parentData"),parentDataProperty:new Lb.Name("parentDataProperty"),rootData:new Lb.Name("rootData"),dynamicAnchors:new Lb.Name("dynamicAnchors"),vErrors:new Lb.Name("vErrors"),errors:new Lb.Name("errors"),this:new Lb.Name("this"),self:new Lb.Name("self"),scope:new Lb.Name("scope"),json:new Lb.Name("json"),jsonPos:new Lb.Name("jsonPos"),jsonLen:new Lb.Name("jsonLen"),jsonPart:new Lb.Name("jsonPart")};DD.default=Bq});var c1=j((JD)=>{Object.defineProperty(JD,"__esModule",{value:!0});JD.extendErrors=JD.resetErrorsCount=JD.reportExtraError=JD.reportError=JD.keyword$DataError=JD.keywordError=void 0;var g=x(),G$=i(),Pb=Qw();JD.keywordError={message:({keyword:b})=>g.str`must pass "${b}" keyword validation`};JD.keyword$DataError={message:({keyword:b,schemaType:w})=>w?g.str`"${b}" keyword must be ${w} ($data)`:g.str`"${b}" keyword is invalid ($data)`};function Fq(b,w=JD.keywordError,$,W){let{it:Q}=b,{gen:G,compositeRule:D,allErrors:X}=Q,Y=HD(b,w,$);if(W!==null&&W!==void 0?W:D||X)XD(G,Y);else YD(Q,g._`[${Y}]`)}JD.reportError=Fq;function Kq(b,w=JD.keywordError,$){let{it:W}=b,{gen:Q,compositeRule:G,allErrors:D}=W,X=HD(b,w,$);if(XD(Q,X),!(G||D))YD(W,Pb.default.vErrors)}JD.reportExtraError=Kq;function Mq(b,w){b.assign(Pb.default.errors,w),b.if(g._`${Pb.default.vErrors} !== null`,()=>b.if(w,()=>b.assign(g._`${Pb.default.vErrors}.length`,w),()=>b.assign(Pb.default.vErrors,null)))}JD.resetErrorsCount=Mq;function Iq({gen:b,keyword:w,schemaValue:$,data:W,errsCount:Q,it:G}){if(Q===void 0)throw Error("ajv implementation error");let D=b.name("err");b.forRange("i",Q,Pb.default.errors,(X)=>{if(b.const(D,g._`${Pb.default.vErrors}[${X}]`),b.if(g._`${D}.instancePath === undefined`,()=>b.assign(g._`${D}.instancePath`,(0,g.strConcat)(Pb.default.instancePath,G.errorPath))),b.assign(g._`${D}.schemaPath`,g.str`${G.errSchemaPath}/${w}`),G.opts.verbose)b.assign(g._`${D}.schema`,$),b.assign(g._`${D}.data`,W)})}JD.extendErrors=Iq;function XD(b,w){let $=b.const("err",w);b.if(g._`${Pb.default.vErrors} === null`,()=>b.assign(Pb.default.vErrors,g._`[${$}]`),g._`${Pb.default.vErrors}.push(${$})`),b.code(g._`${Pb.default.errors}++`)}function YD(b,w){let{gen:$,validateName:W,schemaEnv:Q}=b;if(Q.$async)$.throw(g._`new ${b.ValidationError}(${w})`);else $.assign(g._`${W}.errors`,w),$.return(!1)}var vw={keyword:new g.Name("keyword"),schemaPath:new g.Name("schemaPath"),params:new g.Name("params"),propertyName:new g.Name("propertyName"),message:new g.Name("message"),schema:new g.Name("schema"),parentSchema:new g.Name("parentSchema")};function HD(b,w,$){let{createErrors:W}=b.it;if(W===!1)return g._`{}`;return Zq(b,w,$)}function Zq(b,w,$={}){let{gen:W,it:Q}=b,G=[jq(Q,$),Vq(b,$)];return Nq(b,w,G),W.object(...G)}function jq({errorPath:b},{instancePath:w}){let $=w?g.str`${b}${(0,G$.getErrorPath)(w,G$.Type.Str)}`:b;return[Pb.default.instancePath,(0,g.strConcat)(Pb.default.instancePath,$)]}function Vq({keyword:b,it:{errSchemaPath:w}},{schemaPath:$,parentSchema:W}){let Q=W?w:g.str`${w}/${b}`;if($)Q=g.str`${Q}${(0,G$.getErrorPath)($,G$.Type.Str)}`;return[vw.schemaPath,Q]}function Nq(b,{params:w,message:$},W){let{keyword:Q,data:G,schemaValue:D,it:X}=b,{opts:Y,propertyName:H,topSchemaRef:J,schemaPath:z}=X;if(W.push([vw.keyword,Q],[vw.params,typeof w=="function"?w(b):w||g._`{}`]),Y.messages)W.push([vw.message,typeof $=="function"?$(b):$]);if(Y.verbose)W.push([vw.schema,D],[vw.parentSchema,g._`${J}${z}`],[Pb.default.data,G]);if(H)W.push([vw.propertyName,H])}});var LD=j((OD)=>{Object.defineProperty(OD,"__esModule",{value:!0});OD.boolOrEmptySchema=OD.topBoolOrEmptySchema=void 0;var Rq=c1(),vq=x(),kq=Qw(),Cq={message:"boolean schema is false"};function uq(b){let{gen:w,schema:$,validateName:W}=b;if($===!1)AD(b,!1);else if(typeof $=="object"&&$.$async===!0)w.return(kq.default.data);else w.assign(vq._`${W}.errors`,null),w.return(!0)}OD.topBoolOrEmptySchema=uq;function xq(b,w){let{gen:$,schema:W}=b;if(W===!1)$.var(w,!1),AD(b);else $.var(w,!0)}OD.boolOrEmptySchema=xq;function AD(b,w){let{gen:$,data:W}=b,Q={gen:$,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:b};(0,Rq.reportError)(Q,Cq,void 0,w)}});var L6=j((UD)=>{Object.defineProperty(UD,"__esModule",{value:!0});UD.getRules=UD.isJSONType=void 0;var hq=["string","number","integer","boolean","null","object","array"],fq=new Set(hq);function cq(b){return typeof b=="string"&&fq.has(b)}UD.isJSONType=cq;function nq(){let b={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...b,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},b.number,b.string,b.array,b.object],post:{rules:[]},all:{},keywords:{}}}UD.getRules=nq});var U6=j((KD)=>{Object.defineProperty(KD,"__esModule",{value:!0});KD.shouldUseRule=KD.shouldUseGroup=KD.schemaHasRulesForType=void 0;function mq({schema:b,self:w},$){let W=w.RULES.types[$];return W&&W!==!0&&PD(b,W)}KD.schemaHasRulesForType=mq;function PD(b,w){return w.rules.some(($)=>FD(b,$))}KD.shouldUseGroup=PD;function FD(b,w){var $;return b[w.keyword]!==void 0||(($=w.definition.implements)===null||$===void 0?void 0:$.some((W)=>b[W]!==void 0))}KD.shouldUseRule=FD});var n1=j((VD)=>{Object.defineProperty(VD,"__esModule",{value:!0});VD.reportTypeError=VD.checkDataTypes=VD.checkDataType=VD.coerceAndCheckDataType=VD.getJSONTypes=VD.getSchemaTypes=VD.DataType=void 0;var pq=L6(),oq=U6(),dq=c1(),C=x(),ID=i(),tw;(function(b){b[b.Correct=0]="Correct",b[b.Wrong=1]="Wrong"})(tw||(VD.DataType=tw={}));function tq(b){let w=ZD(b.type);if(w.includes("null")){if(b.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!w.length&&b.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(b.nullable===!0)w.push("null")}return w}VD.getSchemaTypes=tq;function ZD(b){let w=Array.isArray(b)?b:b?[b]:[];if(w.every(pq.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}VD.getJSONTypes=ZD;function rq(b,w){let{gen:$,data:W,opts:Q}=b,G=eq(w,Q.coerceTypes),D=w.length>0&&!(G.length===0&&w.length===1&&(0,oq.schemaHasRulesForType)(b,w[0]));if(D){let X=P6(w,W,Q.strictNumbers,tw.Wrong);$.if(X,()=>{if(G.length)sq(b,w,G);else F6(b)})}return D}VD.coerceAndCheckDataType=rq;var jD=new Set(["string","number","integer","boolean","null"]);function eq(b,w){return w?b.filter(($)=>jD.has($)||w==="array"&&$==="array"):[]}function sq(b,w,$){let{gen:W,data:Q,opts:G}=b,D=W.let("dataType",C._`typeof ${Q}`),X=W.let("coerced",C._`undefined`);if(G.coerceTypes==="array")W.if(C._`${D} == 'object' && Array.isArray(${Q}) && ${Q}.length == 1`,()=>W.assign(Q,C._`${Q}[0]`).assign(D,C._`typeof ${Q}`).if(P6(w,Q,G.strictNumbers),()=>W.assign(X,Q)));W.if(C._`${X} !== undefined`);for(let H of $)if(jD.has(H)||H==="array"&&G.coerceTypes==="array")Y(H);W.else(),F6(b),W.endIf(),W.if(C._`${X} !== undefined`,()=>{W.assign(Q,X),aq(b,X)});function Y(H){switch(H){case"string":W.elseIf(C._`${D} == "number" || ${D} == "boolean"`).assign(X,C._`"" + ${Q}`).elseIf(C._`${Q} === null`).assign(X,C._`""`);return;case"number":W.elseIf(C._`${D} == "boolean" || ${Q} === null
3
+ || (${D} == "string" && ${Q} && ${Q} == +${Q})`).assign(X,C._`+${Q}`);return;case"integer":W.elseIf(C._`${D} === "boolean" || ${Q} === null
4
+ || (${D} === "string" && ${Q} && ${Q} == +${Q} && !(${Q} % 1))`).assign(X,C._`+${Q}`);return;case"boolean":W.elseIf(C._`${Q} === "false" || ${Q} === 0 || ${Q} === null`).assign(X,!1).elseIf(C._`${Q} === "true" || ${Q} === 1`).assign(X,!0);return;case"null":W.elseIf(C._`${Q} === "" || ${Q} === 0 || ${Q} === false`),W.assign(X,null);return;case"array":W.elseIf(C._`${D} === "string" || ${D} === "number"
5
+ || ${D} === "boolean" || ${Q} === null`).assign(X,C._`[${Q}]`)}}}function aq({gen:b,parentData:w,parentDataProperty:$},W){b.if(C._`${w} !== undefined`,()=>b.assign(C._`${w}[${$}]`,W))}function B6(b,w,$,W=tw.Correct){let Q=W===tw.Correct?C.operators.EQ:C.operators.NEQ,G;switch(b){case"null":return C._`${w} ${Q} null`;case"array":G=C._`Array.isArray(${w})`;break;case"object":G=C._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":G=D(C._`!(${w} % 1) && !isNaN(${w})`);break;case"number":G=D();break;default:return C._`typeof ${w} ${Q} ${b}`}return W===tw.Correct?G:(0,C.not)(G);function D(X=C.nil){return(0,C.and)(C._`typeof ${w} == "number"`,X,$?C._`isFinite(${w})`:C.nil)}}VD.checkDataType=B6;function P6(b,w,$,W){if(b.length===1)return B6(b[0],w,$,W);let Q,G=(0,ID.toHash)(b);if(G.array&&G.object){let D=C._`typeof ${w} != "object"`;Q=G.null?D:C._`!${w} || ${D}`,delete G.null,delete G.array,delete G.object}else Q=C.nil;if(G.number)delete G.integer;for(let D in G)Q=(0,C.and)(Q,B6(D,w,$,W));return Q}VD.checkDataTypes=P6;var bL={message:({schema:b})=>`must be ${b}`,params:({schema:b,schemaValue:w})=>typeof b=="string"?C._`{type: ${b}}`:C._`{type: ${w}}`};function F6(b){let w=wL(b);(0,dq.reportError)(w,bL)}VD.reportTypeError=F6;function wL(b){let{gen:w,data:$,schema:W}=b,Q=(0,ID.schemaRefOrVal)(b,W,"type");return{gen:w,keyword:"type",data:$,schema:W.type,schemaCode:Q,schemaValue:Q,parentSchema:W,params:{},it:b}}});var SD=j((ED)=>{Object.defineProperty(ED,"__esModule",{value:!0});ED.assignDefaults=void 0;var rw=x(),YL=i();function HL(b,w){let{properties:$,items:W}=b.schema;if(w==="object"&&$)for(let Q in $)TD(b,Q,$[Q].default);else if(w==="array"&&Array.isArray(W))W.forEach((Q,G)=>TD(b,G,Q.default))}ED.assignDefaults=HL;function TD(b,w,$){let{gen:W,compositeRule:Q,data:G,opts:D}=b;if($===void 0)return;let X=rw._`${G}${(0,rw.getProperty)(w)}`;if(Q){(0,YL.checkStrictMode)(b,`default is ignored for: ${X}`);return}let Y=rw._`${X} === undefined`;if(D.useDefaults==="empty")Y=rw._`${Y} || ${X} === null || ${X} === ""`;W.if(Y,rw._`${X} = ${(0,rw.stringify)($)}`)}});var Cb=j((kD)=>{Object.defineProperty(kD,"__esModule",{value:!0});kD.validateUnion=kD.validateArray=kD.usePattern=kD.callValidateCode=kD.schemaProperties=kD.allSchemaProperties=kD.noPropertyInData=kD.propertyInData=kD.isOwnProperty=kD.hasPropFunc=kD.reportMissingProp=kD.checkMissingProp=kD.checkReportMissingProp=void 0;var a=x(),K6=i(),Zw=Qw(),JL=i();function zL(b,w){let{gen:$,data:W,it:Q}=b;$.if(I6($,W,w,Q.opts.ownProperties),()=>{b.setParams({missingProperty:a._`${w}`},!0),b.error()})}kD.checkReportMissingProp=zL;function AL({gen:b,data:w,it:{opts:$}},W,Q){return(0,a.or)(...W.map((G)=>(0,a.and)(I6(b,w,G,$.ownProperties),a._`${Q} = ${G}`)))}kD.checkMissingProp=AL;function OL(b,w){b.setParams({missingProperty:w},!0),b.error()}kD.reportMissingProp=OL;function RD(b){return b.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:a._`Object.prototype.hasOwnProperty`})}kD.hasPropFunc=RD;function M6(b,w,$){return a._`${RD(b)}.call(${w}, ${$})`}kD.isOwnProperty=M6;function qL(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} !== undefined`;return W?a._`${Q} && ${M6(b,w,$)}`:Q}kD.propertyInData=qL;function I6(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} === undefined`;return W?(0,a.or)(Q,(0,a.not)(M6(b,w,$))):Q}kD.noPropertyInData=I6;function vD(b){return b?Object.keys(b).filter((w)=>w!=="__proto__"):[]}kD.allSchemaProperties=vD;function LL(b,w){return vD(w).filter(($)=>!(0,K6.alwaysValidSchema)(b,w[$]))}kD.schemaProperties=LL;function UL({schemaCode:b,data:w,it:{gen:$,topSchemaRef:W,schemaPath:Q,errorPath:G},it:D},X,Y,H){let J=H?a._`${b}, ${w}, ${W}${Q}`:w,z=[[Zw.default.instancePath,(0,a.strConcat)(Zw.default.instancePath,G)],[Zw.default.parentData,D.parentData],[Zw.default.parentDataProperty,D.parentDataProperty],[Zw.default.rootData,Zw.default.rootData]];if(D.opts.dynamicRef)z.push([Zw.default.dynamicAnchors,Zw.default.dynamicAnchors]);let O=a._`${J}, ${$.object(...z)}`;return Y!==a.nil?a._`${X}.call(${Y}, ${O})`:a._`${X}(${O})`}kD.callValidateCode=UL;var BL=a._`new RegExp`;function PL({gen:b,it:{opts:w}},$){let W=w.unicodeRegExp?"u":"",{regExp:Q}=w.code,G=Q($,W);return b.scopeValue("pattern",{key:G.toString(),ref:G,code:a._`${Q.code==="new RegExp"?BL:(0,JL.useFunc)(b,Q)}(${$}, ${W})`})}kD.usePattern=PL;function FL(b){let{gen:w,data:$,keyword:W,it:Q}=b,G=w.name("valid");if(Q.allErrors){let X=w.let("valid",!0);return D(()=>w.assign(X,!1)),X}return w.var(G,!0),D(()=>w.break()),G;function D(X){let Y=w.const("len",a._`${$}.length`);w.forRange("i",0,Y,(H)=>{b.subschema({keyword:W,dataProp:H,dataPropType:K6.Type.Num},G),w.if((0,a.not)(G),X)})}}kD.validateArray=FL;function KL(b){let{gen:w,schema:$,keyword:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((Y)=>(0,K6.alwaysValidSchema)(Q,Y))&&!Q.opts.unevaluated)return;let D=w.let("valid",!1),X=w.name("_valid");w.block(()=>$.forEach((Y,H)=>{let J=b.subschema({keyword:W,schemaProp:H,compositeRule:!0},X);if(w.assign(D,a._`${D} || ${X}`),!b.mergeValidEvaluated(J,X))w.if((0,a.not)(D))})),b.result(D,()=>b.reset(),()=>b.error(!0))}kD.validateUnion=KL});var fD=j((yD)=>{Object.defineProperty(yD,"__esModule",{value:!0});yD.validateKeywordUsage=yD.validSchemaType=yD.funcKeywordCode=yD.macroKeywordCode=void 0;var Fb=x(),kw=Qw(),kL=Cb(),CL=c1();function uL(b,w){let{gen:$,keyword:W,schema:Q,parentSchema:G,it:D}=b,X=w.macro.call(D.self,Q,G,D),Y=xD($,W,X);if(D.opts.validateSchema!==!1)D.self.validateSchema(X,!0);let H=$.name("valid");b.subschema({schema:X,schemaPath:Fb.nil,errSchemaPath:`${D.errSchemaPath}/${W}`,topSchemaRef:Y,compositeRule:!0},H),b.pass(H,()=>b.error(!0))}yD.macroKeywordCode=uL;function xL(b,w){var $;let{gen:W,keyword:Q,schema:G,parentSchema:D,$data:X,it:Y}=b;hL(Y,w);let H=!X&&w.compile?w.compile.call(Y.self,G,D,Y):w.validate,J=xD(W,Q,H),z=W.let("valid");b.block$data(z,O),b.ok(($=w.valid)!==null&&$!==void 0?$:z);function O(){if(w.errors===!1){if(K(),w.modifying)uD(b);I(()=>b.error())}else{let M=w.async?q():B();if(w.modifying)uD(b);I(()=>yL(b,M))}}function q(){let M=W.let("ruleErrs",null);return W.try(()=>K(Fb._`await `),(v)=>W.assign(z,!1).if(Fb._`${v} instanceof ${Y.ValidationError}`,()=>W.assign(M,Fb._`${v}.errors`),()=>W.throw(v))),M}function B(){let M=Fb._`${J}.errors`;return W.assign(M,null),K(Fb.nil),M}function K(M=w.async?Fb._`await `:Fb.nil){let v=Y.opts.passContext?kw.default.this:kw.default.self,S=!(("compile"in w)&&!X||w.schema===!1);W.assign(z,Fb._`${M}${(0,kL.callValidateCode)(b,J,v,S)}`,w.modifying)}function I(M){var v;W.if((0,Fb.not)((v=w.valid)!==null&&v!==void 0?v:z),M)}}yD.funcKeywordCode=xL;function uD(b){let{gen:w,data:$,it:W}=b;w.if(W.parentData,()=>w.assign($,Fb._`${W.parentData}[${W.parentDataProperty}]`))}function yL(b,w){let{gen:$}=b;$.if(Fb._`Array.isArray(${w})`,()=>{$.assign(kw.default.vErrors,Fb._`${kw.default.vErrors} === null ? ${w} : ${kw.default.vErrors}.concat(${w})`).assign(kw.default.errors,Fb._`${kw.default.vErrors}.length`),(0,CL.extendErrors)(b)},()=>b.error())}function hL({schemaEnv:b},w){if(w.async&&!b.$async)throw Error("async keyword in sync schema")}function xD(b,w,$){if($===void 0)throw Error(`keyword "${w}" failed to compile`);return b.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,Fb.stringify)($)})}function fL(b,w,$=!1){return!w.length||w.some((W)=>W==="array"?Array.isArray(b):W==="object"?b&&typeof b=="object"&&!Array.isArray(b):typeof b==W||$&&typeof b>"u")}yD.validSchemaType=fL;function cL({schema:b,opts:w,self:$,errSchemaPath:W},Q,G){if(Array.isArray(Q.keyword)?!Q.keyword.includes(G):Q.keyword!==G)throw Error("ajv implementation error");let D=Q.dependencies;if(D===null||D===void 0?void 0:D.some((X)=>!Object.prototype.hasOwnProperty.call(b,X)))throw Error(`parent schema must have dependencies of ${G}: ${D.join(",")}`);if(Q.validateSchema){if(!Q.validateSchema(b[G])){let Y=`keyword "${G}" value is invalid at path "${W}": `+$.errorsText(Q.validateSchema.errors);if(w.validateSchema==="log")$.logger.error(Y);else throw Error(Y)}}}yD.validateKeywordUsage=cL});var mD=j((nD)=>{Object.defineProperty(nD,"__esModule",{value:!0});nD.extendSubschemaMode=nD.extendSubschemaData=nD.getSubschema=void 0;var db=x(),cD=i();function iL(b,{keyword:w,schemaProp:$,schema:W,schemaPath:Q,errSchemaPath:G,topSchemaRef:D}){if(w!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let X=b.schema[w];return $===void 0?{schema:X,schemaPath:db._`${b.schemaPath}${(0,db.getProperty)(w)}`,errSchemaPath:`${b.errSchemaPath}/${w}`}:{schema:X[$],schemaPath:db._`${b.schemaPath}${(0,db.getProperty)(w)}${(0,db.getProperty)($)}`,errSchemaPath:`${b.errSchemaPath}/${w}/${(0,cD.escapeFragment)($)}`}}if(W!==void 0){if(Q===void 0||G===void 0||D===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:Q,topSchemaRef:D,errSchemaPath:G}}throw Error('either "keyword" or "schema" must be passed')}nD.getSubschema=iL;function lL(b,w,{dataProp:$,dataPropType:W,data:Q,dataTypes:G,propertyName:D}){if(Q!==void 0&&$!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:X}=w;if($!==void 0){let{errorPath:H,dataPathArr:J,opts:z}=w,O=X.let("data",db._`${w.data}${(0,db.getProperty)($)}`,!0);Y(O),b.errorPath=db.str`${H}${(0,cD.getErrorPath)($,W,z.jsPropertySyntax)}`,b.parentDataProperty=db._`${$}`,b.dataPathArr=[...J,b.parentDataProperty]}if(Q!==void 0){let H=Q instanceof db.Name?Q:X.let("data",Q,!0);if(Y(H),D!==void 0)b.propertyName=D}if(G)b.dataTypes=G;function Y(H){b.data=H,b.dataLevel=w.dataLevel+1,b.dataTypes=[],w.definedProperties=new Set,b.parentData=w.data,b.dataNames=[...w.dataNames,H]}}nD.extendSubschemaData=lL;function pL(b,{jtdDiscriminator:w,jtdMetadata:$,compositeRule:W,createErrors:Q,allErrors:G}){if(W!==void 0)b.compositeRule=W;if(Q!==void 0)b.createErrors=Q;if(G!==void 0)b.allErrors=G;b.jtdDiscriminator=w,b.jtdMetadata=$}nD.extendSubschemaMode=pL});var Z6=j((nT,iD)=>{iD.exports=function b(w,$){if(w===$)return!0;if(w&&$&&typeof w=="object"&&typeof $=="object"){if(w.constructor!==$.constructor)return!1;var W,Q,G;if(Array.isArray(w)){if(W=w.length,W!=$.length)return!1;for(Q=W;Q--!==0;)if(!b(w[Q],$[Q]))return!1;return!0}if(w.constructor===RegExp)return w.source===$.source&&w.flags===$.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===$.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===$.toString();if(G=Object.keys(w),W=G.length,W!==Object.keys($).length)return!1;for(Q=W;Q--!==0;)if(!Object.prototype.hasOwnProperty.call($,G[Q]))return!1;for(Q=W;Q--!==0;){var D=G[Q];if(!b(w[D],$[D]))return!1}return!0}return w!==w&&$!==$}});var pD=j((gT,lD)=>{var jw=lD.exports=function(b,w,$){if(typeof w=="function")$=w,w={};$=w.cb||$;var W=typeof $=="function"?$:$.pre||function(){},Q=$.post||function(){};D$(w,W,Q,b,"",b)};jw.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};jw.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};jw.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};jw.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 D$(b,w,$,W,Q,G,D,X,Y,H){if(W&&typeof W=="object"&&!Array.isArray(W)){w(W,Q,G,D,X,Y,H);for(var J in W){var z=W[J];if(Array.isArray(z)){if(J in jw.arrayKeywords)for(var O=0;O<z.length;O++)D$(b,w,$,z[O],Q+"/"+J+"/"+O,G,Q,J,W,O)}else if(J in jw.propsKeywords){if(z&&typeof z=="object")for(var q in z)D$(b,w,$,z[q],Q+"/"+J+"/"+tL(q),G,Q,J,W,q)}else if(J in jw.keywords||b.allKeys&&!(J in jw.skipKeywords))D$(b,w,$,z,Q+"/"+J,G,Q,J,W)}$(W,Q,G,D,X,Y,H)}}function tL(b){return b.replace(/~/g,"~0").replace(/\//g,"~1")}});var g1=j((rD)=>{Object.defineProperty(rD,"__esModule",{value:!0});rD.getSchemaRefs=rD.resolveUrl=rD.normalizeId=rD._getFullPath=rD.getFullPath=rD.inlineRef=void 0;var rL=i(),eL=Z6(),sL=pD(),aL=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function bU(b,w=!0){if(typeof b=="boolean")return!0;if(w===!0)return!j6(b);if(!w)return!1;return oD(b)<=w}rD.inlineRef=bU;var wU=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function j6(b){for(let w in b){if(wU.has(w))return!0;let $=b[w];if(Array.isArray($)&&$.some(j6))return!0;if(typeof $=="object"&&j6($))return!0}return!1}function oD(b){let w=0;for(let $ in b){if($==="$ref")return 1/0;if(w++,aL.has($))continue;if(typeof b[$]=="object")(0,rL.eachItem)(b[$],(W)=>w+=oD(W));if(w===1/0)return 1/0}return w}function dD(b,w="",$){if($!==!1)w=ew(w);let W=b.parse(w);return tD(b,W)}rD.getFullPath=dD;function tD(b,w){return b.serialize(w).split("#")[0]+"#"}rD._getFullPath=tD;var $U=/#\/?$/;function ew(b){return b?b.replace($U,""):""}rD.normalizeId=ew;function WU(b,w,$){return $=ew($),b.resolve(w,$)}rD.resolveUrl=WU;var QU=/^[a-z_][-a-z0-9._]*$/i;function GU(b,w){if(typeof b=="boolean")return{};let{schemaId:$,uriResolver:W}=this.opts,Q=ew(b[$]||w),G={"":Q},D=dD(W,Q,!1),X={},Y=new Set;return sL(b,{allKeys:!0},(z,O,q,B)=>{if(B===void 0)return;let K=D+O,I=G[B];if(typeof z[$]=="string")I=M.call(this,z[$]);v.call(this,z.$anchor),v.call(this,z.$dynamicAnchor),G[O]=I;function M(S){let h=this.opts.uriResolver.resolve;if(S=ew(I?h(I,S):S),Y.has(S))throw J(S);Y.add(S);let R=this.refs[S];if(typeof R=="string")R=this.refs[R];if(typeof R=="object")H(z,R.schema,S);else if(S!==ew(K))if(S[0]==="#")H(z,X[S],S),X[S]=z;else this.refs[S]=K;return S}function v(S){if(typeof S=="string"){if(!QU.test(S))throw Error(`invalid anchor "${S}"`);M.call(this,`#${S}`)}}}),X;function H(z,O,q){if(O!==void 0&&!eL(z,O))throw J(q)}function J(z){return Error(`reference "${z}" resolves to more than one schema`)}}rD.getSchemaRefs=GU});var l1=j((AX)=>{Object.defineProperty(AX,"__esModule",{value:!0});AX.getData=AX.KeywordCxt=AX.validateFunctionCode=void 0;var $X=LD(),sD=n1(),N6=U6(),X$=n1(),zU=SD(),i1=fD(),V6=mD(),E=x(),k=Qw(),AU=g1(),Gw=i(),m1=c1();function OU(b){if(GX(b)){if(DX(b),QX(b)){UU(b);return}}WX(b,()=>(0,$X.topBoolOrEmptySchema)(b))}AX.validateFunctionCode=OU;function WX({gen:b,validateName:w,schema:$,schemaEnv:W,opts:Q},G){if(Q.code.es5)b.func(w,E._`${k.default.data}, ${k.default.valCxt}`,W.$async,()=>{b.code(E._`"use strict"; ${aD($,Q)}`),LU(b,Q),b.code(G)});else b.func(w,E._`${k.default.data}, ${qU(Q)}`,W.$async,()=>b.code(aD($,Q)).code(G))}function qU(b){return E._`{${k.default.instancePath}="", ${k.default.parentData}, ${k.default.parentDataProperty}, ${k.default.rootData}=${k.default.data}${b.dynamicRef?E._`, ${k.default.dynamicAnchors}={}`:E.nil}}={}`}function LU(b,w){b.if(k.default.valCxt,()=>{if(b.var(k.default.instancePath,E._`${k.default.valCxt}.${k.default.instancePath}`),b.var(k.default.parentData,E._`${k.default.valCxt}.${k.default.parentData}`),b.var(k.default.parentDataProperty,E._`${k.default.valCxt}.${k.default.parentDataProperty}`),b.var(k.default.rootData,E._`${k.default.valCxt}.${k.default.rootData}`),w.dynamicRef)b.var(k.default.dynamicAnchors,E._`${k.default.valCxt}.${k.default.dynamicAnchors}`)},()=>{if(b.var(k.default.instancePath,E._`""`),b.var(k.default.parentData,E._`undefined`),b.var(k.default.parentDataProperty,E._`undefined`),b.var(k.default.rootData,k.default.data),w.dynamicRef)b.var(k.default.dynamicAnchors,E._`{}`)})}function UU(b){let{schema:w,opts:$,gen:W}=b;WX(b,()=>{if($.$comment&&w.$comment)YX(b);if(MU(b),W.let(k.default.vErrors,null),W.let(k.default.errors,0),$.unevaluated)BU(b);XX(b),jU(b)});return}function BU(b){let{gen:w,validateName:$}=b;b.evaluated=w.const("evaluated",E._`${$}.evaluated`),w.if(E._`${b.evaluated}.dynamicProps`,()=>w.assign(E._`${b.evaluated}.props`,E._`undefined`)),w.if(E._`${b.evaluated}.dynamicItems`,()=>w.assign(E._`${b.evaluated}.items`,E._`undefined`))}function aD(b,w){let $=typeof b=="object"&&b[w.schemaId];return $&&(w.code.source||w.code.process)?E._`/*# sourceURL=${$} */`:E.nil}function PU(b,w){if(GX(b)){if(DX(b),QX(b)){FU(b,w);return}}(0,$X.boolOrEmptySchema)(b,w)}function QX({schema:b,self:w}){if(typeof b=="boolean")return!b;for(let $ in b)if(w.RULES.all[$])return!0;return!1}function GX(b){return typeof b.schema!="boolean"}function FU(b,w){let{schema:$,gen:W,opts:Q}=b;if(Q.$comment&&$.$comment)YX(b);IU(b),ZU(b);let G=W.const("_errs",k.default.errors);XX(b,G),W.var(w,E._`${G} === ${k.default.errors}`)}function DX(b){(0,Gw.checkUnknownRules)(b),KU(b)}function XX(b,w){if(b.opts.jtd)return bX(b,[],!1,w);let $=(0,sD.getSchemaTypes)(b.schema),W=(0,sD.coerceAndCheckDataType)(b,$);bX(b,$,!W,w)}function KU(b){let{schema:w,errSchemaPath:$,opts:W,self:Q}=b;if(w.$ref&&W.ignoreKeywordsWithRef&&(0,Gw.schemaHasRulesButRef)(w,Q.RULES))Q.logger.warn(`$ref: keywords ignored in schema at path "${$}"`)}function MU(b){let{schema:w,opts:$}=b;if(w.default!==void 0&&$.useDefaults&&$.strictSchema)(0,Gw.checkStrictMode)(b,"default is ignored in the schema root")}function IU(b){let w=b.schema[b.opts.schemaId];if(w)b.baseId=(0,AU.resolveUrl)(b.opts.uriResolver,b.baseId,w)}function ZU(b){if(b.schema.$async&&!b.schemaEnv.$async)throw Error("async schema in sync schema")}function YX({gen:b,schemaEnv:w,schema:$,errSchemaPath:W,opts:Q}){let G=$.$comment;if(Q.$comment===!0)b.code(E._`${k.default.self}.logger.log(${G})`);else if(typeof Q.$comment=="function"){let D=E.str`${W}/$comment`,X=b.scopeValue("root",{ref:w.root});b.code(E._`${k.default.self}.opts.$comment(${G}, ${D}, ${X}.schema)`)}}function jU(b){let{gen:w,schemaEnv:$,validateName:W,ValidationError:Q,opts:G}=b;if($.$async)w.if(E._`${k.default.errors} === 0`,()=>w.return(k.default.data),()=>w.throw(E._`new ${Q}(${k.default.vErrors})`));else{if(w.assign(E._`${W}.errors`,k.default.vErrors),G.unevaluated)VU(b);w.return(E._`${k.default.errors} === 0`)}}function VU({gen:b,evaluated:w,props:$,items:W}){if($ instanceof E.Name)b.assign(E._`${w}.props`,$);if(W instanceof E.Name)b.assign(E._`${w}.items`,W)}function bX(b,w,$,W){let{gen:Q,schema:G,data:D,allErrors:X,opts:Y,self:H}=b,{RULES:J}=H;if(G.$ref&&(Y.ignoreKeywordsWithRef||!(0,Gw.schemaHasRulesButRef)(G,J))){Q.block(()=>JX(b,"$ref",J.all.$ref.definition));return}if(!Y.jtd)NU(b,w);Q.block(()=>{for(let O of J.rules)z(O);z(J.post)});function z(O){if(!(0,N6.shouldUseGroup)(G,O))return;if(O.type){if(Q.if((0,X$.checkDataType)(O.type,D,Y.strictNumbers)),wX(b,O),w.length===1&&w[0]===O.type&&$)Q.else(),(0,X$.reportTypeError)(b);Q.endIf()}else wX(b,O);if(!X)Q.if(E._`${k.default.errors} === ${W||0}`)}}function wX(b,w){let{gen:$,schema:W,opts:{useDefaults:Q}}=b;if(Q)(0,zU.assignDefaults)(b,w.type);$.block(()=>{for(let G of w.rules)if((0,N6.shouldUseRule)(W,G))JX(b,G.keyword,G.definition,w.type)})}function NU(b,w){if(b.schemaEnv.meta||!b.opts.strictTypes)return;if(TU(b,w),!b.opts.allowUnionTypes)EU(b,w);_U(b,b.dataTypes)}function TU(b,w){if(!w.length)return;if(!b.dataTypes.length){b.dataTypes=w;return}w.forEach(($)=>{if(!HX(b.dataTypes,$))T6(b,`type "${$}" not allowed by context "${b.dataTypes.join(",")}"`)}),RU(b,w)}function EU(b,w){if(w.length>1&&!(w.length===2&&w.includes("null")))T6(b,"use allowUnionTypes to allow union type keyword")}function _U(b,w){let $=b.self.RULES.all;for(let W in $){let Q=$[W];if(typeof Q=="object"&&(0,N6.shouldUseRule)(b.schema,Q)){let{type:G}=Q.definition;if(G.length&&!G.some((D)=>SU(w,D)))T6(b,`missing type "${G.join(",")}" for keyword "${W}"`)}}}function SU(b,w){return b.includes(w)||w==="number"&&b.includes("integer")}function HX(b,w){return b.includes(w)||w==="integer"&&b.includes("number")}function RU(b,w){let $=[];for(let W of b.dataTypes)if(HX(w,W))$.push(W);else if(w.includes("integer")&&W==="number")$.push("integer");b.dataTypes=$}function T6(b,w){let $=b.schemaEnv.baseId+b.errSchemaPath;w+=` at "${$}" (strictTypes)`,(0,Gw.checkStrictMode)(b,w,b.opts.strictTypes)}class E6{constructor(b,w,$){if((0,i1.validateKeywordUsage)(b,w,$),this.gen=b.gen,this.allErrors=b.allErrors,this.keyword=$,this.data=b.data,this.schema=b.schema[$],this.$data=w.$data&&b.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Gw.schemaRefOrVal)(b,this.schema,$,this.$data),this.schemaType=w.schemaType,this.parentSchema=b.schema,this.params={},this.it=b,this.def=w,this.$data)this.schemaCode=b.gen.const("vSchema",zX(this.$data,b));else if(this.schemaCode=this.schemaValue,!(0,i1.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${$} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=b.gen.const("_errs",k.default.errors)}result(b,w,$){this.failResult((0,E.not)(b),w,$)}failResult(b,w,$){if(this.gen.if(b),$)$();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(b,w){this.failResult((0,E.not)(b),void 0,w)}fail(b){if(b===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(b),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(b){if(!this.$data)return this.fail(b);let{schemaCode:w}=this;this.fail(E._`${w} !== undefined && (${(0,E.or)(this.invalid$data(),b)})`)}error(b,w,$){if(w){this.setParams(w),this._error(b,$),this.setParams({});return}this._error(b,$)}_error(b,w){(b?m1.reportExtraError:m1.reportError)(this,this.def.error,w)}$dataError(){(0,m1.reportError)(this,this.def.$dataError||m1.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,m1.resetErrorsCount)(this.gen,this.errsCount)}ok(b){if(!this.allErrors)this.gen.if(b)}setParams(b,w){if(w)Object.assign(this.params,b);else this.params=b}block$data(b,w,$=E.nil){this.gen.block(()=>{this.check$data(b,$),w()})}check$data(b=E.nil,w=E.nil){if(!this.$data)return;let{gen:$,schemaCode:W,schemaType:Q,def:G}=this;if($.if((0,E.or)(E._`${W} === undefined`,w)),b!==E.nil)$.assign(b,!0);if(Q.length||G.validateSchema){if($.elseIf(this.invalid$data()),this.$dataError(),b!==E.nil)$.assign(b,!1)}$.else()}invalid$data(){let{gen:b,schemaCode:w,schemaType:$,def:W,it:Q}=this;return(0,E.or)(G(),D());function G(){if($.length){if(!(w instanceof E.Name))throw Error("ajv implementation error");let X=Array.isArray($)?$:[$];return E._`${(0,X$.checkDataTypes)(X,w,Q.opts.strictNumbers,X$.DataType.Wrong)}`}return E.nil}function D(){if(W.validateSchema){let X=b.scopeValue("validate$data",{ref:W.validateSchema});return E._`!${X}(${w})`}return E.nil}}subschema(b,w){let $=(0,V6.getSubschema)(this.it,b);(0,V6.extendSubschemaData)($,this.it,b),(0,V6.extendSubschemaMode)($,b);let W={...this.it,...$,items:void 0,props:void 0};return PU(W,w),W}mergeEvaluated(b,w){let{it:$,gen:W}=this;if(!$.opts.unevaluated)return;if($.props!==!0&&b.props!==void 0)$.props=Gw.mergeEvaluated.props(W,b.props,$.props,w);if($.items!==!0&&b.items!==void 0)$.items=Gw.mergeEvaluated.items(W,b.items,$.items,w)}mergeValidEvaluated(b,w){let{it:$,gen:W}=this;if($.opts.unevaluated&&($.props!==!0||$.items!==!0))return W.if(w,()=>this.mergeEvaluated(b,E.Name)),!0}}AX.KeywordCxt=E6;function JX(b,w,$,W){let Q=new E6(b,$,w);if("code"in $)$.code(Q,W);else if(Q.$data&&$.validate)(0,i1.funcKeywordCode)(Q,$);else if("macro"in $)(0,i1.macroKeywordCode)(Q,$);else if($.compile||$.validate)(0,i1.funcKeywordCode)(Q,$)}var vU=/^\/(?:[^~]|~0|~1)*$/,kU=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function zX(b,{dataLevel:w,dataNames:$,dataPathArr:W}){let Q,G;if(b==="")return k.default.rootData;if(b[0]==="/"){if(!vU.test(b))throw Error(`Invalid JSON-pointer: ${b}`);Q=b,G=k.default.rootData}else{let H=kU.exec(b);if(!H)throw Error(`Invalid JSON-pointer: ${b}`);let J=+H[1];if(Q=H[2],Q==="#"){if(J>=w)throw Error(Y("property/index",J));return W[w-J]}if(J>w)throw Error(Y("data",J));if(G=$[w-J],!Q)return G}let D=G,X=Q.split("/");for(let H of X)if(H)G=E._`${G}${(0,E.getProperty)((0,Gw.unescapeJsonPointer)(H))}`,D=E._`${D} && ${G}`;return D;function Y(H,J){return`Cannot access ${H} ${J} levels up, current level is ${w}`}}AX.getData=zX});var Y$=j((LX)=>{Object.defineProperty(LX,"__esModule",{value:!0});class qX extends Error{constructor(b){super("validation failed");this.errors=b,this.ajv=this.validation=!0}}LX.default=qX});var p1=j((BX)=>{Object.defineProperty(BX,"__esModule",{value:!0});var _6=g1();class UX extends Error{constructor(b,w,$,W){super(W||`can't resolve reference ${$} from id ${w}`);this.missingRef=(0,_6.resolveUrl)(b,w,$),this.missingSchema=(0,_6.normalizeId)((0,_6.getFullPath)(b,this.missingRef))}}BX.default=UX});var J$=j((KX)=>{Object.defineProperty(KX,"__esModule",{value:!0});KX.resolveSchema=KX.getCompilingSchema=KX.resolveRef=KX.compileSchema=KX.SchemaEnv=void 0;var cb=x(),hU=Y$(),Cw=Qw(),nb=g1(),PX=i(),fU=l1();class o1{constructor(b){var w;this.refs={},this.dynamicAnchors={};let $;if(typeof b.schema=="object")$=b.schema;this.schema=b.schema,this.schemaId=b.schemaId,this.root=b.root||this,this.baseId=(w=b.baseId)!==null&&w!==void 0?w:(0,nb.normalizeId)($===null||$===void 0?void 0:$[b.schemaId||"$id"]),this.schemaPath=b.schemaPath,this.localRefs=b.localRefs,this.meta=b.meta,this.$async=$===null||$===void 0?void 0:$.$async,this.refs={}}}KX.SchemaEnv=o1;function R6(b){let w=FX.call(this,b);if(w)return w;let $=(0,nb.getFullPath)(this.opts.uriResolver,b.root.baseId),{es5:W,lines:Q}=this.opts.code,{ownProperties:G}=this.opts,D=new cb.CodeGen(this.scope,{es5:W,lines:Q,ownProperties:G}),X;if(b.$async)X=D.scopeValue("Error",{ref:hU.default,code:cb._`require("ajv/dist/runtime/validation_error").default`});let Y=D.scopeName("validate");b.validateName=Y;let H={gen:D,allErrors:this.opts.allErrors,data:Cw.default.data,parentData:Cw.default.parentData,parentDataProperty:Cw.default.parentDataProperty,dataNames:[Cw.default.data],dataPathArr:[cb.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:D.scopeValue("schema",this.opts.code.source===!0?{ref:b.schema,code:(0,cb.stringify)(b.schema)}:{ref:b.schema}),validateName:Y,ValidationError:X,schema:b.schema,schemaEnv:b,rootId:$,baseId:b.baseId||$,schemaPath:cb.nil,errSchemaPath:b.schemaPath||(this.opts.jtd?"":"#"),errorPath:cb._`""`,opts:this.opts,self:this},J;try{this._compilations.add(b),(0,fU.validateFunctionCode)(H),D.optimize(this.opts.code.optimize);let z=D.toString();if(J=`${D.scopeRefs(Cw.default.scope)}return ${z}`,this.opts.code.process)J=this.opts.code.process(J,b);let q=Function(`${Cw.default.self}`,`${Cw.default.scope}`,J)(this,this.scope.get());if(this.scope.value(Y,{ref:q}),q.errors=null,q.schema=b.schema,q.schemaEnv=b,b.$async)q.$async=!0;if(this.opts.code.source===!0)q.source={validateName:Y,validateCode:z,scopeValues:D._values};if(this.opts.unevaluated){let{props:B,items:K}=H;if(q.evaluated={props:B instanceof cb.Name?void 0:B,items:K instanceof cb.Name?void 0:K,dynamicProps:B instanceof cb.Name,dynamicItems:K instanceof cb.Name},q.source)q.source.evaluated=(0,cb.stringify)(q.evaluated)}return b.validate=q,b}catch(z){if(delete b.validate,delete b.validateName,J)this.logger.error("Error compiling schema, function code:",J);throw z}finally{this._compilations.delete(b)}}KX.compileSchema=R6;function cU(b,w,$){var W;$=(0,nb.resolveUrl)(this.opts.uriResolver,w,$);let Q=b.refs[$];if(Q)return Q;let G=mU.call(this,b,$);if(G===void 0){let D=(W=b.localRefs)===null||W===void 0?void 0:W[$],{schemaId:X}=this.opts;if(D)G=new o1({schema:D,schemaId:X,root:b,baseId:w})}if(G===void 0)return;return b.refs[$]=nU.call(this,G)}KX.resolveRef=cU;function nU(b){if((0,nb.inlineRef)(b.schema,this.opts.inlineRefs))return b.schema;return b.validate?b:R6.call(this,b)}function FX(b){for(let w of this._compilations)if(gU(w,b))return w}KX.getCompilingSchema=FX;function gU(b,w){return b.schema===w.schema&&b.root===w.root&&b.baseId===w.baseId}function mU(b,w){let $;while(typeof($=this.refs[w])=="string")w=$;return $||this.schemas[w]||H$.call(this,b,w)}function H$(b,w){let $=this.opts.uriResolver.parse(w),W=(0,nb._getFullPath)(this.opts.uriResolver,$),Q=(0,nb.getFullPath)(this.opts.uriResolver,b.baseId,void 0);if(Object.keys(b.schema).length>0&&W===Q)return S6.call(this,$,b);let G=(0,nb.normalizeId)(W),D=this.refs[G]||this.schemas[G];if(typeof D=="string"){let X=H$.call(this,b,D);if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;return S6.call(this,$,X)}if(typeof(D===null||D===void 0?void 0:D.schema)!=="object")return;if(!D.validate)R6.call(this,D);if(G===(0,nb.normalizeId)(w)){let{schema:X}=D,{schemaId:Y}=this.opts,H=X[Y];if(H)Q=(0,nb.resolveUrl)(this.opts.uriResolver,Q,H);return new o1({schema:X,schemaId:Y,root:b,baseId:Q})}return S6.call(this,$,D)}KX.resolveSchema=H$;var iU=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function S6(b,{baseId:w,schema:$,root:W}){var Q;if(((Q=b.fragment)===null||Q===void 0?void 0:Q[0])!=="/")return;for(let X of b.fragment.slice(1).split("/")){if(typeof $==="boolean")return;let Y=$[(0,PX.unescapeFragment)(X)];if(Y===void 0)return;$=Y;let H=typeof $==="object"&&$[this.opts.schemaId];if(!iU.has(X)&&H)w=(0,nb.resolveUrl)(this.opts.uriResolver,w,H)}let G;if(typeof $!="boolean"&&$.$ref&&!(0,PX.schemaHasRulesButRef)($,this.RULES)){let X=(0,nb.resolveUrl)(this.opts.uriResolver,w,$.$ref);G=H$.call(this,W,X)}let{schemaId:D}=this.opts;if(G=G||new o1({schema:$,schemaId:D,root:W,baseId:w}),G.schema!==G.root.schema)return G;return}});var IX=j((dT,tU)=>{tU.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 k6=j((tT,NX)=>{var rU=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),jX=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 v6(b){let w="",$=0,W=0;for(W=0;W<b.length;W++){if($=b[W].charCodeAt(0),$===48)continue;if(!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";w+=b[W];break}for(W+=1;W<b.length;W++){if($=b[W].charCodeAt(0),!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";w+=b[W]}return w}var eU=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ZX(b){return b.length=0,!0}function sU(b,w,$){if(b.length){let W=v6(b);if(W!=="")w.push(W);else return $.error=!0,!1;b.length=0}return!0}function aU(b){let w=0,$={error:!1,address:"",zone:""},W=[],Q=[],G=!1,D=!1,X=sU;for(let Y=0;Y<b.length;Y++){let H=b[Y];if(H==="["||H==="]")continue;if(H===":"){if(G===!0)D=!0;if(!X(Q,W,$))break;if(++w>7){$.error=!0;break}if(Y>0&&b[Y-1]===":")G=!0;W.push(":");continue}else if(H==="%"){if(!X(Q,W,$))break;X=ZX}else{Q.push(H);continue}}if(Q.length)if(X===ZX)$.zone=Q.join("");else if(D)W.push(Q.join(""));else W.push(v6(Q));return $.address=W.join(""),$}function VX(b){if(b3(b,":")<2)return{host:b,isIPV6:!1};let w=aU(b);if(!w.error){let{address:$,address:W}=w;if(w.zone)$+="%"+w.zone,W+="%25"+w.zone;return{host:$,isIPV6:!0,escapedHost:W}}else return{host:b,isIPV6:!1}}function b3(b,w){let $=0;for(let W=0;W<b.length;W++)if(b[W]===w)$++;return $}function w3(b){let w=b,$=[],W=-1,Q=0;while(Q=w.length){if(Q===1)if(w===".")break;else if(w==="/"){$.push("/");break}else{$.push(w);break}else if(Q===2){if(w[0]==="."){if(w[1]===".")break;else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."||w[1]==="/"){$.push("/");break}}}else if(Q===3){if(w==="/.."){if($.length!==0)$.pop();$.push("/");break}}if(w[0]==="."){if(w[1]==="."){if(w[2]==="/"){w=w.slice(3);continue}}else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."){if(w[2]==="/"){w=w.slice(2);continue}else if(w[2]==="."){if(w[3]==="/"){if(w=w.slice(3),$.length!==0)$.pop();continue}}}}if((W=w.indexOf("/",1))===-1){$.push(w);break}else $.push(w.slice(0,W)),w=w.slice(W)}return $.join("")}function $3(b,w){let $=w!==!0?escape:unescape;if(b.scheme!==void 0)b.scheme=$(b.scheme);if(b.userinfo!==void 0)b.userinfo=$(b.userinfo);if(b.host!==void 0)b.host=$(b.host);if(b.path!==void 0)b.path=$(b.path);if(b.query!==void 0)b.query=$(b.query);if(b.fragment!==void 0)b.fragment=$(b.fragment);return b}function W3(b){let w=[];if(b.userinfo!==void 0)w.push(b.userinfo),w.push("@");if(b.host!==void 0){let $=unescape(b.host);if(!jX($)){let W=VX($);if(W.isIPV6===!0)$=`[${W.escapedHost}]`;else $=b.host}w.push($)}if(typeof b.port==="number"||typeof b.port==="string")w.push(":"),w.push(String(b.port));return w.length?w.join(""):void 0}NX.exports={nonSimpleDomain:eU,recomposeAuthority:W3,normalizeComponentEncoding:$3,removeDotSegments:w3,isIPv4:jX,isUUID:rU,normalizeIPv6:VX,stringArrayToHexStripped:v6}});var RX=j((rT,SX)=>{var{isUUID:Q3}=k6(),G3=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,D3=["http","https","ws","wss","urn","urn:uuid"];function X3(b){return D3.indexOf(b)!==-1}function C6(b){if(b.secure===!0)return!0;else if(b.secure===!1)return!1;else if(b.scheme)return b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S");else return!1}function TX(b){if(!b.host)b.error=b.error||"HTTP URIs must have a host.";return b}function EX(b){let w=String(b.scheme).toLowerCase()==="https";if(b.port===(w?443:80)||b.port==="")b.port=void 0;if(!b.path)b.path="/";return b}function Y3(b){return b.secure=C6(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function H3(b){if(b.port===(C6(b)?443:80)||b.port==="")b.port=void 0;if(typeof b.secure==="boolean")b.scheme=b.secure?"wss":"ws",b.secure=void 0;if(b.resourceName){let[w,$]=b.resourceName.split("?");b.path=w&&w!=="/"?w:void 0,b.query=$,b.resourceName=void 0}return b.fragment=void 0,b}function J3(b,w){if(!b.path)return b.error="URN can not be parsed",b;let $=b.path.match(G3);if($){let W=w.scheme||b.scheme||"urn";b.nid=$[1].toLowerCase(),b.nss=$[2];let Q=`${W}:${w.nid||b.nid}`,G=u6(Q);if(b.path=void 0,G)b=G.parse(b,w)}else b.error=b.error||"URN can not be parsed.";return b}function z3(b,w){if(b.nid===void 0)throw Error("URN without nid cannot be serialized");let $=w.scheme||b.scheme||"urn",W=b.nid.toLowerCase(),Q=`${$}:${w.nid||W}`,G=u6(Q);if(G)b=G.serialize(b,w);let D=b,X=b.nss;return D.path=`${W||w.nid}:${X}`,w.skipEscape=!0,D}function A3(b,w){let $=b;if($.uuid=$.nss,$.nss=void 0,!w.tolerant&&(!$.uuid||!Q3($.uuid)))$.error=$.error||"UUID is not valid.";return $}function O3(b){let w=b;return w.nss=(b.uuid||"").toLowerCase(),w}var _X={scheme:"http",domainHost:!0,parse:TX,serialize:EX},q3={scheme:"https",domainHost:_X.domainHost,parse:TX,serialize:EX},z$={scheme:"ws",domainHost:!0,parse:Y3,serialize:H3},L3={scheme:"wss",domainHost:z$.domainHost,parse:z$.parse,serialize:z$.serialize},U3={scheme:"urn",parse:J3,serialize:z3,skipNormalize:!0},B3={scheme:"urn:uuid",parse:A3,serialize:O3,skipNormalize:!0},A$={http:_X,https:q3,ws:z$,wss:L3,urn:U3,"urn:uuid":B3};Object.setPrototypeOf(A$,null);function u6(b){return b&&(A$[b]||A$[b.toLowerCase()])||void 0}SX.exports={wsIsSecure:C6,SCHEMES:A$,isValidSchemeName:X3,getSchemeHandler:u6}});var CX=j((eT,q$)=>{var{normalizeIPv6:P3,removeDotSegments:d1,recomposeAuthority:F3,normalizeComponentEncoding:O$,isIPv4:K3,nonSimpleDomain:M3}=k6(),{SCHEMES:I3,getSchemeHandler:vX}=RX();function Z3(b,w){if(typeof b==="string")b=tb(Dw(b,w),w);else if(typeof b==="object")b=Dw(tb(b,w),w);return b}function j3(b,w,$){let W=$?Object.assign({scheme:"null"},$):{scheme:"null"},Q=kX(Dw(b,W),Dw(w,W),W,!0);return W.skipEscape=!0,tb(Q,W)}function kX(b,w,$,W){let Q={};if(!W)b=Dw(tb(b,$),$),w=Dw(tb(w,$),$);if($=$||{},!$.tolerant&&w.scheme)Q.scheme=w.scheme,Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port,Q.path=d1(w.path||""),Q.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port,Q.path=d1(w.path||""),Q.query=w.query;else{if(!w.path)if(Q.path=b.path,w.query!==void 0)Q.query=w.query;else Q.query=b.query;else{if(w.path[0]==="/")Q.path=d1(w.path);else{if((b.userinfo!==void 0||b.host!==void 0||b.port!==void 0)&&!b.path)Q.path="/"+w.path;else if(!b.path)Q.path=w.path;else Q.path=b.path.slice(0,b.path.lastIndexOf("/")+1)+w.path;Q.path=d1(Q.path)}Q.query=w.query}Q.userinfo=b.userinfo,Q.host=b.host,Q.port=b.port}Q.scheme=b.scheme}return Q.fragment=w.fragment,Q}function V3(b,w,$){if(typeof b==="string")b=unescape(b),b=tb(O$(Dw(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=tb(O$(b,!0),{...$,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=tb(O$(Dw(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=tb(O$(w,!0),{...$,skipEscape:!0});return b.toLowerCase()===w.toLowerCase()}function tb(b,w){let $={host:b.host,scheme:b.scheme,userinfo:b.userinfo,port:b.port,path:b.path,query:b.query,nid:b.nid,nss:b.nss,uuid:b.uuid,fragment:b.fragment,reference:b.reference,resourceName:b.resourceName,secure:b.secure,error:""},W=Object.assign({},w),Q=[],G=vX(W.scheme||$.scheme);if(G&&G.serialize)G.serialize($,W);if($.path!==void 0)if(!W.skipEscape){if($.path=escape($.path),$.scheme!==void 0)$.path=$.path.split("%3A").join(":")}else $.path=unescape($.path);if(W.reference!=="suffix"&&$.scheme)Q.push($.scheme,":");let D=F3($);if(D!==void 0){if(W.reference!=="suffix")Q.push("//");if(Q.push(D),$.path&&$.path[0]!=="/")Q.push("/")}if($.path!==void 0){let X=$.path;if(!W.absolutePath&&(!G||!G.absolutePath))X=d1(X);if(D===void 0&&X[0]==="/"&&X[1]==="/")X="/%2F"+X.slice(2);Q.push(X)}if($.query!==void 0)Q.push("?",$.query);if($.fragment!==void 0)Q.push("#",$.fragment);return Q.join("")}var N3=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Dw(b,w){let $=Object.assign({},w),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},Q=!1;if($.reference==="suffix")if($.scheme)b=$.scheme+":"+b;else b="//"+b;let G=b.match(N3);if(G){if(W.scheme=G[1],W.userinfo=G[3],W.host=G[4],W.port=parseInt(G[5],10),W.path=G[6]||"",W.query=G[7],W.fragment=G[8],isNaN(W.port))W.port=G[5];if(W.host)if(K3(W.host)===!1){let Y=P3(W.host);W.host=Y.host.toLowerCase(),Q=Y.isIPV6}else Q=!0;if(W.scheme===void 0&&W.userinfo===void 0&&W.host===void 0&&W.port===void 0&&W.query===void 0&&!W.path)W.reference="same-document";else if(W.scheme===void 0)W.reference="relative";else if(W.fragment===void 0)W.reference="absolute";else W.reference="uri";if($.reference&&$.reference!=="suffix"&&$.reference!==W.reference)W.error=W.error||"URI is not a "+$.reference+" reference.";let D=vX($.scheme||W.scheme);if(!$.unicodeSupport&&(!D||!D.unicodeSupport)){if(W.host&&($.domainHost||D&&D.domainHost)&&Q===!1&&M3(W.host))try{W.host=URL.domainToASCII(W.host.toLowerCase())}catch(X){W.error=W.error||"Host's domain name can not be converted to ASCII: "+X}}if(!D||D&&!D.skipNormalize){if(b.indexOf("%")!==-1){if(W.scheme!==void 0)W.scheme=unescape(W.scheme);if(W.host!==void 0)W.host=unescape(W.host)}if(W.path)W.path=escape(unescape(W.path));if(W.fragment)W.fragment=encodeURI(decodeURIComponent(W.fragment))}if(D&&D.parse)D.parse(W,$)}else W.error=W.error||"URI can not be parsed.";return W}var x6={SCHEMES:I3,normalize:Z3,resolve:j3,resolveComponent:kX,equal:V3,serialize:tb,parse:Dw};q$.exports=x6;q$.exports.default=x6;q$.exports.fastUri=x6});var yX=j((xX)=>{Object.defineProperty(xX,"__esModule",{value:!0});var uX=CX();uX.code='require("ajv/dist/runtime/uri").default';xX.default=uX});var lX=j((Xw)=>{Object.defineProperty(Xw,"__esModule",{value:!0});Xw.CodeGen=Xw.Name=Xw.nil=Xw.stringify=Xw.str=Xw._=Xw.KeywordCxt=void 0;var E3=l1();Object.defineProperty(Xw,"KeywordCxt",{enumerable:!0,get:function(){return E3.KeywordCxt}});var sw=x();Object.defineProperty(Xw,"_",{enumerable:!0,get:function(){return sw._}});Object.defineProperty(Xw,"str",{enumerable:!0,get:function(){return sw.str}});Object.defineProperty(Xw,"stringify",{enumerable:!0,get:function(){return sw.stringify}});Object.defineProperty(Xw,"nil",{enumerable:!0,get:function(){return sw.nil}});Object.defineProperty(Xw,"Name",{enumerable:!0,get:function(){return sw.Name}});Object.defineProperty(Xw,"CodeGen",{enumerable:!0,get:function(){return sw.CodeGen}});var _3=Y$(),gX=p1(),S3=L6(),t1=J$(),R3=x(),r1=g1(),L$=n1(),h6=i(),hX=IX(),v3=yX(),mX=(b,w)=>new RegExp(b,w);mX.code="new RegExp";var k3=["removeAdditional","useDefaults","coerceTypes"],C3=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),u3={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."},x3={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},fX=200;function y3(b){var w,$,W,Q,G,D,X,Y,H,J,z,O,q,B,K,I,M,v,S,h,R,pb,sb,l$,p$;let J1=b.strict,o$=(w=b.code)===null||w===void 0?void 0:w.optimize,_W=o$===!0||o$===void 0?1:o$||0,SW=(W=($=b.code)===null||$===void 0?void 0:$.regExp)!==null&&W!==void 0?W:mX,uz=(Q=b.uriResolver)!==null&&Q!==void 0?Q:v3.default;return{strictSchema:(D=(G=b.strictSchema)!==null&&G!==void 0?G:J1)!==null&&D!==void 0?D:!0,strictNumbers:(Y=(X=b.strictNumbers)!==null&&X!==void 0?X:J1)!==null&&Y!==void 0?Y:!0,strictTypes:(J=(H=b.strictTypes)!==null&&H!==void 0?H:J1)!==null&&J!==void 0?J:"log",strictTuples:(O=(z=b.strictTuples)!==null&&z!==void 0?z:J1)!==null&&O!==void 0?O:"log",strictRequired:(B=(q=b.strictRequired)!==null&&q!==void 0?q:J1)!==null&&B!==void 0?B:!1,code:b.code?{...b.code,optimize:_W,regExp:SW}:{optimize:_W,regExp:SW},loopRequired:(K=b.loopRequired)!==null&&K!==void 0?K:fX,loopEnum:(I=b.loopEnum)!==null&&I!==void 0?I:fX,meta:(M=b.meta)!==null&&M!==void 0?M:!0,messages:(v=b.messages)!==null&&v!==void 0?v:!0,inlineRefs:(S=b.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(h=b.schemaId)!==null&&h!==void 0?h:"$id",addUsedSchema:(R=b.addUsedSchema)!==null&&R!==void 0?R:!0,validateSchema:(pb=b.validateSchema)!==null&&pb!==void 0?pb:!0,validateFormats:(sb=b.validateFormats)!==null&&sb!==void 0?sb:!0,unicodeRegExp:(l$=b.unicodeRegExp)!==null&&l$!==void 0?l$:!0,int32range:(p$=b.int32range)!==null&&p$!==void 0?p$:!0,uriResolver:uz}}class U${constructor(b={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,b=this.opts={...b,...y3(b)};let{es5:w,lines:$}=this.opts.code;this.scope=new R3.ValueScope({scope:{},prefixes:C3,es5:w,lines:$}),this.logger=m3(b.logger);let W=b.validateFormats;if(b.validateFormats=!1,this.RULES=(0,S3.getRules)(),cX.call(this,u3,b,"NOT SUPPORTED"),cX.call(this,x3,b,"DEPRECATED","warn"),this._metaOpts=n3.call(this),b.formats)f3.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),b.keywords)c3.call(this,b.keywords);if(typeof b.meta=="object")this.addMetaSchema(b.meta);h3.call(this),b.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:b,meta:w,schemaId:$}=this.opts,W=hX;if($==="id")W={...hX},W.id=W.$id,delete W.$id;if(w&&b)this.addMetaSchema(W,W[$],!1)}defaultMeta(){let{meta:b,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof b=="object"?b[w]||b:void 0}validate(b,w){let $;if(typeof b=="string"){if($=this.getSchema(b),!$)throw Error(`no schema with key or ref "${b}"`)}else $=this.compile(b);let W=$(w);if(!("$async"in $))this.errors=$.errors;return W}compile(b,w){let $=this._addSchema(b,w);return $.validate||this._compileSchemaEnv($)}compileAsync(b,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:$}=this.opts;return W.call(this,b,w);async function W(H,J){await Q.call(this,H.$schema);let z=this._addSchema(H,J);return z.validate||G.call(this,z)}async function Q(H){if(H&&!this.getSchema(H))await W.call(this,{$ref:H},!0)}async function G(H){try{return this._compileSchemaEnv(H)}catch(J){if(!(J instanceof gX.default))throw J;return D.call(this,J),await X.call(this,J.missingSchema),G.call(this,H)}}function D({missingSchema:H,missingRef:J}){if(this.refs[H])throw Error(`AnySchema ${H} is loaded but ${J} cannot be resolved`)}async function X(H){let J=await Y.call(this,H);if(!this.refs[H])await Q.call(this,J.$schema);if(!this.refs[H])this.addSchema(J,H,w)}async function Y(H){let J=this._loading[H];if(J)return J;try{return await(this._loading[H]=$(H))}finally{delete this._loading[H]}}}addSchema(b,w,$,W=this.opts.validateSchema){if(Array.isArray(b)){for(let G of b)this.addSchema(G,void 0,$,W);return this}let Q;if(typeof b==="object"){let{schemaId:G}=this.opts;if(Q=b[G],Q!==void 0&&typeof Q!="string")throw Error(`schema ${G} must be string`)}return w=(0,r1.normalizeId)(w||Q),this._checkUnique(w),this.schemas[w]=this._addSchema(b,$,w,W,!0),this}addMetaSchema(b,w,$=this.opts.validateSchema){return this.addSchema(b,w,!0,$),this}validateSchema(b,w){if(typeof b=="boolean")return!0;let $;if($=b.$schema,$!==void 0&&typeof $!="string")throw Error("$schema must be a string");if($=$||this.opts.defaultMeta||this.defaultMeta(),!$)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate($,b);if(!W&&w){let Q="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(Q);else throw Error(Q)}return W}getSchema(b){let w;while(typeof(w=nX.call(this,b))=="string")b=w;if(w===void 0){let{schemaId:$}=this.opts,W=new t1.SchemaEnv({schema:{},schemaId:$});if(w=t1.resolveSchema.call(this,W,b),!w)return;this.refs[b]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema(b){if(b instanceof RegExp)return this._removeAllSchemas(this.schemas,b),this._removeAllSchemas(this.refs,b),this;switch(typeof b){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=nX.call(this,b);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[b],delete this.refs[b],this}case"object":{let w=b;this._cache.delete(w);let $=b[this.opts.schemaId];if($)$=(0,r1.normalizeId)($),delete this.schemas[$],delete this.refs[$];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(b){for(let w of b)this.addKeyword(w);return this}addKeyword(b,w){let $;if(typeof b=="string"){if($=b,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=$}else if(typeof b=="object"&&w===void 0){if(w=b,$=w.keyword,Array.isArray($)&&!$.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(l3.call(this,$,w),!w)return(0,h6.eachItem)($,(Q)=>y6.call(this,Q)),this;o3.call(this,w);let W={...w,type:(0,L$.getJSONTypes)(w.type),schemaType:(0,L$.getJSONTypes)(w.schemaType)};return(0,h6.eachItem)($,W.type.length===0?(Q)=>y6.call(this,Q,W):(Q)=>W.type.forEach((G)=>y6.call(this,Q,W,G))),this}getKeyword(b){let w=this.RULES.all[b];return typeof w=="object"?w.definition:!!w}removeKeyword(b){let{RULES:w}=this;delete w.keywords[b],delete w.all[b];for(let $ of w.rules){let W=$.rules.findIndex((Q)=>Q.keyword===b);if(W>=0)$.rules.splice(W,1)}return this}addFormat(b,w){if(typeof w=="string")w=new RegExp(w);return this.formats[b]=w,this}errorsText(b=this.errors,{separator:w=", ",dataVar:$="data"}={}){if(!b||b.length===0)return"No errors";return b.map((W)=>`${$}${W.instancePath} ${W.message}`).reduce((W,Q)=>W+w+Q)}$dataMetaSchema(b,w){let $=this.RULES.all;b=JSON.parse(JSON.stringify(b));for(let W of w){let Q=W.split("/").slice(1),G=b;for(let D of Q)G=G[D];for(let D in $){let X=$[D];if(typeof X!="object")continue;let{$data:Y}=X.definition,H=G[D];if(Y&&H)G[D]=iX(H)}}return b}_removeAllSchemas(b,w){for(let $ in b){let W=b[$];if(!w||w.test($)){if(typeof W=="string")delete b[$];else if(W&&!W.meta)this._cache.delete(W.schema),delete b[$]}}}_addSchema(b,w,$,W=this.opts.validateSchema,Q=this.opts.addUsedSchema){let G,{schemaId:D}=this.opts;if(typeof b=="object")G=b[D];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof b!="boolean")throw Error("schema must be object or boolean");let X=this._cache.get(b);if(X!==void 0)return X;$=(0,r1.normalizeId)(G||$);let Y=r1.getSchemaRefs.call(this,b,$);if(X=new t1.SchemaEnv({schema:b,schemaId:D,meta:w,baseId:$,localRefs:Y}),this._cache.set(X.schema,X),Q&&!$.startsWith("#")){if($)this._checkUnique($);this.refs[$]=X}if(W)this.validateSchema(b,!0);return X}_checkUnique(b){if(this.schemas[b]||this.refs[b])throw Error(`schema with key or id "${b}" already exists`)}_compileSchemaEnv(b){if(b.meta)this._compileMetaSchema(b);else t1.compileSchema.call(this,b);if(!b.validate)throw Error("ajv implementation error");return b.validate}_compileMetaSchema(b){let w=this.opts;this.opts=this._metaOpts;try{t1.compileSchema.call(this,b)}finally{this.opts=w}}}U$.ValidationError=_3.default;U$.MissingRefError=gX.default;Xw.default=U$;function cX(b,w,$,W="error"){for(let Q in b){let G=Q;if(G in w)this.logger[W](`${$}: option ${Q}. ${b[G]}`)}}function nX(b){return b=(0,r1.normalizeId)(b),this.schemas[b]||this.refs[b]}function h3(){let b=this.opts.schemas;if(!b)return;if(Array.isArray(b))this.addSchema(b);else for(let w in b)this.addSchema(b[w],w)}function f3(){for(let b in this.opts.formats){let w=this.opts.formats[b];if(w)this.addFormat(b,w)}}function c3(b){if(Array.isArray(b)){this.addVocabulary(b);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in b){let $=b[w];if(!$.keyword)$.keyword=w;this.addKeyword($)}}function n3(){let b={...this.opts};for(let w of k3)delete b[w];return b}var g3={log(){},warn(){},error(){}};function m3(b){if(b===!1)return g3;if(b===void 0)return console;if(b.log&&b.warn&&b.error)return b;throw Error("logger must implement log, warn and error methods")}var i3=/^[a-z_$][a-z0-9_$:-]*$/i;function l3(b,w){let{RULES:$}=this;if((0,h6.eachItem)(b,(W)=>{if($.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!i3.test(W))throw Error(`Keyword ${W} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function y6(b,w,$){var W;let Q=w===null||w===void 0?void 0:w.post;if($&&Q)throw Error('keyword with "post" flag cannot have "type"');let{RULES:G}=this,D=Q?G.post:G.rules.find(({type:Y})=>Y===$);if(!D)D={type:$,rules:[]},G.rules.push(D);if(G.keywords[b]=!0,!w)return;let X={keyword:b,definition:{...w,type:(0,L$.getJSONTypes)(w.type),schemaType:(0,L$.getJSONTypes)(w.schemaType)}};if(w.before)p3.call(this,D,X,w.before);else D.rules.push(X);G.all[b]=X,(W=w.implements)===null||W===void 0||W.forEach((Y)=>this.addKeyword(Y))}function p3(b,w,$){let W=b.rules.findIndex((Q)=>Q.keyword===$);if(W>=0)b.rules.splice(W,0,w);else b.rules.push(w),this.logger.warn(`rule ${$} is not defined`)}function o3(b){let{metaSchema:w}=b;if(w===void 0)return;if(b.$data&&this.opts.$data)w=iX(w);b.validateSchema=this.compile(w,!0)}var d3={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function iX(b){return{anyOf:[b,d3]}}});var oX=j((pX)=>{Object.defineProperty(pX,"__esModule",{value:!0});var e3={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};pX.default=e3});var aX=j((eX)=>{Object.defineProperty(eX,"__esModule",{value:!0});eX.callRef=eX.getValidate=void 0;var a3=p1(),dX=Cb(),jb=x(),aw=Qw(),tX=J$(),B$=i(),bB={keyword:"$ref",schemaType:"string",code(b){let{gen:w,schema:$,it:W}=b,{baseId:Q,schemaEnv:G,validateName:D,opts:X,self:Y}=W,{root:H}=G;if(($==="#"||$==="#/")&&Q===H.baseId)return z();let J=tX.resolveRef.call(Y,H,Q,$);if(J===void 0)throw new a3.default(W.opts.uriResolver,Q,$);if(J instanceof tX.SchemaEnv)return O(J);return q(J);function z(){if(G===H)return P$(b,D,G,G.$async);let B=w.scopeValue("root",{ref:H});return P$(b,jb._`${B}.validate`,H,H.$async)}function O(B){let K=rX(b,B);P$(b,K,B,B.$async)}function q(B){let K=w.scopeValue("schema",X.code.source===!0?{ref:B,code:(0,jb.stringify)(B)}:{ref:B}),I=w.name("valid"),M=b.subschema({schema:B,dataTypes:[],schemaPath:jb.nil,topSchemaRef:K,errSchemaPath:$},I);b.mergeEvaluated(M),b.ok(I)}}};function rX(b,w){let{gen:$}=b;return w.validate?$.scopeValue("validate",{ref:w.validate}):jb._`${$.scopeValue("wrapper",{ref:w})}.validate`}eX.getValidate=rX;function P$(b,w,$,W){let{gen:Q,it:G}=b,{allErrors:D,schemaEnv:X,opts:Y}=G,H=Y.passContext?aw.default.this:jb.nil;if(W)J();else z();function J(){if(!X.$async)throw Error("async schema referenced by sync schema");let B=Q.let("valid");Q.try(()=>{if(Q.code(jb._`await ${(0,dX.callValidateCode)(b,w,H)}`),q(w),!D)Q.assign(B,!0)},(K)=>{if(Q.if(jb._`!(${K} instanceof ${G.ValidationError})`,()=>Q.throw(K)),O(K),!D)Q.assign(B,!1)}),b.ok(B)}function z(){b.result((0,dX.callValidateCode)(b,w,H),()=>q(w),()=>O(w))}function O(B){let K=jb._`${B}.errors`;Q.assign(aw.default.vErrors,jb._`${aw.default.vErrors} === null ? ${K} : ${aw.default.vErrors}.concat(${K})`),Q.assign(aw.default.errors,jb._`${aw.default.vErrors}.length`)}function q(B){var K;if(!G.opts.unevaluated)return;let I=(K=$===null||$===void 0?void 0:$.validate)===null||K===void 0?void 0:K.evaluated;if(G.props!==!0)if(I&&!I.dynamicProps){if(I.props!==void 0)G.props=B$.mergeEvaluated.props(Q,I.props,G.props)}else{let M=Q.var("props",jb._`${B}.evaluated.props`);G.props=B$.mergeEvaluated.props(Q,M,G.props,jb.Name)}if(G.items!==!0)if(I&&!I.dynamicItems){if(I.items!==void 0)G.items=B$.mergeEvaluated.items(Q,I.items,G.items)}else{let M=Q.var("items",jb._`${B}.evaluated.items`);G.items=B$.mergeEvaluated.items(Q,M,G.items,jb.Name)}}}eX.callRef=P$;eX.default=bB});var wY=j((bY)=>{Object.defineProperty(bY,"__esModule",{value:!0});var WB=oX(),QB=aX(),GB=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",WB.default,QB.default];bY.default=GB});var WY=j(($Y)=>{Object.defineProperty($Y,"__esModule",{value:!0});var F$=x(),Vw=F$.operators,K$={maximum:{okStr:"<=",ok:Vw.LTE,fail:Vw.GT},minimum:{okStr:">=",ok:Vw.GTE,fail:Vw.LT},exclusiveMaximum:{okStr:"<",ok:Vw.LT,fail:Vw.GTE},exclusiveMinimum:{okStr:">",ok:Vw.GT,fail:Vw.LTE}},XB={message:({keyword:b,schemaCode:w})=>F$.str`must be ${K$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>F$._`{comparison: ${K$[b].okStr}, limit: ${w}}`},YB={keyword:Object.keys(K$),type:"number",schemaType:"number",$data:!0,error:XB,code(b){let{keyword:w,data:$,schemaCode:W}=b;b.fail$data(F$._`${$} ${K$[w].fail} ${W} || isNaN(${$})`)}};$Y.default=YB});var GY=j((QY)=>{Object.defineProperty(QY,"__esModule",{value:!0});var e1=x(),JB={message:({schemaCode:b})=>e1.str`must be multiple of ${b}`,params:({schemaCode:b})=>e1._`{multipleOf: ${b}}`},zB={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:JB,code(b){let{gen:w,data:$,schemaCode:W,it:Q}=b,G=Q.opts.multipleOfPrecision,D=w.let("res"),X=G?e1._`Math.abs(Math.round(${D}) - ${D}) > 1e-${G}`:e1._`${D} !== parseInt(${D})`;b.fail$data(e1._`(${W} === 0 || (${D} = ${$}/${W}, ${X}))`)}};QY.default=zB});var YY=j((XY)=>{Object.defineProperty(XY,"__esModule",{value:!0});function DY(b){let w=b.length,$=0,W=0,Q;while(W<w)if($++,Q=b.charCodeAt(W++),Q>=55296&&Q<=56319&&W<w){if(Q=b.charCodeAt(W),(Q&64512)===56320)W++}return $}XY.default=DY;DY.code='require("ajv/dist/runtime/ucs2length").default'});var JY=j((HY)=>{Object.defineProperty(HY,"__esModule",{value:!0});var uw=x(),qB=i(),LB=YY(),UB={message({keyword:b,schemaCode:w}){let $=b==="maxLength"?"more":"fewer";return uw.str`must NOT have ${$} than ${w} characters`},params:({schemaCode:b})=>uw._`{limit: ${b}}`},BB={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:UB,code(b){let{keyword:w,data:$,schemaCode:W,it:Q}=b,G=w==="maxLength"?uw.operators.GT:uw.operators.LT,D=Q.opts.unicode===!1?uw._`${$}.length`:uw._`${(0,qB.useFunc)(b.gen,LB.default)}(${$})`;b.fail$data(uw._`${D} ${G} ${W}`)}};HY.default=BB});var AY=j((zY)=>{Object.defineProperty(zY,"__esModule",{value:!0});var FB=Cb(),M$=x(),KB={message:({schemaCode:b})=>M$.str`must match pattern "${b}"`,params:({schemaCode:b})=>M$._`{pattern: ${b}}`},MB={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:KB,code(b){let{data:w,$data:$,schema:W,schemaCode:Q,it:G}=b,D=G.opts.unicodeRegExp?"u":"",X=$?M$._`(new RegExp(${Q}, ${D}))`:(0,FB.usePattern)(b,W);b.fail$data(M$._`!${X}.test(${w})`)}};zY.default=MB});var qY=j((OY)=>{Object.defineProperty(OY,"__esModule",{value:!0});var s1=x(),ZB={message({keyword:b,schemaCode:w}){let $=b==="maxProperties"?"more":"fewer";return s1.str`must NOT have ${$} than ${w} properties`},params:({schemaCode:b})=>s1._`{limit: ${b}}`},jB={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:ZB,code(b){let{keyword:w,data:$,schemaCode:W}=b,Q=w==="maxProperties"?s1.operators.GT:s1.operators.LT;b.fail$data(s1._`Object.keys(${$}).length ${Q} ${W}`)}};OY.default=jB});var UY=j((LY)=>{Object.defineProperty(LY,"__esModule",{value:!0});var a1=Cb(),b0=x(),NB=i(),TB={message:({params:{missingProperty:b}})=>b0.str`must have required property '${b}'`,params:({params:{missingProperty:b}})=>b0._`{missingProperty: ${b}}`},EB={keyword:"required",type:"object",schemaType:"array",$data:!0,error:TB,code(b){let{gen:w,schema:$,schemaCode:W,data:Q,$data:G,it:D}=b,{opts:X}=D;if(!G&&$.length===0)return;let Y=$.length>=X.loopRequired;if(D.allErrors)H();else J();if(X.strictRequired){let q=b.parentSchema.properties,{definedProperties:B}=b.it;for(let K of $)if((q===null||q===void 0?void 0:q[K])===void 0&&!B.has(K)){let I=D.schemaEnv.baseId+D.errSchemaPath,M=`required property "${K}" is not defined at "${I}" (strictRequired)`;(0,NB.checkStrictMode)(D,M,D.opts.strictRequired)}}function H(){if(Y||G)b.block$data(b0.nil,z);else for(let q of $)(0,a1.checkReportMissingProp)(b,q)}function J(){let q=w.let("missing");if(Y||G){let B=w.let("valid",!0);b.block$data(B,()=>O(q,B)),b.ok(B)}else w.if((0,a1.checkMissingProp)(b,$,q)),(0,a1.reportMissingProp)(b,q),w.else()}function z(){w.forOf("prop",W,(q)=>{b.setParams({missingProperty:q}),w.if((0,a1.noPropertyInData)(w,Q,q,X.ownProperties),()=>b.error())})}function O(q,B){b.setParams({missingProperty:q}),w.forOf(q,W,()=>{w.assign(B,(0,a1.propertyInData)(w,Q,q,X.ownProperties)),w.if((0,b0.not)(B),()=>{b.error(),w.break()})},b0.nil)}}};LY.default=EB});var PY=j((BY)=>{Object.defineProperty(BY,"__esModule",{value:!0});var w0=x(),SB={message({keyword:b,schemaCode:w}){let $=b==="maxItems"?"more":"fewer";return w0.str`must NOT have ${$} than ${w} items`},params:({schemaCode:b})=>w0._`{limit: ${b}}`},RB={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:SB,code(b){let{keyword:w,data:$,schemaCode:W}=b,Q=w==="maxItems"?w0.operators.GT:w0.operators.LT;b.fail$data(w0._`${$}.length ${Q} ${W}`)}};BY.default=RB});var I$=j((KY)=>{Object.defineProperty(KY,"__esModule",{value:!0});var FY=Z6();FY.code='require("ajv/dist/runtime/equal").default';KY.default=FY});var IY=j((MY)=>{Object.defineProperty(MY,"__esModule",{value:!0});var f6=n1(),qb=x(),CB=i(),uB=I$(),xB={message:({params:{i:b,j:w}})=>qb.str`must NOT have duplicate items (items ## ${w} and ${b} are identical)`,params:({params:{i:b,j:w}})=>qb._`{i: ${b}, j: ${w}}`},yB={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:xB,code(b){let{gen:w,data:$,$data:W,schema:Q,parentSchema:G,schemaCode:D,it:X}=b;if(!W&&!Q)return;let Y=w.let("valid"),H=G.items?(0,f6.getSchemaTypes)(G.items):[];b.block$data(Y,J,qb._`${D} === false`),b.ok(Y);function J(){let B=w.let("i",qb._`${$}.length`),K=w.let("j");b.setParams({i:B,j:K}),w.assign(Y,!0),w.if(qb._`${B} > 1`,()=>(z()?O:q)(B,K))}function z(){return H.length>0&&!H.some((B)=>B==="object"||B==="array")}function O(B,K){let I=w.name("item"),M=(0,f6.checkDataTypes)(H,I,X.opts.strictNumbers,f6.DataType.Wrong),v=w.const("indices",qb._`{}`);w.for(qb._`;${B}--;`,()=>{if(w.let(I,qb._`${$}[${B}]`),w.if(M,qb._`continue`),H.length>1)w.if(qb._`typeof ${I} == "string"`,qb._`${I} += "_"`);w.if(qb._`typeof ${v}[${I}] == "number"`,()=>{w.assign(K,qb._`${v}[${I}]`),b.error(),w.assign(Y,!1).break()}).code(qb._`${v}[${I}] = ${B}`)})}function q(B,K){let I=(0,CB.useFunc)(w,uB.default),M=w.name("outer");w.label(M).for(qb._`;${B}--;`,()=>w.for(qb._`${K} = ${B}; ${K}--;`,()=>w.if(qb._`${I}(${$}[${B}], ${$}[${K}])`,()=>{b.error(),w.assign(Y,!1).break(M)})))}}};MY.default=yB});var jY=j((ZY)=>{Object.defineProperty(ZY,"__esModule",{value:!0});var c6=x(),fB=i(),cB=I$(),nB={message:"must be equal to constant",params:({schemaCode:b})=>c6._`{allowedValue: ${b}}`},gB={keyword:"const",$data:!0,error:nB,code(b){let{gen:w,data:$,$data:W,schemaCode:Q,schema:G}=b;if(W||G&&typeof G=="object")b.fail$data(c6._`!${(0,fB.useFunc)(w,cB.default)}(${$}, ${Q})`);else b.fail(c6._`${G} !== ${$}`)}};ZY.default=gB});var NY=j((VY)=>{Object.defineProperty(VY,"__esModule",{value:!0});var $0=x(),iB=i(),lB=I$(),pB={message:"must be equal to one of the allowed values",params:({schemaCode:b})=>$0._`{allowedValues: ${b}}`},oB={keyword:"enum",schemaType:"array",$data:!0,error:pB,code(b){let{gen:w,data:$,$data:W,schema:Q,schemaCode:G,it:D}=b;if(!W&&Q.length===0)throw Error("enum must have non-empty array");let X=Q.length>=D.opts.loopEnum,Y,H=()=>Y!==null&&Y!==void 0?Y:Y=(0,iB.useFunc)(w,lB.default),J;if(X||W)J=w.let("valid"),b.block$data(J,z);else{if(!Array.isArray(Q))throw Error("ajv implementation error");let q=w.const("vSchema",G);J=(0,$0.or)(...Q.map((B,K)=>O(q,K)))}b.pass(J);function z(){w.assign(J,!1),w.forOf("v",G,(q)=>w.if($0._`${H()}(${$}, ${q})`,()=>w.assign(J,!0).break()))}function O(q,B){let K=Q[B];return typeof K==="object"&&K!==null?$0._`${H()}(${$}, ${q}[${B}])`:$0._`${$} === ${K}`}}};VY.default=oB});var EY=j((TY)=>{Object.defineProperty(TY,"__esModule",{value:!0});var tB=WY(),rB=GY(),eB=JY(),sB=AY(),aB=qY(),bP=UY(),wP=PY(),$P=IY(),WP=jY(),QP=NY(),GP=[tB.default,rB.default,eB.default,sB.default,aB.default,bP.default,wP.default,$P.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},WP.default,QP.default];TY.default=GP});var g6=j((SY)=>{Object.defineProperty(SY,"__esModule",{value:!0});SY.validateAdditionalItems=void 0;var xw=x(),n6=i(),XP={message:({params:{len:b}})=>xw.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>xw._`{limit: ${b}}`},YP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:XP,code(b){let{parentSchema:w,it:$}=b,{items:W}=w;if(!Array.isArray(W)){(0,n6.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}_Y(b,W)}};function _Y(b,w){let{gen:$,schema:W,data:Q,keyword:G,it:D}=b;D.items=!0;let X=$.const("len",xw._`${Q}.length`);if(W===!1)b.setParams({len:w.length}),b.pass(xw._`${X} <= ${w.length}`);else if(typeof W=="object"&&!(0,n6.alwaysValidSchema)(D,W)){let H=$.var("valid",xw._`${X} <= ${w.length}`);$.if((0,xw.not)(H),()=>Y(H)),b.ok(H)}function Y(H){$.forRange("i",w.length,X,(J)=>{if(b.subschema({keyword:G,dataProp:J,dataPropType:n6.Type.Num},H),!D.allErrors)$.if((0,xw.not)(H),()=>$.break())})}}SY.validateAdditionalItems=_Y;SY.default=YP});var m6=j((CY)=>{Object.defineProperty(CY,"__esModule",{value:!0});CY.validateTuple=void 0;var vY=x(),Z$=i(),JP=Cb(),zP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(b){let{schema:w,it:$}=b;if(Array.isArray(w))return kY(b,"additionalItems",w);if($.items=!0,(0,Z$.alwaysValidSchema)($,w))return;b.ok((0,JP.validateArray)(b))}};function kY(b,w,$=b.schema){let{gen:W,parentSchema:Q,data:G,keyword:D,it:X}=b;if(J(Q),X.opts.unevaluated&&$.length&&X.items!==!0)X.items=Z$.mergeEvaluated.items(W,$.length,X.items);let Y=W.name("valid"),H=W.const("len",vY._`${G}.length`);$.forEach((z,O)=>{if((0,Z$.alwaysValidSchema)(X,z))return;W.if(vY._`${H} > ${O}`,()=>b.subschema({keyword:D,schemaProp:O,dataProp:O},Y)),b.ok(Y)});function J(z){let{opts:O,errSchemaPath:q}=X,B=$.length,K=B===z.minItems&&(B===z.maxItems||z[w]===!1);if(O.strictTuples&&!K){let I=`"${D}" is ${B}-tuple, but minItems or maxItems/${w} are not specified or different at path "${q}"`;(0,Z$.checkStrictMode)(X,I,O.strictTuples)}}}CY.validateTuple=kY;CY.default=zP});var yY=j((xY)=>{Object.defineProperty(xY,"__esModule",{value:!0});var OP=m6(),qP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(b)=>(0,OP.validateTuple)(b,"items")};xY.default=qP});var cY=j((fY)=>{Object.defineProperty(fY,"__esModule",{value:!0});var hY=x(),UP=i(),BP=Cb(),PP=g6(),FP={message:({params:{len:b}})=>hY.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>hY._`{limit: ${b}}`},KP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:FP,code(b){let{schema:w,parentSchema:$,it:W}=b,{prefixItems:Q}=$;if(W.items=!0,(0,UP.alwaysValidSchema)(W,w))return;if(Q)(0,PP.validateAdditionalItems)(b,Q);else b.ok((0,BP.validateArray)(b))}};fY.default=KP});var gY=j((nY)=>{Object.defineProperty(nY,"__esModule",{value:!0});var ub=x(),j$=i(),IP={message:({params:{min:b,max:w}})=>w===void 0?ub.str`must contain at least ${b} valid item(s)`:ub.str`must contain at least ${b} and no more than ${w} valid item(s)`,params:({params:{min:b,max:w}})=>w===void 0?ub._`{minContains: ${b}}`:ub._`{minContains: ${b}, maxContains: ${w}}`},ZP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:IP,code(b){let{gen:w,schema:$,parentSchema:W,data:Q,it:G}=b,D,X,{minContains:Y,maxContains:H}=W;if(G.opts.next)D=Y===void 0?1:Y,X=H;else D=1;let J=w.const("len",ub._`${Q}.length`);if(b.setParams({min:D,max:X}),X===void 0&&D===0){(0,j$.checkStrictMode)(G,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(X!==void 0&&D>X){(0,j$.checkStrictMode)(G,'"minContains" > "maxContains" is always invalid'),b.fail();return}if((0,j$.alwaysValidSchema)(G,$)){let K=ub._`${J} >= ${D}`;if(X!==void 0)K=ub._`${K} && ${J} <= ${X}`;b.pass(K);return}G.items=!0;let z=w.name("valid");if(X===void 0&&D===1)q(z,()=>w.if(z,()=>w.break()));else if(D===0){if(w.let(z,!0),X!==void 0)w.if(ub._`${Q}.length > 0`,O)}else w.let(z,!1),O();b.result(z,()=>b.reset());function O(){let K=w.name("_valid"),I=w.let("count",0);q(K,()=>w.if(K,()=>B(I)))}function q(K,I){w.forRange("i",0,J,(M)=>{b.subschema({keyword:"contains",dataProp:M,dataPropType:j$.Type.Num,compositeRule:!0},K),I()})}function B(K){if(w.code(ub._`${K}++`),X===void 0)w.if(ub._`${K} >= ${D}`,()=>w.assign(z,!0).break());else if(w.if(ub._`${K} > ${X}`,()=>w.assign(z,!1).break()),D===1)w.assign(z,!0);else w.if(ub._`${K} >= ${D}`,()=>w.assign(z,!0))}}};nY.default=ZP});var dY=j((lY)=>{Object.defineProperty(lY,"__esModule",{value:!0});lY.validateSchemaDeps=lY.validatePropertyDeps=lY.error=void 0;var i6=x(),VP=i(),W0=Cb();lY.error={message:({params:{property:b,depsCount:w,deps:$}})=>{let W=w===1?"property":"properties";return i6.str`must have ${W} ${$} when property ${b} is present`},params:({params:{property:b,depsCount:w,deps:$,missingProperty:W}})=>i6._`{property: ${b},
6
6
  missingProperty: ${W},
7
7
  depsCount: ${w},
8
- deps: ${$}}`};var MF={keyword:"dependencies",type:"object",schemaType:"object",error:iH.error,code(b){let[w,$]=ZF(b);nH(b,w),lH(b,$)}};function ZF({schema:b}){let w={},$={};for(let W in b){if(W==="__proto__")continue;let Q=Array.isArray(b[W])?w:$;Q[W]=b[W]}return[w,$]}function nH(b,w=b.schema){let{gen:$,data:W,it:Q}=b;if(Object.keys(w).length===0)return;let G=$.let("missing");for(let X in w){let Y=w[X];if(Y.length===0)continue;let H=(0,W0.propertyInData)($,W,X,Q.opts.ownProperties);if(b.setParams({property:X,depsCount:Y.length,deps:Y.join(", ")}),Q.allErrors)$.if(H,()=>{for(let J of Y)(0,W0.checkReportMissingProp)(b,J)});else $.if(l6._`${H} && (${(0,W0.checkMissingProp)(b,Y,G)})`),(0,W0.reportMissingProp)(b,G),$.else()}}iH.validatePropertyDeps=nH;function lH(b,w=b.schema){let{gen:$,data:W,keyword:Q,it:G}=b,X=$.name("valid");for(let Y in w){if((0,PF.alwaysValidSchema)(G,w[Y]))continue;$.if((0,W0.propertyInData)($,W,Y,G.opts.ownProperties),()=>{let H=b.subschema({keyword:Q,schemaProp:Y},X);b.mergeValidEvaluated(H,X)},()=>$.var(X,!0)),b.ok(X)}}iH.validateSchemaDeps=lH;iH.default=MF});var eH=I((rH)=>{Object.defineProperty(rH,"__esModule",{value:!0});var tH=u(),VF=l(),NF={message:"property name must be valid",params:({params:b})=>tH._`{propertyName: ${b.propertyName}}`},TF={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:NF,code(b){let{gen:w,schema:$,data:W,it:Q}=b;if((0,VF.alwaysValidSchema)(Q,$))return;let G=w.name("valid");w.forIn("key",W,(X)=>{b.setParams({propertyName:X}),b.subschema({keyword:"propertyNames",data:X,dataTypes:["string"],propertyName:X,compositeRule:!0},G),w.if((0,tH.not)(G),()=>{if(b.error(!0),!Q.allErrors)w.break()})}),b.ok(G)}};rH.default=TF});var i6=I((sH)=>{Object.defineProperty(sH,"__esModule",{value:!0});var V$=vb(),gb=u(),_F=Qw(),N$=l(),SF={message:"must NOT have additional properties",params:({params:b})=>gb._`{additionalProperty: ${b.additionalProperty}}`},RF={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:SF,code(b){let{gen:w,schema:$,parentSchema:W,data:Q,errsCount:G,it:X}=b;if(!G)throw Error("ajv implementation error");let{allErrors:Y,opts:H}=X;if(X.props=!0,H.removeAdditional!=="all"&&(0,N$.alwaysValidSchema)(X,$))return;let J=(0,V$.allSchemaProperties)(W.properties),D=(0,V$.allSchemaProperties)(W.patternProperties);z(),b.ok(gb._`${G} === ${_F.default.errors}`);function z(){w.forIn("key",Q,(Z)=>{if(!J.length&&!D.length)B(Z);else w.if(O(Z),()=>B(Z))})}function O(Z){let M;if(J.length>8){let k=(0,N$.schemaRefOrVal)(X,W.properties,"properties");M=(0,V$.isOwnProperty)(w,k,Z)}else if(J.length)M=(0,gb.or)(...J.map((k)=>gb._`${Z} === ${k}`));else M=gb.nil;if(D.length)M=(0,gb.or)(M,...D.map((k)=>gb._`${(0,V$.usePattern)(b,k)}.test(${Z})`));return(0,gb.not)(M)}function q(Z){w.code(gb._`delete ${Q}[${Z}]`)}function B(Z){if(H.removeAdditional==="all"||H.removeAdditional&&$===!1){q(Z);return}if($===!1){if(b.setParams({additionalProperty:Z}),b.error(),!Y)w.break();return}if(typeof $=="object"&&!(0,N$.alwaysValidSchema)(X,$)){let M=w.name("valid");if(H.removeAdditional==="failing")K(Z,M,!1),w.if((0,gb.not)(M),()=>{b.reset(),q(Z)});else if(K(Z,M),!Y)w.if((0,gb.not)(M),()=>w.break())}}function K(Z,M,k){let S={keyword:"additionalProperties",dataProp:Z,dataPropType:N$.Type.Str};if(k===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});b.subschema(S,M)}}};sH.default=RF});var $J=I((wJ)=>{Object.defineProperty(wJ,"__esModule",{value:!0});var vF=i1(),aH=vb(),p6=l(),bJ=i6(),CF={keyword:"properties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,parentSchema:W,data:Q,it:G}=b;if(G.opts.removeAdditional==="all"&&W.additionalProperties===void 0)bJ.default.code(new vF.KeywordCxt(G,bJ.default,"additionalProperties"));let X=(0,aH.allSchemaProperties)($);for(let z of X)G.definedProperties.add(z);if(G.opts.unevaluated&&X.length&&G.props!==!0)G.props=p6.mergeEvaluated.props(w,(0,p6.toHash)(X),G.props);let Y=X.filter((z)=>!(0,p6.alwaysValidSchema)(G,$[z]));if(Y.length===0)return;let H=w.name("valid");for(let z of Y){if(J(z))D(z);else{if(w.if((0,aH.propertyInData)(w,Q,z,G.opts.ownProperties)),D(z),!G.allErrors)w.else().var(H,!0);w.endIf()}b.it.definedProperties.add(z),b.ok(H)}function J(z){return G.opts.useDefaults&&!G.compositeRule&&$[z].default!==void 0}function D(z){b.subschema({keyword:"properties",schemaProp:z,dataProp:z},H)}}};wJ.default=CF});var YJ=I((XJ)=>{Object.defineProperty(XJ,"__esModule",{value:!0});var WJ=vb(),T$=u(),QJ=l(),GJ=l(),uF={keyword:"patternProperties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,data:W,parentSchema:Q,it:G}=b,{opts:X}=G,Y=(0,WJ.allSchemaProperties)($),H=Y.filter((K)=>(0,QJ.alwaysValidSchema)(G,$[K]));if(Y.length===0||H.length===Y.length&&(!G.opts.unevaluated||G.props===!0))return;let J=X.strictSchema&&!X.allowMatchingProperties&&Q.properties,D=w.name("valid");if(G.props!==!0&&!(G.props instanceof T$.Name))G.props=(0,GJ.evaluatedPropsToName)(w,G.props);let{props:z}=G;O();function O(){for(let K of Y){if(J)q(K);if(G.allErrors)B(K);else w.var(D,!0),B(K),w.if(D)}}function q(K){for(let Z in J)if(new RegExp(K).test(Z))(0,QJ.checkStrictMode)(G,`property ${Z} matches pattern ${K} (use allowMatchingProperties)`)}function B(K){w.forIn("key",W,(Z)=>{w.if(T$._`${(0,WJ.usePattern)(b,K)}.test(${Z})`,()=>{let M=H.includes(K);if(!M)b.subschema({keyword:"patternProperties",schemaProp:K,dataProp:Z,dataPropType:GJ.Type.Str},D);if(G.opts.unevaluated&&z!==!0)w.assign(T$._`${z}[${Z}]`,!0);else if(!M&&!G.allErrors)w.if((0,T$.not)(D),()=>w.break())})})}}};XJ.default=uF});var JJ=I((HJ)=>{Object.defineProperty(HJ,"__esModule",{value:!0});var hF=l(),fF={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(b){let{gen:w,schema:$,it:W}=b;if((0,hF.alwaysValidSchema)(W,$)){b.fail();return}let Q=w.name("valid");b.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},Q),b.failResult(Q,()=>b.reset(),()=>b.error())},error:{message:"must NOT be valid"}};HJ.default=fF});var zJ=I((DJ)=>{Object.defineProperty(DJ,"__esModule",{value:!0});var gF=vb(),mF={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:gF.validateUnion,error:{message:"must match a schema in anyOf"}};DJ.default=mF});var OJ=I((AJ)=>{Object.defineProperty(AJ,"__esModule",{value:!0});var E$=u(),lF=l(),iF={message:"must match exactly one schema in oneOf",params:({params:b})=>E$._`{passingSchemas: ${b.passing}}`},pF={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:iF,code(b){let{gen:w,schema:$,parentSchema:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if(Q.opts.discriminator&&W.discriminator)return;let G=$,X=w.let("valid",!1),Y=w.let("passing",null),H=w.name("_valid");b.setParams({passing:Y}),w.block(J),b.result(X,()=>b.reset(),()=>b.error(!0));function J(){G.forEach((D,z)=>{let O;if((0,lF.alwaysValidSchema)(Q,D))w.var(H,!0);else O=b.subschema({keyword:"oneOf",schemaProp:z,compositeRule:!0},H);if(z>0)w.if(E$._`${H} && ${X}`).assign(X,!1).assign(Y,E$._`[${Y}, ${z}]`).else();w.if(H,()=>{if(w.assign(X,!0),w.assign(Y,z),O)b.mergeEvaluated(O,E$.Name)})})}}};AJ.default=pF});var LJ=I((qJ)=>{Object.defineProperty(qJ,"__esModule",{value:!0});var dF=l(),tF={keyword:"allOf",schemaType:"array",code(b){let{gen:w,schema:$,it:W}=b;if(!Array.isArray($))throw Error("ajv implementation error");let Q=w.name("valid");$.forEach((G,X)=>{if((0,dF.alwaysValidSchema)(W,G))return;let Y=b.subschema({keyword:"allOf",schemaProp:X},Q);b.ok(Q),b.mergeEvaluated(Y)})}};qJ.default=tF});var KJ=I((FJ)=>{Object.defineProperty(FJ,"__esModule",{value:!0});var _$=u(),BJ=l(),eF={message:({params:b})=>_$.str`must match "${b.ifClause}" schema`,params:({params:b})=>_$._`{failingKeyword: ${b.ifClause}}`},sF={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:eF,code(b){let{gen:w,parentSchema:$,it:W}=b;if($.then===void 0&&$.else===void 0)(0,BJ.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Q=UJ(W,"then"),G=UJ(W,"else");if(!Q&&!G)return;let X=w.let("valid",!0),Y=w.name("_valid");if(H(),b.reset(),Q&&G){let D=w.let("ifClause");b.setParams({ifClause:D}),w.if(Y,J("then",D),J("else",D))}else if(Q)w.if(Y,J("then"));else w.if((0,_$.not)(Y),J("else"));b.pass(X,()=>b.error(!0));function H(){let D=b.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},Y);b.mergeEvaluated(D)}function J(D,z){return()=>{let O=b.subschema({keyword:D},Y);if(w.assign(X,Y),b.mergeValidEvaluated(O,X),z)w.assign(z,_$._`${D}`);else b.setParams({ifClause:D})}}}};function UJ(b,w){let $=b.schema[w];return $!==void 0&&!(0,BJ.alwaysValidSchema)(b,$)}FJ.default=sF});var MJ=I((PJ)=>{Object.defineProperty(PJ,"__esModule",{value:!0});var bK=l(),wK={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:b,parentSchema:w,it:$}){if(w.if===void 0)(0,bK.checkStrictMode)($,`"${b}" without "if" is ignored`)}};PJ.default=wK});var jJ=I((ZJ)=>{Object.defineProperty(ZJ,"__esModule",{value:!0});var WK=m6(),QK=yH(),GK=n6(),XK=cH(),YK=mH(),HK=dH(),JK=eH(),DK=i6(),zK=$J(),AK=YJ(),OK=JJ(),qK=zJ(),LK=OJ(),UK=LJ(),BK=KJ(),FK=MJ();function KK(b=!1){let w=[OK.default,qK.default,LK.default,UK.default,BK.default,FK.default,JK.default,DK.default,HK.default,zK.default,AK.default];if(b)w.push(QK.default,XK.default);else w.push(WK.default,GK.default);return w.push(YK.default),w}ZJ.default=KK});var VJ=I((IJ)=>{Object.defineProperty(IJ,"__esModule",{value:!0});var Gb=u(),MK={message:({schemaCode:b})=>Gb.str`must match format "${b}"`,params:({schemaCode:b})=>Gb._`{format: ${b}}`},ZK={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:MK,code(b,w){let{gen:$,data:W,$data:Q,schema:G,schemaCode:X,it:Y}=b,{opts:H,errSchemaPath:J,schemaEnv:D,self:z}=Y;if(!H.validateFormats)return;if(Q)O();else q();function O(){let B=$.scopeValue("formats",{ref:z.formats,code:H.code.formats}),K=$.const("fDef",Gb._`${B}[${X}]`),Z=$.let("fType"),M=$.let("format");$.if(Gb._`typeof ${K} == "object" && !(${K} instanceof RegExp)`,()=>$.assign(Z,Gb._`${K}.type || "string"`).assign(M,Gb._`${K}.validate`),()=>$.assign(Z,Gb._`"string"`).assign(M,K)),b.fail$data((0,Gb.or)(k(),S()));function k(){if(H.strictSchema===!1)return Gb.nil;return Gb._`${X} && !${M}`}function S(){let h=D.$async?Gb._`(${K}.async ? await ${M}(${W}) : ${M}(${W}))`:Gb._`${M}(${W})`,R=Gb._`(typeof ${M} == "function" ? ${h} : ${M}.test(${W}))`;return Gb._`${M} && ${M} !== true && ${Z} === ${w} && !${R}`}}function q(){let B=z.formats[G];if(!B){k();return}if(B===!0)return;let[K,Z,M]=S(B);if(K===w)b.pass(h());function k(){if(H.strictSchema===!1){z.logger.warn(R());return}throw Error(R());function R(){return`unknown format "${G}" ignored in schema at path "${J}"`}}function S(R){let pb=R instanceof RegExp?(0,Gb.regexpCode)(R):H.code.formats?Gb._`${H.code.formats}${(0,Gb.getProperty)(G)}`:void 0,sb=$.scopeValue("formats",{key:G,ref:R,code:pb});if(typeof R=="object"&&!(R instanceof RegExp))return[R.type||"string",R.validate,Gb._`${sb}.validate`];return["string",R,sb]}function h(){if(typeof B=="object"&&!(B instanceof RegExp)&&B.async){if(!D.$async)throw Error("async format in sync schema");return Gb._`await ${M}(${W})`}return typeof Z=="function"?Gb._`${M}(${W})`:Gb._`${M}.test(${W})`}}}};IJ.default=ZK});var TJ=I((NJ)=>{Object.defineProperty(NJ,"__esModule",{value:!0});var IK=VJ(),VK=[IK.default];NJ.default=VK});var SJ=I((EJ)=>{Object.defineProperty(EJ,"__esModule",{value:!0});EJ.contentVocabulary=EJ.metadataVocabulary=void 0;EJ.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];EJ.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var vJ=I((kJ)=>{Object.defineProperty(kJ,"__esModule",{value:!0});var EK=wH(),_K=EH(),SK=jJ(),RK=TJ(),RJ=SJ(),kK=[EK.default,_K.default,(0,SK.default)(),RK.default,RJ.metadataVocabulary,RJ.contentVocabulary];kJ.default=kK});var yJ=I((xJ)=>{Object.defineProperty(xJ,"__esModule",{value:!0});xJ.DiscrError=void 0;var CJ;(function(b){b.Tag="tag",b.Mapping="mapping"})(CJ||(xJ.DiscrError=CJ={}))});var cJ=I((fJ)=>{Object.defineProperty(fJ,"__esModule",{value:!0});var b1=u(),o6=yJ(),hJ=D$(),CK=p1(),xK=l(),uK={message:({params:{discrError:b,tagName:w}})=>b===o6.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:b,tag:w,tagName:$}})=>b1._`{error: ${b}, tag: ${$}, tagValue: ${w}}`},yK={keyword:"discriminator",type:"object",schemaType:"object",error:uK,code(b){let{gen:w,data:$,schema:W,parentSchema:Q,it:G}=b,{oneOf:X}=Q;if(!G.opts.discriminator)throw Error("discriminator: requires discriminator option");let Y=W.propertyName;if(typeof Y!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!X)throw Error("discriminator: requires oneOf keyword");let H=w.let("valid",!1),J=w.const("tag",b1._`${$}${(0,b1.getProperty)(Y)}`);w.if(b1._`typeof ${J} == "string"`,()=>D(),()=>b.error(!1,{discrError:o6.DiscrError.Tag,tag:J,tagName:Y})),b.ok(H);function D(){let q=O();w.if(!1);for(let B in q)w.elseIf(b1._`${J} === ${B}`),w.assign(H,z(q[B]));w.else(),b.error(!1,{discrError:o6.DiscrError.Mapping,tag:J,tagName:Y}),w.endIf()}function z(q){let B=w.name("valid"),K=b.subschema({keyword:"oneOf",schemaProp:q},B);return b.mergeEvaluated(K,b1.Name),B}function O(){var q;let B={},K=M(Q),Z=!0;for(let h=0;h<X.length;h++){let R=X[h];if((R===null||R===void 0?void 0:R.$ref)&&!(0,xK.schemaHasRulesButRef)(R,G.self.RULES)){let sb=R.$ref;if(R=hJ.resolveRef.call(G.self,G.schemaEnv.root,G.baseId,sb),R instanceof hJ.SchemaEnv)R=R.schema;if(R===void 0)throw new CK.default(G.opts.uriResolver,G.baseId,sb)}let pb=(q=R===null||R===void 0?void 0:R.properties)===null||q===void 0?void 0:q[Y];if(typeof pb!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${Y}"`);Z=Z&&(K||M(R)),k(pb,h)}if(!Z)throw Error(`discriminator: "${Y}" must be required`);return B;function M({required:h}){return Array.isArray(h)&&h.includes(Y)}function k(h,R){if(h.const)S(h.const,R);else if(h.enum)for(let pb of h.enum)S(pb,R);else throw Error(`discriminator: "properties/${Y}" must have "const" or "enum"`)}function S(h,R){if(typeof h!="string"||h in B)throw Error(`discriminator: "${Y}" values must be unique strings`);B[h]=R}}}};fJ.default=yK});var gJ=I((cE,fK)=>{fK.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 t6=I((Ib,d6)=>{Object.defineProperty(Ib,"__esModule",{value:!0});Ib.MissingRefError=Ib.ValidationError=Ib.CodeGen=Ib.Name=Ib.nil=Ib.stringify=Ib.str=Ib._=Ib.KeywordCxt=Ib.Ajv=void 0;var cK=iY(),gK=vJ(),mK=cJ(),mJ=gJ(),nK=["/properties"],S$="http://json-schema.org/draft-07/schema";class Q0 extends cK.default{_addVocabularies(){if(super._addVocabularies(),gK.default.forEach((b)=>this.addVocabulary(b)),this.opts.discriminator)this.addKeyword(mK.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let b=this.opts.$data?this.$dataMetaSchema(mJ,nK):mJ;this.addMetaSchema(b,S$,!1),this.refs["http://json-schema.org/schema"]=S$}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(S$)?S$:void 0)}}Ib.Ajv=Q0;d6.exports=Ib=Q0;d6.exports.Ajv=Q0;Object.defineProperty(Ib,"__esModule",{value:!0});Ib.default=Q0;var lK=i1();Object.defineProperty(Ib,"KeywordCxt",{enumerable:!0,get:function(){return lK.KeywordCxt}});var w1=u();Object.defineProperty(Ib,"_",{enumerable:!0,get:function(){return w1._}});Object.defineProperty(Ib,"str",{enumerable:!0,get:function(){return w1.str}});Object.defineProperty(Ib,"stringify",{enumerable:!0,get:function(){return w1.stringify}});Object.defineProperty(Ib,"nil",{enumerable:!0,get:function(){return w1.nil}});Object.defineProperty(Ib,"Name",{enumerable:!0,get:function(){return w1.Name}});Object.defineProperty(Ib,"CodeGen",{enumerable:!0,get:function(){return w1.CodeGen}});var iK=H$();Object.defineProperty(Ib,"ValidationError",{enumerable:!0,get:function(){return iK.default}});var pK=p1();Object.defineProperty(Ib,"MissingRefError",{enumerable:!0,get:function(){return pK.default}})});var sJ=I((rJ)=>{Object.defineProperty(rJ,"__esModule",{value:!0});rJ.formatNames=rJ.fastFormats=rJ.fullFormats=void 0;function rb(b,w){return{validate:b,compare:w}}rJ.fullFormats={date:rb(pJ,a6),time:rb(e6(!0),bW),"date-time":rb(nJ(!0),dJ),"iso-time":rb(e6(),oJ),"iso-date-time":rb(nJ(),tJ),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:bP,"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:YP,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:wP,int32:{type:"number",validate:QP},int64:{type:"number",validate:GP},float:{type:"number",validate:iJ},double:{type:"number",validate:iJ},password:!0,binary:!0};rJ.fastFormats={...rJ.fullFormats,date:rb(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a6),time:rb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,bW),"date-time":rb(/^\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,dJ),"iso-time":rb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,oJ),"iso-date-time":rb(/^\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,tJ),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};rJ.formatNames=Object.keys(rJ.fullFormats);function tK(b){return b%4===0&&(b%100!==0||b%400===0)}var rK=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,eK=[0,31,28,31,30,31,30,31,31,30,31,30,31];function pJ(b){let w=rK.exec(b);if(!w)return!1;let $=+w[1],W=+w[2],Q=+w[3];return W>=1&&W<=12&&Q>=1&&Q<=(W===2&&tK($)?29:eK[W])}function a6(b,w){if(!(b&&w))return;if(b>w)return 1;if(b<w)return-1;return 0}var r6=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function e6(b){return function($){let W=r6.exec($);if(!W)return!1;let Q=+W[1],G=+W[2],X=+W[3],Y=W[4],H=W[5]==="-"?-1:1,J=+(W[6]||0),D=+(W[7]||0);if(J>23||D>59||b&&!Y)return!1;if(Q<=23&&G<=59&&X<60)return!0;let z=G-D*H,O=Q-J*H-(z<0?1:0);return(O===23||O===-1)&&(z===59||z===-1)&&X<61}}function bW(b,w){if(!(b&&w))return;let $=new Date("2020-01-01T"+b).valueOf(),W=new Date("2020-01-01T"+w).valueOf();if(!($&&W))return;return $-W}function oJ(b,w){if(!(b&&w))return;let $=r6.exec(b),W=r6.exec(w);if(!($&&W))return;if(b=$[1]+$[2]+$[3],w=W[1]+W[2]+W[3],b>w)return 1;if(b<w)return-1;return 0}var s6=/t|\s/i;function nJ(b){let w=e6(b);return function(W){let Q=W.split(s6);return Q.length===2&&pJ(Q[0])&&w(Q[1])}}function dJ(b,w){if(!(b&&w))return;let $=new Date(b).valueOf(),W=new Date(w).valueOf();if(!($&&W))return;return $-W}function tJ(b,w){if(!(b&&w))return;let[$,W]=b.split(s6),[Q,G]=w.split(s6),X=a6($,Q);if(X===void 0)return;return X||bW(W,G)}var sK=/\/|:/,aK=/^(?:[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 bP(b){return sK.test(b)&&aK.test(b)}var lJ=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function wP(b){return lJ.lastIndex=0,lJ.test(b)}var $P=-2147483648,WP=2147483647;function QP(b){return Number.isInteger(b)&&b<=WP&&b>=$P}function GP(b){return Number.isInteger(b)}function iJ(){return!0}var XP=/[^\\]\\Z/;function YP(b){if(XP.test(b))return!1;try{return new RegExp(b),!0}catch(w){return!1}}});var bD=I((aJ)=>{Object.defineProperty(aJ,"__esModule",{value:!0});aJ.formatLimitDefinition=void 0;var JP=t6(),mb=u(),Nw=mb.operators,R$={formatMaximum:{okStr:"<=",ok:Nw.LTE,fail:Nw.GT},formatMinimum:{okStr:">=",ok:Nw.GTE,fail:Nw.LT},formatExclusiveMaximum:{okStr:"<",ok:Nw.LT,fail:Nw.GTE},formatExclusiveMinimum:{okStr:">",ok:Nw.GT,fail:Nw.LTE}},DP={message:({keyword:b,schemaCode:w})=>mb.str`should be ${R$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>mb._`{comparison: ${R$[b].okStr}, limit: ${w}}`};aJ.formatLimitDefinition={keyword:Object.keys(R$),type:"string",schemaType:"string",$data:!0,error:DP,code(b){let{gen:w,data:$,schemaCode:W,keyword:Q,it:G}=b,{opts:X,self:Y}=G;if(!X.validateFormats)return;let H=new JP.KeywordCxt(G,Y.RULES.all.format.definition,"format");if(H.$data)J();else D();function J(){let O=w.scopeValue("formats",{ref:Y.formats,code:X.code.formats}),q=w.const("fmt",mb._`${O}[${H.schemaCode}]`);b.fail$data((0,mb.or)(mb._`typeof ${q} != "object"`,mb._`${q} instanceof RegExp`,mb._`typeof ${q}.compare != "function"`,z(q)))}function D(){let O=H.schema,q=Y.formats[O];if(!q||q===!0)return;if(typeof q!="object"||q instanceof RegExp||typeof q.compare!="function")throw Error(`"${Q}": format "${O}" does not define "compare" function`);let B=w.scopeValue("formats",{key:O,ref:q,code:X.code.formats?mb._`${X.code.formats}${(0,mb.getProperty)(O)}`:void 0});b.fail$data(z(B))}function z(O){return mb._`${O}.compare(${$}, ${W}) ${R$[Q].fail} 0`}},dependencies:["format"]};var zP=(b)=>{return b.addKeyword(aJ.formatLimitDefinition),b};aJ.default=zP});var QD=I((G0,WD)=>{Object.defineProperty(G0,"__esModule",{value:!0});var $1=sJ(),OP=bD(),WW=u(),wD=new WW.Name("fullFormats"),qP=new WW.Name("fastFormats"),QW=(b,w={keywords:!0})=>{if(Array.isArray(w))return $D(b,w,$1.fullFormats,wD),b;let[$,W]=w.mode==="fast"?[$1.fastFormats,qP]:[$1.fullFormats,wD],Q=w.formats||$1.formatNames;if($D(b,Q,$,W),w.keywords)(0,OP.default)(b);return b};QW.get=(b,w="full")=>{let W=(w==="fast"?$1.fastFormats:$1.fullFormats)[b];if(!W)throw Error(`Unknown format "${b}"`);return W};function $D(b,w,$,W){var Q,G;(Q=(G=b.opts.code).formats)!==null&&Q!==void 0||(G.formats=WW._`require("ajv-formats/dist/formats").${W}`);for(let X of w)b.addFormat(X,$[X])}WD.exports=G0=QW;Object.defineProperty(G0,"__esModule",{value:!0});G0.default=QW});import{AsyncLocalStorage as nz}from"node:async_hooks";class ob extends Error{statusCode;rawDetails;code;context;constructor(b,w,$,W,Q){super(b);this.statusCode=w;this.rawDetails=$;this.code=W;this.context=Q;this.name="McpApiError"}}function cz(b){if(b instanceof ob)return{message:b.message,statusCode:b.statusCode,code:b.code,rawDetails:b.rawDetails,context:b.context};if(b instanceof Error)return{message:b.message};return{message:String(b)}}function gz(b){let w=b.match(/api key is missing required scopes?:\s*(.+)$/i);if(!w?.[1])return[];return w[1].match(/[a-z_]+:[a-z_]+/gi)??[]}function mz(b){let w=cz(b),$=w.message.trim()||"Unknown error",W=$.toLowerCase(),Q=w.rawDetails?.trim()||$;if(w.context?.title||w.context?.description||w.context?.howToFix||w.context?.docsUrl)return{title:w.context.title??(w.statusCode===409?"Request conflict":"API request failed"),description:w.context.description??$,howToFix:w.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:w.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.code==="MCP_AUTH_REQUIRED"||W.includes("sequenzy_api_key environment variable is required"))return{title:"Missing MCP API key",description:"The MCP server started without a Sequenzy API key, so it cannot authenticate any tool or resource request.",howToFix:"Add `SEQUENZY_API_KEY` to the MCP server environment, or run `npx @sequenzy/setup` to configure the integration automatically.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===401||w.code==="UNAUTHORIZED")return{title:"Authentication failed",description:"The MCP server reached Sequenzy, but the current API key was rejected.",howToFix:"Replace `SEQUENZY_API_KEY` with a valid personal API key, then restart the MCP client so it reconnects with fresh credentials.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};let G=gz($);if(G.length>0){let X=G.map((H)=>`\`${H}\``).join(", "),Y=G.every((H)=>H.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${G.length===1?"scope":"scopes"}: ${X}.`,howToFix:`For a local API-key connection, call \`get_account\` to inspect \`apiKeyPermissions\` and open \`apiKeyPermissions.manageUrl\` (or \`companies[].settingsUrl\` → API Keys). If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and use the MCP setup or Settings → API Keys. Create a replacement key with ${Y} including ${X}, replace \`SEQUENZY_API_KEY\`, and restart the client. For hosted OAuth MCP, disconnect and reauthorize the Sequenzy connection with a preset or Custom permissions including ${X}. Existing key permissions cannot be edited in place.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}if(w.statusCode===403||W.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};if(W.includes("no company available")||W.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===404||W.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===409||W.includes("already exists"))return{title:"Resource already exists",description:"Sequenzy rejected this MCP request because it would create a duplicate resource.",howToFix:"List the existing resources first, reuse the matching resource when appropriate, or retry with a unique name or domain.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===429||W.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.code==="NETWORK_ERROR"||W.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("unknown tool")||W.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("is required")||W.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode&&w.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If it still fails, keep the details below and consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}function yw(b){let w=mz(b);return[`Sequenzy MCP error: ${w.title}`,`Description: ${w.description}`,`How to fix: ${w.howToFix}`,`Docs: ${w.docsUrl}`,`Details: ${w.details}`].join(`
9
- `)}var lz="https://api.sequenzy.com",z1=new nz,vW=!1;function jM(){vW=!0}function z0(){return vW}var CW=null;function Ew(){let b=z1.getStore();if(b)return b.selectedCompanyId??null;return CW}function t$(b){let w=z1.getStore();if(w){w.selectedCompanyId=b;return}CW=b}function xW(b,w){return z1.run(b,w)}function uW(){return z1.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??lz}function yW(){return z1.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function hW(b,w){let $=yW();if(!$)throw new ob("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let W={"Content-Type":b,Authorization:`Bearer ${$}`},Q=w??Ew();if(Q)W["x-company-id"]=Q;return W}function IM(){if(yW())return;console.error(yw(new ob("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function Nb(b,w){let $=b[w];return typeof $==="string"&&$.trim()!==""?$.trim():void 0}function iz(b){if(b===void 0)return;if(typeof b==="string")return b.trim()||void 0;return JSON.stringify(b)}function fW(b){if(!b.trim())return{message:"Request failed"};try{let w=JSON.parse(b);if(typeof w==="string")return{message:w};let $=typeof w.error==="object"&&w.error!==null?w.error:void 0,W=Nb(w,"code")??($?Nb($,"code"):void 0),Q=(typeof w.error==="string"?w.error:void 0)??($?Nb($,"message"):void 0)??Nb(w,"message")??Nb(w,"error")??b,G=Nb(w,"howToFix")??Nb(w,"resolution"),X={...Nb(w,"title")?{title:Nb(w,"title")}:{},...Nb(w,"description")?{description:Nb(w,"description")}:{},...G?{howToFix:G}:{},...Nb(w,"docsUrl")?{docsUrl:Nb(w,"docsUrl")}:{}},Y=iz(w.details);if(Object.keys(X).length>0||Y)return{message:Q,...W?{code:W}:{},...Y?{details:Y}:{},...Object.keys(X).length>0?{context:X}:{}};if(typeof w.error==="string")return{message:w.error,...W?{code:W}:{}};if($)return{message:Q,...W?{code:W}:{}};return{message:Q,...W?{code:W}:{}}}catch{return{message:b}}}async function A(b,w,$,W){let Q=hW("application/json",W),G;try{G=await fetch(`${uW()}${w}`,{method:b,headers:Q,body:$?JSON.stringify($):void 0})}catch(X){throw new ob(X instanceof Error?X.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!G.ok){let X=await G.text(),Y=fW(X);throw new ob(Y.message,G.status,Y.details??X,Y.code,Y.context)}return G.json()}async function cW(b,w,$,W){let Q=new URL(uW()).origin,G=new URL(b,`${Q}/`);if(G.origin!==Q)throw new ob("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");let X;try{X=await fetch(G,{method:"PUT",headers:hW($,W),body:w})}catch(Y){throw new ob(Y instanceof Error?Y.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!X.ok){let Y=await X.text(),H=fW(Y);throw new ob(H.message,X.status,H.details??Y,H.code,H.context)}}var NM=Object.freeze({status:"aborted"});function U(b,w,$){function W(Y,H){var J;Object.defineProperty(Y,"_zod",{value:Y._zod??{},enumerable:!1}),(J=Y._zod).traits??(J.traits=new Set),Y._zod.traits.add(b),w(Y,H);for(let D in X.prototype)if(!(D in Y))Object.defineProperty(Y,D,{value:X.prototype[D].bind(Y)});Y._zod.constr=X,Y._zod.def=H}let Q=$?.Parent??Object;class G extends Q{}Object.defineProperty(G,"name",{value:b});function X(Y){var H;let J=$?.Parent?new G:this;W(J,Y),(H=J._zod).deferred??(H.deferred=[]);for(let D of J._zod.deferred)D();return J}return Object.defineProperty(X,"init",{value:W}),Object.defineProperty(X,Symbol.hasInstance,{value:(Y)=>{if($?.Parent&&Y instanceof $.Parent)return!0;return Y?._zod?.traits?.has(b)}}),Object.defineProperty(X,"name",{value:b}),X}var TM=Symbol("zod_brand");class ab extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class A1 extends Error{constructor(b){super(`Encountered unidirectional transform during encode: ${b}`);this.name="ZodEncodeError"}}var A0={};function Sb(b){if(b)Object.assign(A0,b);return A0}var n={};kW(n,{unwrapMessage:()=>O1,uint8ArrayToHex:()=>U7,uint8ArrayToBase64url:()=>q7,uint8ArrayToBase64:()=>oW,stringifyPrimitive:()=>U0,shallowClone:()=>mW,safeExtend:()=>H7,required:()=>z7,randomString:()=>w7,propertyKeyTypes:()=>b4,promiseAllObject:()=>b7,primitiveTypes:()=>nW,prefixIssues:()=>ww,pick:()=>G7,partial:()=>D7,optionalKeys:()=>w4,omit:()=>X7,objectClone:()=>ez,numKeys:()=>$7,nullish:()=>q1,normalizeParams:()=>_,mergeDefs:()=>qw,merge:()=>J7,jsonStringifyReplacer:()=>hw,joinValues:()=>O0,issue:()=>cw,isPlainObject:()=>Lw,isObject:()=>_w,hexToUint8Array:()=>L7,getSizableOrigin:()=>iW,getParsedType:()=>W7,getLengthableOrigin:()=>U1,getEnumValues:()=>e$,getElementAtPath:()=>az,floatSafeRemainder:()=>s$,finalizeIssue:()=>ub,extend:()=>Y7,escapeRegex:()=>bw,esc:()=>q0,defineLazy:()=>o,createTransparentProxy:()=>Q7,cloneDef:()=>sz,clone:()=>xb,cleanRegex:()=>L1,cleanEnum:()=>A7,captureStackTrace:()=>L0,cached:()=>fw,base64urlToUint8Array:()=>O7,base64ToUint8Array:()=>pW,assignProp:()=>Ow,assertNotEqual:()=>oz,assertNever:()=>tz,assertIs:()=>dz,assertEqual:()=>pz,assert:()=>rz,allowsEval:()=>a$,aborted:()=>Uw,NUMBER_FORMAT_RANGES:()=>$4,Class:()=>dW,BIGINT_FORMAT_RANGES:()=>lW});function pz(b){return b}function oz(b){return b}function dz(b){}function tz(b){throw Error()}function rz(b){}function e$(b){let w=Object.values(b).filter((W)=>typeof W==="number");return Object.entries(b).filter(([W,Q])=>w.indexOf(+W)===-1).map(([W,Q])=>Q)}function O0(b,w="|"){return b.map(($)=>U0($)).join(w)}function hw(b,w){if(typeof w==="bigint")return w.toString();return w}function fw(b){return{get value(){{let $=b();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function q1(b){return b===null||b===void 0}function L1(b){let w=b.startsWith("^")?1:0,$=b.endsWith("$")?b.length-1:b.length;return b.slice(w,$)}function s$(b,w){let $=(b.toString().split(".")[1]||"").length,W=w.toString(),Q=(W.split(".")[1]||"").length;if(Q===0&&/\d?e-\d?/.test(W)){let H=W.match(/\d?e-(\d?)/);if(H?.[1])Q=Number.parseInt(H[1])}let G=$>Q?$:Q,X=Number.parseInt(b.toFixed(G).replace(".","")),Y=Number.parseInt(w.toFixed(G).replace(".",""));return X%Y/10**G}var gW=Symbol("evaluating");function o(b,w,$){let W=void 0;Object.defineProperty(b,w,{get(){if(W===gW)return;if(W===void 0)W=gW,W=$();return W},set(Q){Object.defineProperty(b,w,{value:Q})},configurable:!0})}function ez(b){return Object.create(Object.getPrototypeOf(b),Object.getOwnPropertyDescriptors(b))}function Ow(b,w,$){Object.defineProperty(b,w,{value:$,writable:!0,enumerable:!0,configurable:!0})}function qw(...b){let w={};for(let $ of b){let W=Object.getOwnPropertyDescriptors($);Object.assign(w,W)}return Object.defineProperties({},w)}function sz(b){return qw(b._zod.def)}function az(b,w){if(!w)return b;return w.reduce(($,W)=>$?.[W],b)}function b7(b){let w=Object.keys(b),$=w.map((W)=>b[W]);return Promise.all($).then((W)=>{let Q={};for(let G=0;G<w.length;G++)Q[w[G]]=W[G];return Q})}function w7(b=10){let $="";for(let W=0;W<b;W++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function q0(b){return JSON.stringify(b)}var L0="captureStackTrace"in Error?Error.captureStackTrace:(...b)=>{};function _w(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}var a$=fw(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(b){return!1}});function Lw(b){if(_w(b)===!1)return!1;let w=b.constructor;if(w===void 0)return!0;let $=w.prototype;if(_w($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function mW(b){if(Lw(b))return{...b};if(Array.isArray(b))return[...b];return b}function $7(b){let w=0;for(let $ in b)if(Object.prototype.hasOwnProperty.call(b,$))w++;return w}var W7=(b)=>{let w=typeof b;switch(w){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(b)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(b))return"array";if(b===null)return"null";if(b.then&&typeof b.then==="function"&&b.catch&&typeof b.catch==="function")return"promise";if(typeof Map<"u"&&b instanceof Map)return"map";if(typeof Set<"u"&&b instanceof Set)return"set";if(typeof Date<"u"&&b instanceof Date)return"date";if(typeof File<"u"&&b instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${w}`)}},b4=new Set(["string","number","symbol"]),nW=new Set(["string","number","bigint","boolean","symbol","undefined"]);function bw(b){return b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xb(b,w,$){let W=new b._zod.constr(w??b._zod.def);if(!w||$?.parent)W._zod.parent=b;return W}function _(b){let w=b;if(!w)return{};if(typeof w==="string")return{error:()=>w};if(w?.message!==void 0){if(w?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");w.error=w.message}if(delete w.message,typeof w.error==="string")return{...w,error:()=>w.error};return w}function Q7(b){let w;return new Proxy({},{get($,W,Q){return w??(w=b()),Reflect.get(w,W,Q)},set($,W,Q,G){return w??(w=b()),Reflect.set(w,W,Q,G)},has($,W){return w??(w=b()),Reflect.has(w,W)},deleteProperty($,W){return w??(w=b()),Reflect.deleteProperty(w,W)},ownKeys($){return w??(w=b()),Reflect.ownKeys(w)},getOwnPropertyDescriptor($,W){return w??(w=b()),Reflect.getOwnPropertyDescriptor(w,W)},defineProperty($,W,Q){return w??(w=b()),Reflect.defineProperty(w,W,Q)}})}function U0(b){if(typeof b==="bigint")return b.toString()+"n";if(typeof b==="string")return`"${b}"`;return`${b}`}function w4(b){return Object.keys(b).filter((w)=>{return b[w]._zod.optin==="optional"&&b[w]._zod.optout==="optional"})}var $4={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},lW={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function G7(b,w){let $=b._zod.def,W=qw(b._zod.def,{get shape(){let Q={};for(let G in w){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;Q[G]=$.shape[G]}return Ow(this,"shape",Q),Q},checks:[]});return xb(b,W)}function X7(b,w){let $=b._zod.def,W=qw(b._zod.def,{get shape(){let Q={...b._zod.def.shape};for(let G in w){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;delete Q[G]}return Ow(this,"shape",Q),Q},checks:[]});return xb(b,W)}function Y7(b,w){if(!Lw(w))throw Error("Invalid input to extend: expected a plain object");let $=b._zod.def.checks;if($&&$.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let Q=qw(b._zod.def,{get shape(){let G={...b._zod.def.shape,...w};return Ow(this,"shape",G),G},checks:[]});return xb(b,Q)}function H7(b,w){if(!Lw(w))throw Error("Invalid input to safeExtend: expected a plain object");let $={...b._zod.def,get shape(){let W={...b._zod.def.shape,...w};return Ow(this,"shape",W),W},checks:b._zod.def.checks};return xb(b,$)}function J7(b,w){let $=qw(b._zod.def,{get shape(){let W={...b._zod.def.shape,...w._zod.def.shape};return Ow(this,"shape",W),W},get catchall(){return w._zod.def.catchall},checks:[]});return xb(b,$)}function D7(b,w,$){let W=qw(w._zod.def,{get shape(){let Q=w._zod.def.shape,G={...Q};if($)for(let X in $){if(!(X in Q))throw Error(`Unrecognized key: "${X}"`);if(!$[X])continue;G[X]=b?new b({type:"optional",innerType:Q[X]}):Q[X]}else for(let X in Q)G[X]=b?new b({type:"optional",innerType:Q[X]}):Q[X];return Ow(this,"shape",G),G},checks:[]});return xb(w,W)}function z7(b,w,$){let W=qw(w._zod.def,{get shape(){let Q=w._zod.def.shape,G={...Q};if($)for(let X in $){if(!(X in G))throw Error(`Unrecognized key: "${X}"`);if(!$[X])continue;G[X]=new b({type:"nonoptional",innerType:Q[X]})}else for(let X in Q)G[X]=new b({type:"nonoptional",innerType:Q[X]});return Ow(this,"shape",G),G},checks:[]});return xb(w,W)}function Uw(b,w=0){if(b.aborted===!0)return!0;for(let $=w;$<b.issues.length;$++)if(b.issues[$]?.continue!==!0)return!0;return!1}function ww(b,w){return w.map(($)=>{var W;return(W=$).path??(W.path=[]),$.path.unshift(b),$})}function O1(b){return typeof b==="string"?b:b?.message}function ub(b,w,$){let W={...b,path:b.path??[]};if(!b.message){let Q=O1(b.inst?._zod.def?.error?.(b))??O1(w?.error?.(b))??O1($.customError?.(b))??O1($.localeError?.(b))??"Invalid input";W.message=Q}if(delete W.inst,delete W.continue,!w?.reportInput)delete W.input;return W}function iW(b){if(b instanceof Set)return"set";if(b instanceof Map)return"map";if(b instanceof File)return"file";return"unknown"}function U1(b){if(Array.isArray(b))return"array";if(typeof b==="string")return"string";return"unknown"}function cw(...b){let[w,$,W]=b;if(typeof w==="string")return{message:w,code:"custom",input:$,inst:W};return{...w}}function A7(b){return Object.entries(b).filter(([w,$])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}function pW(b){let w=atob(b),$=new Uint8Array(w.length);for(let W=0;W<w.length;W++)$[W]=w.charCodeAt(W);return $}function oW(b){let w="";for(let $=0;$<b.length;$++)w+=String.fromCharCode(b[$]);return btoa(w)}function O7(b){let w=b.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-w.length%4)%4);return pW(w+$)}function q7(b){return oW(b).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function L7(b){let w=b.replace(/^0x/,"");if(w.length%2!==0)throw Error("Invalid hex string length");let $=new Uint8Array(w.length/2);for(let W=0;W<w.length;W+=2)$[W/2]=Number.parseInt(w.slice(W,W+2),16);return $}function U7(b){return Array.from(b).map((w)=>w.toString(16).padStart(2,"0")).join("")}class dW{constructor(...b){}}var tW=(b,w)=>{b.name="$ZodError",Object.defineProperty(b,"_zod",{value:b._zod,enumerable:!1}),Object.defineProperty(b,"issues",{value:w,enumerable:!1}),b.message=JSON.stringify(w,hw,2),Object.defineProperty(b,"toString",{value:()=>b.message,enumerable:!1})},B0=U("$ZodError",tW),W4=U("$ZodError",tW,{Parent:Error});function rW(b,w=($)=>$.message){let $={},W=[];for(let Q of b.issues)if(Q.path.length>0)$[Q.path[0]]=$[Q.path[0]]||[],$[Q.path[0]].push(w(Q));else W.push(w(Q));return{formErrors:W,fieldErrors:$}}function eW(b,w=($)=>$.message){let $={_errors:[]},W=(Q)=>{for(let G of Q.issues)if(G.code==="invalid_union"&&G.errors.length)G.errors.map((X)=>W({issues:X}));else if(G.code==="invalid_key")W({issues:G.issues});else if(G.code==="invalid_element")W({issues:G.issues});else if(G.path.length===0)$._errors.push(w(G));else{let X=$,Y=0;while(Y<G.path.length){let H=G.path[Y];if(Y!==G.path.length-1)X[H]=X[H]||{_errors:[]};else X[H]=X[H]||{_errors:[]},X[H]._errors.push(w(G));X=X[H],Y++}}};return W(b),$}var F0=(b)=>(w,$,W,Q)=>{let G=W?Object.assign(W,{async:!1}):{async:!1},X=w._zod.run({value:$,issues:[]},G);if(X instanceof Promise)throw new ab;if(X.issues.length){let Y=new(Q?.Err??b)(X.issues.map((H)=>ub(H,G,Sb())));throw L0(Y,Q?.callee),Y}return X.value};var K0=(b)=>async(w,$,W,Q)=>{let G=W?Object.assign(W,{async:!0}):{async:!0},X=w._zod.run({value:$,issues:[]},G);if(X instanceof Promise)X=await X;if(X.issues.length){let Y=new(Q?.Err??b)(X.issues.map((H)=>ub(H,G,Sb())));throw L0(Y,Q?.callee),Y}return X.value};var B1=(b)=>(w,$,W)=>{let Q=W?{...W,async:!1}:{async:!1},G=w._zod.run({value:$,issues:[]},Q);if(G instanceof Promise)throw new ab;return G.issues.length?{success:!1,error:new(b??B0)(G.issues.map((X)=>ub(X,Q,Sb())))}:{success:!0,data:G.value}},F1=B1(W4),K1=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{async:!0}):{async:!0},G=w._zod.run({value:$,issues:[]},Q);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new b(G.issues.map((X)=>ub(X,Q,Sb())))}:{success:!0,data:G.value}},P0=K1(W4),sW=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return F0(b)(w,$,Q)};var aW=(b)=>(w,$,W)=>{return F0(b)(w,$,W)};var bQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return K0(b)(w,$,Q)};var wQ=(b)=>async(w,$,W)=>{return K0(b)(w,$,W)};var $Q=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return B1(b)(w,$,Q)};var WQ=(b)=>(w,$,W)=>{return B1(b)(w,$,W)};var QQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return K1(b)(w,$,Q)};var GQ=(b)=>async(w,$,W)=>{return K1(b)(w,$,W)};var XQ=/^[cC][^\s-]{8,}$/,YQ=/^[0-9a-z]+$/,HQ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,JQ=/^[0-9a-vA-V]{20}$/,DQ=/^[A-Za-z0-9]{27}$/,zQ=/^[a-zA-Z0-9_-]{21}$/,AQ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var OQ=/^([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})$/,Q4=(b)=>{if(!b)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${b}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var qQ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function LQ(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var UQ=/^(?:(?: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])$/,BQ=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,FQ=/^((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])$/,KQ=/^(([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])$/,PQ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,G4=/^[A-Za-z0-9_-]*$/,MQ=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var ZQ=/^\+(?:[0-9]){6,14}[0-9]$/,jQ="(?:(?:\\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])))",IQ=new RegExp(`^${jQ}$`);function VQ(b){return typeof b.precision==="number"?b.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":b.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${b.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function NQ(b){return new RegExp(`^${VQ(b)}$`)}function TQ(b){let w=VQ({precision:b.precision}),$=["Z"];if(b.local)$.push("");if(b.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let W=`${w}(?:${$.join("|")})`;return new RegExp(`^${jQ}T(?:${W})$`)}var EQ=(b)=>{let w=b?`[\\s\\S]{${b?.minimum??0},${b?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)};var _Q=/^-?\d+$/,SQ=/^-?\d+(?:\.\d+)?/,RQ=/^(?:true|false)$/i,kQ=/^null$/i;var vQ=/^[^A-Z]*$/,CQ=/^[^a-z]*$/;var Jb=U("$ZodCheck",(b,w)=>{var $;b._zod??(b._zod={}),b._zod.def=w,($=b._zod).onattach??($.onattach=[])}),xQ={number:"number",bigint:"bigint",object:"date"},X4=U("$ZodCheckLessThan",(b,w)=>{Jb.init(b,w);let $=xQ[typeof w.value];b._zod.onattach.push((W)=>{let Q=W._zod.bag,G=(w.inclusive?Q.maximum:Q.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(w.value<G)if(w.inclusive)Q.maximum=w.value;else Q.exclusiveMaximum=w.value}),b._zod.check=(W)=>{if(w.inclusive?W.value<=w.value:W.value<w.value)return;W.issues.push({origin:$,code:"too_big",maximum:w.value,input:W.value,inclusive:w.inclusive,inst:b,continue:!w.abort})}}),Y4=U("$ZodCheckGreaterThan",(b,w)=>{Jb.init(b,w);let $=xQ[typeof w.value];b._zod.onattach.push((W)=>{let Q=W._zod.bag,G=(w.inclusive?Q.minimum:Q.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(w.value>G)if(w.inclusive)Q.minimum=w.value;else Q.exclusiveMinimum=w.value}),b._zod.check=(W)=>{if(w.inclusive?W.value>=w.value:W.value>w.value)return;W.issues.push({origin:$,code:"too_small",minimum:w.value,input:W.value,inclusive:w.inclusive,inst:b,continue:!w.abort})}}),uQ=U("$ZodCheckMultipleOf",(b,w)=>{Jb.init(b,w),b._zod.onattach.push(($)=>{var W;(W=$._zod.bag).multipleOf??(W.multipleOf=w.value)}),b._zod.check=($)=>{if(typeof $.value!==typeof w.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof $.value==="bigint"?$.value%w.value===BigInt(0):s$($.value,w.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:w.value,input:$.value,inst:b,continue:!w.abort})}}),yQ=U("$ZodCheckNumberFormat",(b,w)=>{Jb.init(b,w),w.format=w.format||"float64";let $=w.format?.includes("int"),W=$?"int":"number",[Q,G]=$4[w.format];b._zod.onattach.push((X)=>{let Y=X._zod.bag;if(Y.format=w.format,Y.minimum=Q,Y.maximum=G,$)Y.pattern=_Q}),b._zod.check=(X)=>{let Y=X.value;if($){if(!Number.isInteger(Y)){X.issues.push({expected:W,format:w.format,code:"invalid_type",continue:!1,input:Y,inst:b});return}if(!Number.isSafeInteger(Y)){if(Y>0)X.issues.push({input:Y,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:W,continue:!w.abort});else X.issues.push({input:Y,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:W,continue:!w.abort});return}}if(Y<Q)X.issues.push({origin:"number",input:Y,code:"too_small",minimum:Q,inclusive:!0,inst:b,continue:!w.abort});if(Y>G)X.issues.push({origin:"number",input:Y,code:"too_big",maximum:G,inst:b})}});var hQ=U("$ZodCheckMaxLength",(b,w)=>{var $;Jb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!q1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag.maximum??Number.POSITIVE_INFINITY;if(w.maximum<Q)W._zod.bag.maximum=w.maximum}),b._zod.check=(W)=>{let Q=W.value;if(Q.length<=w.maximum)return;let X=U1(Q);W.issues.push({origin:X,code:"too_big",maximum:w.maximum,inclusive:!0,input:Q,inst:b,continue:!w.abort})}}),fQ=U("$ZodCheckMinLength",(b,w)=>{var $;Jb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!q1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(w.minimum>Q)W._zod.bag.minimum=w.minimum}),b._zod.check=(W)=>{let Q=W.value;if(Q.length>=w.minimum)return;let X=U1(Q);W.issues.push({origin:X,code:"too_small",minimum:w.minimum,inclusive:!0,input:Q,inst:b,continue:!w.abort})}}),cQ=U("$ZodCheckLengthEquals",(b,w)=>{var $;Jb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!q1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.minimum=w.length,Q.maximum=w.length,Q.length=w.length}),b._zod.check=(W)=>{let Q=W.value,G=Q.length;if(G===w.length)return;let X=U1(Q),Y=G>w.length;W.issues.push({origin:X,...Y?{code:"too_big",maximum:w.length}:{code:"too_small",minimum:w.length},inclusive:!0,exact:!0,input:W.value,inst:b,continue:!w.abort})}}),P1=U("$ZodCheckStringFormat",(b,w)=>{var $,W;if(Jb.init(b,w),b._zod.onattach.push((Q)=>{let G=Q._zod.bag;if(G.format=w.format,w.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(w.pattern)}),w.pattern)($=b._zod).check??($.check=(Q)=>{if(w.pattern.lastIndex=0,w.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:w.format,input:Q.value,...w.pattern?{pattern:w.pattern.toString()}:{},inst:b,continue:!w.abort})});else(W=b._zod).check??(W.check=()=>{})}),gQ=U("$ZodCheckRegex",(b,w)=>{P1.init(b,w),b._zod.check=($)=>{if(w.pattern.lastIndex=0,w.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:"regex",input:$.value,pattern:w.pattern.toString(),inst:b,continue:!w.abort})}}),mQ=U("$ZodCheckLowerCase",(b,w)=>{w.pattern??(w.pattern=vQ),P1.init(b,w)}),nQ=U("$ZodCheckUpperCase",(b,w)=>{w.pattern??(w.pattern=CQ),P1.init(b,w)}),lQ=U("$ZodCheckIncludes",(b,w)=>{Jb.init(b,w);let $=bw(w.includes),W=new RegExp(typeof w.position==="number"?`^.{${w.position}}${$}`:$);w.pattern=W,b._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(W)}),b._zod.check=(Q)=>{if(Q.value.includes(w.includes,w.position))return;Q.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:w.includes,input:Q.value,inst:b,continue:!w.abort})}}),iQ=U("$ZodCheckStartsWith",(b,w)=>{Jb.init(b,w);let $=new RegExp(`^${bw(w.prefix)}.*`);w.pattern??(w.pattern=$),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),b._zod.check=(W)=>{if(W.value.startsWith(w.prefix))return;W.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:w.prefix,input:W.value,inst:b,continue:!w.abort})}}),pQ=U("$ZodCheckEndsWith",(b,w)=>{Jb.init(b,w);let $=new RegExp(`.*${bw(w.suffix)}$`);w.pattern??(w.pattern=$),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),b._zod.check=(W)=>{if(W.value.endsWith(w.suffix))return;W.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:w.suffix,input:W.value,inst:b,continue:!w.abort})}});var oQ=U("$ZodCheckOverwrite",(b,w)=>{Jb.init(b,w),b._zod.check=($)=>{$.value=w.tx($.value)}});class H4{constructor(b=[]){if(this.content=[],this.indent=0,this)this.args=b}indented(b){this.indent+=1,b(this),this.indent-=1}write(b){if(typeof b==="function"){b(this,{execution:"sync"}),b(this,{execution:"async"});return}let $=b.split(`
8
+ deps: ${$}}`};var NP={keyword:"dependencies",type:"object",schemaType:"object",error:lY.error,code(b){let[w,$]=TP(b);mY(b,w),iY(b,$)}};function TP({schema:b}){let w={},$={};for(let W in b){if(W==="__proto__")continue;let Q=Array.isArray(b[W])?w:$;Q[W]=b[W]}return[w,$]}function mY(b,w=b.schema){let{gen:$,data:W,it:Q}=b;if(Object.keys(w).length===0)return;let G=$.let("missing");for(let D in w){let X=w[D];if(X.length===0)continue;let Y=(0,W0.propertyInData)($,W,D,Q.opts.ownProperties);if(b.setParams({property:D,depsCount:X.length,deps:X.join(", ")}),Q.allErrors)$.if(Y,()=>{for(let H of X)(0,W0.checkReportMissingProp)(b,H)});else $.if(i6._`${Y} && (${(0,W0.checkMissingProp)(b,X,G)})`),(0,W0.reportMissingProp)(b,G),$.else()}}lY.validatePropertyDeps=mY;function iY(b,w=b.schema){let{gen:$,data:W,keyword:Q,it:G}=b,D=$.name("valid");for(let X in w){if((0,VP.alwaysValidSchema)(G,w[X]))continue;$.if((0,W0.propertyInData)($,W,X,G.opts.ownProperties),()=>{let Y=b.subschema({keyword:Q,schemaProp:X},D);b.mergeValidEvaluated(Y,D)},()=>$.var(D,!0)),b.ok(D)}}lY.validateSchemaDeps=iY;lY.default=NP});var eY=j((rY)=>{Object.defineProperty(rY,"__esModule",{value:!0});var tY=x(),SP=i(),RP={message:"property name must be valid",params:({params:b})=>tY._`{propertyName: ${b.propertyName}}`},vP={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:RP,code(b){let{gen:w,schema:$,data:W,it:Q}=b;if((0,SP.alwaysValidSchema)(Q,$))return;let G=w.name("valid");w.forIn("key",W,(D)=>{b.setParams({propertyName:D}),b.subschema({keyword:"propertyNames",data:D,dataTypes:["string"],propertyName:D,compositeRule:!0},G),w.if((0,tY.not)(G),()=>{if(b.error(!0),!Q.allErrors)w.break()})}),b.ok(G)}};rY.default=vP});var l6=j((sY)=>{Object.defineProperty(sY,"__esModule",{value:!0});var V$=Cb(),gb=x(),CP=Qw(),N$=i(),uP={message:"must NOT have additional properties",params:({params:b})=>gb._`{additionalProperty: ${b.additionalProperty}}`},xP={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:uP,code(b){let{gen:w,schema:$,parentSchema:W,data:Q,errsCount:G,it:D}=b;if(!G)throw Error("ajv implementation error");let{allErrors:X,opts:Y}=D;if(D.props=!0,Y.removeAdditional!=="all"&&(0,N$.alwaysValidSchema)(D,$))return;let H=(0,V$.allSchemaProperties)(W.properties),J=(0,V$.allSchemaProperties)(W.patternProperties);z(),b.ok(gb._`${G} === ${CP.default.errors}`);function z(){w.forIn("key",Q,(I)=>{if(!H.length&&!J.length)B(I);else w.if(O(I),()=>B(I))})}function O(I){let M;if(H.length>8){let v=(0,N$.schemaRefOrVal)(D,W.properties,"properties");M=(0,V$.isOwnProperty)(w,v,I)}else if(H.length)M=(0,gb.or)(...H.map((v)=>gb._`${I} === ${v}`));else M=gb.nil;if(J.length)M=(0,gb.or)(M,...J.map((v)=>gb._`${(0,V$.usePattern)(b,v)}.test(${I})`));return(0,gb.not)(M)}function q(I){w.code(gb._`delete ${Q}[${I}]`)}function B(I){if(Y.removeAdditional==="all"||Y.removeAdditional&&$===!1){q(I);return}if($===!1){if(b.setParams({additionalProperty:I}),b.error(),!X)w.break();return}if(typeof $=="object"&&!(0,N$.alwaysValidSchema)(D,$)){let M=w.name("valid");if(Y.removeAdditional==="failing")K(I,M,!1),w.if((0,gb.not)(M),()=>{b.reset(),q(I)});else if(K(I,M),!X)w.if((0,gb.not)(M),()=>w.break())}}function K(I,M,v){let S={keyword:"additionalProperties",dataProp:I,dataPropType:N$.Type.Str};if(v===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});b.subschema(S,M)}}};sY.default=xP});var $H=j((wH)=>{Object.defineProperty(wH,"__esModule",{value:!0});var hP=l1(),aY=Cb(),p6=i(),bH=l6(),fP={keyword:"properties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,parentSchema:W,data:Q,it:G}=b;if(G.opts.removeAdditional==="all"&&W.additionalProperties===void 0)bH.default.code(new hP.KeywordCxt(G,bH.default,"additionalProperties"));let D=(0,aY.allSchemaProperties)($);for(let z of D)G.definedProperties.add(z);if(G.opts.unevaluated&&D.length&&G.props!==!0)G.props=p6.mergeEvaluated.props(w,(0,p6.toHash)(D),G.props);let X=D.filter((z)=>!(0,p6.alwaysValidSchema)(G,$[z]));if(X.length===0)return;let Y=w.name("valid");for(let z of X){if(H(z))J(z);else{if(w.if((0,aY.propertyInData)(w,Q,z,G.opts.ownProperties)),J(z),!G.allErrors)w.else().var(Y,!0);w.endIf()}b.it.definedProperties.add(z),b.ok(Y)}function H(z){return G.opts.useDefaults&&!G.compositeRule&&$[z].default!==void 0}function J(z){b.subschema({keyword:"properties",schemaProp:z,dataProp:z},Y)}}};wH.default=fP});var XH=j((DH)=>{Object.defineProperty(DH,"__esModule",{value:!0});var WH=Cb(),T$=x(),QH=i(),GH=i(),nP={keyword:"patternProperties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,data:W,parentSchema:Q,it:G}=b,{opts:D}=G,X=(0,WH.allSchemaProperties)($),Y=X.filter((K)=>(0,QH.alwaysValidSchema)(G,$[K]));if(X.length===0||Y.length===X.length&&(!G.opts.unevaluated||G.props===!0))return;let H=D.strictSchema&&!D.allowMatchingProperties&&Q.properties,J=w.name("valid");if(G.props!==!0&&!(G.props instanceof T$.Name))G.props=(0,GH.evaluatedPropsToName)(w,G.props);let{props:z}=G;O();function O(){for(let K of X){if(H)q(K);if(G.allErrors)B(K);else w.var(J,!0),B(K),w.if(J)}}function q(K){for(let I in H)if(new RegExp(K).test(I))(0,QH.checkStrictMode)(G,`property ${I} matches pattern ${K} (use allowMatchingProperties)`)}function B(K){w.forIn("key",W,(I)=>{w.if(T$._`${(0,WH.usePattern)(b,K)}.test(${I})`,()=>{let M=Y.includes(K);if(!M)b.subschema({keyword:"patternProperties",schemaProp:K,dataProp:I,dataPropType:GH.Type.Str},J);if(G.opts.unevaluated&&z!==!0)w.assign(T$._`${z}[${I}]`,!0);else if(!M&&!G.allErrors)w.if((0,T$.not)(J),()=>w.break())})})}}};DH.default=nP});var HH=j((YH)=>{Object.defineProperty(YH,"__esModule",{value:!0});var mP=i(),iP={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(b){let{gen:w,schema:$,it:W}=b;if((0,mP.alwaysValidSchema)(W,$)){b.fail();return}let Q=w.name("valid");b.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},Q),b.failResult(Q,()=>b.reset(),()=>b.error())},error:{message:"must NOT be valid"}};YH.default=iP});var zH=j((JH)=>{Object.defineProperty(JH,"__esModule",{value:!0});var pP=Cb(),oP={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:pP.validateUnion,error:{message:"must match a schema in anyOf"}};JH.default=oP});var OH=j((AH)=>{Object.defineProperty(AH,"__esModule",{value:!0});var E$=x(),tP=i(),rP={message:"must match exactly one schema in oneOf",params:({params:b})=>E$._`{passingSchemas: ${b.passing}}`},eP={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:rP,code(b){let{gen:w,schema:$,parentSchema:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if(Q.opts.discriminator&&W.discriminator)return;let G=$,D=w.let("valid",!1),X=w.let("passing",null),Y=w.name("_valid");b.setParams({passing:X}),w.block(H),b.result(D,()=>b.reset(),()=>b.error(!0));function H(){G.forEach((J,z)=>{let O;if((0,tP.alwaysValidSchema)(Q,J))w.var(Y,!0);else O=b.subschema({keyword:"oneOf",schemaProp:z,compositeRule:!0},Y);if(z>0)w.if(E$._`${Y} && ${D}`).assign(D,!1).assign(X,E$._`[${X}, ${z}]`).else();w.if(Y,()=>{if(w.assign(D,!0),w.assign(X,z),O)b.mergeEvaluated(O,E$.Name)})})}}};AH.default=eP});var LH=j((qH)=>{Object.defineProperty(qH,"__esModule",{value:!0});var aP=i(),bF={keyword:"allOf",schemaType:"array",code(b){let{gen:w,schema:$,it:W}=b;if(!Array.isArray($))throw Error("ajv implementation error");let Q=w.name("valid");$.forEach((G,D)=>{if((0,aP.alwaysValidSchema)(W,G))return;let X=b.subschema({keyword:"allOf",schemaProp:D},Q);b.ok(Q),b.mergeEvaluated(X)})}};qH.default=bF});var FH=j((PH)=>{Object.defineProperty(PH,"__esModule",{value:!0});var _$=x(),BH=i(),$F={message:({params:b})=>_$.str`must match "${b.ifClause}" schema`,params:({params:b})=>_$._`{failingKeyword: ${b.ifClause}}`},WF={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:$F,code(b){let{gen:w,parentSchema:$,it:W}=b;if($.then===void 0&&$.else===void 0)(0,BH.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Q=UH(W,"then"),G=UH(W,"else");if(!Q&&!G)return;let D=w.let("valid",!0),X=w.name("_valid");if(Y(),b.reset(),Q&&G){let J=w.let("ifClause");b.setParams({ifClause:J}),w.if(X,H("then",J),H("else",J))}else if(Q)w.if(X,H("then"));else w.if((0,_$.not)(X),H("else"));b.pass(D,()=>b.error(!0));function Y(){let J=b.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},X);b.mergeEvaluated(J)}function H(J,z){return()=>{let O=b.subschema({keyword:J},X);if(w.assign(D,X),b.mergeValidEvaluated(O,D),z)w.assign(z,_$._`${J}`);else b.setParams({ifClause:J})}}}};function UH(b,w){let $=b.schema[w];return $!==void 0&&!(0,BH.alwaysValidSchema)(b,$)}PH.default=WF});var MH=j((KH)=>{Object.defineProperty(KH,"__esModule",{value:!0});var GF=i(),DF={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:b,parentSchema:w,it:$}){if(w.if===void 0)(0,GF.checkStrictMode)($,`"${b}" without "if" is ignored`)}};KH.default=DF});var ZH=j((IH)=>{Object.defineProperty(IH,"__esModule",{value:!0});var YF=g6(),HF=yY(),JF=m6(),zF=cY(),AF=gY(),OF=dY(),qF=eY(),LF=l6(),UF=$H(),BF=XH(),PF=HH(),FF=zH(),KF=OH(),MF=LH(),IF=FH(),ZF=MH();function jF(b=!1){let w=[PF.default,FF.default,KF.default,MF.default,IF.default,ZF.default,qF.default,LF.default,OF.default,UF.default,BF.default];if(b)w.push(HF.default,zF.default);else w.push(YF.default,JF.default);return w.push(AF.default),w}IH.default=jF});var VH=j((jH)=>{Object.defineProperty(jH,"__esModule",{value:!0});var Gb=x(),NF={message:({schemaCode:b})=>Gb.str`must match format "${b}"`,params:({schemaCode:b})=>Gb._`{format: ${b}}`},TF={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:NF,code(b,w){let{gen:$,data:W,$data:Q,schema:G,schemaCode:D,it:X}=b,{opts:Y,errSchemaPath:H,schemaEnv:J,self:z}=X;if(!Y.validateFormats)return;if(Q)O();else q();function O(){let B=$.scopeValue("formats",{ref:z.formats,code:Y.code.formats}),K=$.const("fDef",Gb._`${B}[${D}]`),I=$.let("fType"),M=$.let("format");$.if(Gb._`typeof ${K} == "object" && !(${K} instanceof RegExp)`,()=>$.assign(I,Gb._`${K}.type || "string"`).assign(M,Gb._`${K}.validate`),()=>$.assign(I,Gb._`"string"`).assign(M,K)),b.fail$data((0,Gb.or)(v(),S()));function v(){if(Y.strictSchema===!1)return Gb.nil;return Gb._`${D} && !${M}`}function S(){let h=J.$async?Gb._`(${K}.async ? await ${M}(${W}) : ${M}(${W}))`:Gb._`${M}(${W})`,R=Gb._`(typeof ${M} == "function" ? ${h} : ${M}.test(${W}))`;return Gb._`${M} && ${M} !== true && ${I} === ${w} && !${R}`}}function q(){let B=z.formats[G];if(!B){v();return}if(B===!0)return;let[K,I,M]=S(B);if(K===w)b.pass(h());function v(){if(Y.strictSchema===!1){z.logger.warn(R());return}throw Error(R());function R(){return`unknown format "${G}" ignored in schema at path "${H}"`}}function S(R){let pb=R instanceof RegExp?(0,Gb.regexpCode)(R):Y.code.formats?Gb._`${Y.code.formats}${(0,Gb.getProperty)(G)}`:void 0,sb=$.scopeValue("formats",{key:G,ref:R,code:pb});if(typeof R=="object"&&!(R instanceof RegExp))return[R.type||"string",R.validate,Gb._`${sb}.validate`];return["string",R,sb]}function h(){if(typeof B=="object"&&!(B instanceof RegExp)&&B.async){if(!J.$async)throw Error("async format in sync schema");return Gb._`await ${M}(${W})`}return typeof I=="function"?Gb._`${M}(${W})`:Gb._`${M}.test(${W})`}}}};jH.default=TF});var TH=j((NH)=>{Object.defineProperty(NH,"__esModule",{value:!0});var _F=VH(),SF=[_F.default];NH.default=SF});var SH=j((EH)=>{Object.defineProperty(EH,"__esModule",{value:!0});EH.contentVocabulary=EH.metadataVocabulary=void 0;EH.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];EH.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var kH=j((vH)=>{Object.defineProperty(vH,"__esModule",{value:!0});var kF=wY(),CF=EY(),uF=ZH(),xF=TH(),RH=SH(),yF=[kF.default,CF.default,(0,uF.default)(),xF.default,RH.metadataVocabulary,RH.contentVocabulary];vH.default=yF});var yH=j((uH)=>{Object.defineProperty(uH,"__esModule",{value:!0});uH.DiscrError=void 0;var CH;(function(b){b.Tag="tag",b.Mapping="mapping"})(CH||(uH.DiscrError=CH={}))});var cH=j((fH)=>{Object.defineProperty(fH,"__esModule",{value:!0});var b1=x(),o6=yH(),hH=J$(),fF=p1(),cF=i(),nF={message:({params:{discrError:b,tagName:w}})=>b===o6.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:b,tag:w,tagName:$}})=>b1._`{error: ${b}, tag: ${$}, tagValue: ${w}}`},gF={keyword:"discriminator",type:"object",schemaType:"object",error:nF,code(b){let{gen:w,data:$,schema:W,parentSchema:Q,it:G}=b,{oneOf:D}=Q;if(!G.opts.discriminator)throw Error("discriminator: requires discriminator option");let X=W.propertyName;if(typeof X!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!D)throw Error("discriminator: requires oneOf keyword");let Y=w.let("valid",!1),H=w.const("tag",b1._`${$}${(0,b1.getProperty)(X)}`);w.if(b1._`typeof ${H} == "string"`,()=>J(),()=>b.error(!1,{discrError:o6.DiscrError.Tag,tag:H,tagName:X})),b.ok(Y);function J(){let q=O();w.if(!1);for(let B in q)w.elseIf(b1._`${H} === ${B}`),w.assign(Y,z(q[B]));w.else(),b.error(!1,{discrError:o6.DiscrError.Mapping,tag:H,tagName:X}),w.endIf()}function z(q){let B=w.name("valid"),K=b.subschema({keyword:"oneOf",schemaProp:q},B);return b.mergeEvaluated(K,b1.Name),B}function O(){var q;let B={},K=M(Q),I=!0;for(let h=0;h<D.length;h++){let R=D[h];if((R===null||R===void 0?void 0:R.$ref)&&!(0,cF.schemaHasRulesButRef)(R,G.self.RULES)){let sb=R.$ref;if(R=hH.resolveRef.call(G.self,G.schemaEnv.root,G.baseId,sb),R instanceof hH.SchemaEnv)R=R.schema;if(R===void 0)throw new fF.default(G.opts.uriResolver,G.baseId,sb)}let pb=(q=R===null||R===void 0?void 0:R.properties)===null||q===void 0?void 0:q[X];if(typeof pb!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${X}"`);I=I&&(K||M(R)),v(pb,h)}if(!I)throw Error(`discriminator: "${X}" must be required`);return B;function M({required:h}){return Array.isArray(h)&&h.includes(X)}function v(h,R){if(h.const)S(h.const,R);else if(h.enum)for(let pb of h.enum)S(pb,R);else throw Error(`discriminator: "properties/${X}" must have "const" or "enum"`)}function S(h,R){if(typeof h!="string"||h in B)throw Error(`discriminator: "${X}" values must be unique strings`);B[h]=R}}}};fH.default=gF});var nH=j((lE,iF)=>{iF.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 t6=j((Vb,d6)=>{Object.defineProperty(Vb,"__esModule",{value:!0});Vb.MissingRefError=Vb.ValidationError=Vb.CodeGen=Vb.Name=Vb.nil=Vb.stringify=Vb.str=Vb._=Vb.KeywordCxt=Vb.Ajv=void 0;var lF=lX(),pF=kH(),oF=cH(),gH=nH(),dF=["/properties"],S$="http://json-schema.org/draft-07/schema";class Q0 extends lF.default{_addVocabularies(){if(super._addVocabularies(),pF.default.forEach((b)=>this.addVocabulary(b)),this.opts.discriminator)this.addKeyword(oF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let b=this.opts.$data?this.$dataMetaSchema(gH,dF):gH;this.addMetaSchema(b,S$,!1),this.refs["http://json-schema.org/schema"]=S$}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(S$)?S$:void 0)}}Vb.Ajv=Q0;d6.exports=Vb=Q0;d6.exports.Ajv=Q0;Object.defineProperty(Vb,"__esModule",{value:!0});Vb.default=Q0;var tF=l1();Object.defineProperty(Vb,"KeywordCxt",{enumerable:!0,get:function(){return tF.KeywordCxt}});var w1=x();Object.defineProperty(Vb,"_",{enumerable:!0,get:function(){return w1._}});Object.defineProperty(Vb,"str",{enumerable:!0,get:function(){return w1.str}});Object.defineProperty(Vb,"stringify",{enumerable:!0,get:function(){return w1.stringify}});Object.defineProperty(Vb,"nil",{enumerable:!0,get:function(){return w1.nil}});Object.defineProperty(Vb,"Name",{enumerable:!0,get:function(){return w1.Name}});Object.defineProperty(Vb,"CodeGen",{enumerable:!0,get:function(){return w1.CodeGen}});var rF=Y$();Object.defineProperty(Vb,"ValidationError",{enumerable:!0,get:function(){return rF.default}});var eF=p1();Object.defineProperty(Vb,"MissingRefError",{enumerable:!0,get:function(){return eF.default}})});var sH=j((rH)=>{Object.defineProperty(rH,"__esModule",{value:!0});rH.formatNames=rH.fastFormats=rH.fullFormats=void 0;function rb(b,w){return{validate:b,compare:w}}rH.fullFormats={date:rb(pH,a6),time:rb(e6(!0),bW),"date-time":rb(mH(!0),dH),"iso-time":rb(e6(),oH),"iso-date-time":rb(mH(),tH),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:GK,"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:AK,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:DK,int32:{type:"number",validate:HK},int64:{type:"number",validate:JK},float:{type:"number",validate:lH},double:{type:"number",validate:lH},password:!0,binary:!0};rH.fastFormats={...rH.fullFormats,date:rb(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a6),time:rb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,bW),"date-time":rb(/^\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,dH),"iso-time":rb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,oH),"iso-date-time":rb(/^\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,tH),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};rH.formatNames=Object.keys(rH.fullFormats);function bK(b){return b%4===0&&(b%100!==0||b%400===0)}var wK=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,$K=[0,31,28,31,30,31,30,31,31,30,31,30,31];function pH(b){let w=wK.exec(b);if(!w)return!1;let $=+w[1],W=+w[2],Q=+w[3];return W>=1&&W<=12&&Q>=1&&Q<=(W===2&&bK($)?29:$K[W])}function a6(b,w){if(!(b&&w))return;if(b>w)return 1;if(b<w)return-1;return 0}var r6=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function e6(b){return function($){let W=r6.exec($);if(!W)return!1;let Q=+W[1],G=+W[2],D=+W[3],X=W[4],Y=W[5]==="-"?-1:1,H=+(W[6]||0),J=+(W[7]||0);if(H>23||J>59||b&&!X)return!1;if(Q<=23&&G<=59&&D<60)return!0;let z=G-J*Y,O=Q-H*Y-(z<0?1:0);return(O===23||O===-1)&&(z===59||z===-1)&&D<61}}function bW(b,w){if(!(b&&w))return;let $=new Date("2020-01-01T"+b).valueOf(),W=new Date("2020-01-01T"+w).valueOf();if(!($&&W))return;return $-W}function oH(b,w){if(!(b&&w))return;let $=r6.exec(b),W=r6.exec(w);if(!($&&W))return;if(b=$[1]+$[2]+$[3],w=W[1]+W[2]+W[3],b>w)return 1;if(b<w)return-1;return 0}var s6=/t|\s/i;function mH(b){let w=e6(b);return function(W){let Q=W.split(s6);return Q.length===2&&pH(Q[0])&&w(Q[1])}}function dH(b,w){if(!(b&&w))return;let $=new Date(b).valueOf(),W=new Date(w).valueOf();if(!($&&W))return;return $-W}function tH(b,w){if(!(b&&w))return;let[$,W]=b.split(s6),[Q,G]=w.split(s6),D=a6($,Q);if(D===void 0)return;return D||bW(W,G)}var WK=/\/|:/,QK=/^(?:[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 GK(b){return WK.test(b)&&QK.test(b)}var iH=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function DK(b){return iH.lastIndex=0,iH.test(b)}var XK=-2147483648,YK=2147483647;function HK(b){return Number.isInteger(b)&&b<=YK&&b>=XK}function JK(b){return Number.isInteger(b)}function lH(){return!0}var zK=/[^\\]\\Z/;function AK(b){if(zK.test(b))return!1;try{return new RegExp(b),!0}catch(w){return!1}}});var bJ=j((aH)=>{Object.defineProperty(aH,"__esModule",{value:!0});aH.formatLimitDefinition=void 0;var qK=t6(),mb=x(),Nw=mb.operators,R$={formatMaximum:{okStr:"<=",ok:Nw.LTE,fail:Nw.GT},formatMinimum:{okStr:">=",ok:Nw.GTE,fail:Nw.LT},formatExclusiveMaximum:{okStr:"<",ok:Nw.LT,fail:Nw.GTE},formatExclusiveMinimum:{okStr:">",ok:Nw.GT,fail:Nw.LTE}},LK={message:({keyword:b,schemaCode:w})=>mb.str`should be ${R$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>mb._`{comparison: ${R$[b].okStr}, limit: ${w}}`};aH.formatLimitDefinition={keyword:Object.keys(R$),type:"string",schemaType:"string",$data:!0,error:LK,code(b){let{gen:w,data:$,schemaCode:W,keyword:Q,it:G}=b,{opts:D,self:X}=G;if(!D.validateFormats)return;let Y=new qK.KeywordCxt(G,X.RULES.all.format.definition,"format");if(Y.$data)H();else J();function H(){let O=w.scopeValue("formats",{ref:X.formats,code:D.code.formats}),q=w.const("fmt",mb._`${O}[${Y.schemaCode}]`);b.fail$data((0,mb.or)(mb._`typeof ${q} != "object"`,mb._`${q} instanceof RegExp`,mb._`typeof ${q}.compare != "function"`,z(q)))}function J(){let O=Y.schema,q=X.formats[O];if(!q||q===!0)return;if(typeof q!="object"||q instanceof RegExp||typeof q.compare!="function")throw Error(`"${Q}": format "${O}" does not define "compare" function`);let B=w.scopeValue("formats",{key:O,ref:q,code:D.code.formats?mb._`${D.code.formats}${(0,mb.getProperty)(O)}`:void 0});b.fail$data(z(B))}function z(O){return mb._`${O}.compare(${$}, ${W}) ${R$[Q].fail} 0`}},dependencies:["format"]};var UK=(b)=>{return b.addKeyword(aH.formatLimitDefinition),b};aH.default=UK});var QJ=j((G0,WJ)=>{Object.defineProperty(G0,"__esModule",{value:!0});var $1=sH(),PK=bJ(),WW=x(),wJ=new WW.Name("fullFormats"),FK=new WW.Name("fastFormats"),QW=(b,w={keywords:!0})=>{if(Array.isArray(w))return $J(b,w,$1.fullFormats,wJ),b;let[$,W]=w.mode==="fast"?[$1.fastFormats,FK]:[$1.fullFormats,wJ],Q=w.formats||$1.formatNames;if($J(b,Q,$,W),w.keywords)(0,PK.default)(b);return b};QW.get=(b,w="full")=>{let W=(w==="fast"?$1.fastFormats:$1.fullFormats)[b];if(!W)throw Error(`Unknown format "${b}"`);return W};function $J(b,w,$,W){var Q,G;(Q=(G=b.opts.code).formats)!==null&&Q!==void 0||(G.formats=WW._`require("ajv-formats/dist/formats").${W}`);for(let D of w)b.addFormat(D,$[D])}WJ.exports=G0=QW;Object.defineProperty(G0,"__esModule",{value:!0});G0.default=QW});import{AsyncLocalStorage as dz}from"node:async_hooks";class ob extends Error{statusCode;rawDetails;code;context;constructor(b,w,$,W,Q){super(b);this.statusCode=w;this.rawDetails=$;this.code=W;this.context=Q;this.name="McpApiError"}}function lz(b){if(b instanceof ob)return{message:b.message,statusCode:b.statusCode,code:b.code,rawDetails:b.rawDetails,context:b.context};if(b instanceof Error)return{message:b.message};return{message:String(b)}}function pz(b){let w=b.match(/api key is missing required scopes?:\s*(.+)$/i);if(!w?.[1])return[];return w[1].match(/[a-z_]+:[a-z_]+/gi)??[]}function oz(b){let w=lz(b),$=w.message.trim()||"Unknown error",W=$.toLowerCase(),Q=w.rawDetails?.trim()||$;if(w.context?.title||w.context?.description||w.context?.howToFix||w.context?.docsUrl)return{title:w.context.title??(w.statusCode===409?"Request conflict":"API request failed"),description:w.context.description??$,howToFix:w.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:w.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.code==="MCP_AUTH_REQUIRED"||W.includes("sequenzy_api_key environment variable is required"))return{title:"Missing MCP API key",description:"The MCP server started without a Sequenzy API key, so it cannot authenticate any tool or resource request.",howToFix:"Add `SEQUENZY_API_KEY` to the MCP server environment, or run `npx @sequenzy/setup` to configure the integration automatically.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===401||w.code==="UNAUTHORIZED")return{title:"Authentication failed",description:"The MCP server reached Sequenzy, but the current API key was rejected.",howToFix:"Replace `SEQUENZY_API_KEY` with a valid personal API key, then restart the MCP client so it reconnects with fresh credentials.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};let G=pz($);if(G.length>0){let D=G.map((Y)=>`\`${Y}\``).join(", "),X=G.every((Y)=>Y.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${G.length===1?"scope":"scopes"}: ${D}.`,howToFix:`For a local API-key connection, call \`get_account\` to inspect \`apiKeyPermissions\` and open \`apiKeyPermissions.manageUrl\` (or \`companies[].settingsUrl\` → API Keys). If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and use the MCP setup or Settings → API Keys. Create a replacement key with ${X} including ${D}, replace \`SEQUENZY_API_KEY\`, and restart the client. For hosted OAuth MCP, disconnect and reauthorize the Sequenzy connection with a preset or Custom permissions including ${D}. Existing key permissions cannot be edited in place.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}if(w.statusCode===403||W.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};if(W.includes("no company available")||W.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===404||W.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===409||W.includes("already exists"))return{title:"Resource already exists",description:"Sequenzy rejected this MCP request because it would create a duplicate resource.",howToFix:"List the existing resources first, reuse the matching resource when appropriate, or retry with a unique name or domain.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===429||W.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.code==="NETWORK_ERROR"||W.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("unknown tool")||W.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("is required")||W.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode&&w.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If it still fails, keep the details below and consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}function yw(b){let w=oz(b);return[`Sequenzy MCP error: ${w.title}`,`Description: ${w.description}`,`How to fix: ${w.howToFix}`,`Docs: ${w.docsUrl}`,`Details: ${w.details}`].join(`
9
+ `)}var tz="https://api.sequenzy.com",z1=new dz,kW=!1;function EM(){kW=!0}function z0(){return kW}var CW=null;function Ew(){let b=z1.getStore();if(b)return b.selectedCompanyId??null;return CW}function t$(b){let w=z1.getStore();if(w){w.selectedCompanyId=b;return}CW=b}function uW(b,w){return z1.run(b,w)}function xW(){return z1.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??tz}function yW(){return z1.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function hW(b,w){let $=yW();if(!$)throw new ob("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let W={"Content-Type":b,Authorization:`Bearer ${$}`},Q=w??Ew();if(Q)W["x-company-id"]=Q;return W}function _M(){if(yW())return;console.error(yw(new ob("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function Nb(b,w){let $=b[w];return typeof $==="string"&&$.trim()!==""?$.trim():void 0}function rz(b){if(b===void 0)return;if(typeof b==="string")return b.trim()||void 0;return JSON.stringify(b)}function fW(b){if(!b.trim())return{message:"Request failed"};try{let w=JSON.parse(b);if(typeof w==="string")return{message:w};let $=typeof w.error==="object"&&w.error!==null?w.error:void 0,W=Nb(w,"code")??($?Nb($,"code"):void 0),Q=(typeof w.error==="string"?w.error:void 0)??($?Nb($,"message"):void 0)??Nb(w,"message")??Nb(w,"error")??b,G=Nb(w,"howToFix")??Nb(w,"resolution"),D={...Nb(w,"title")?{title:Nb(w,"title")}:{},...Nb(w,"description")?{description:Nb(w,"description")}:{},...G?{howToFix:G}:{},...Nb(w,"docsUrl")?{docsUrl:Nb(w,"docsUrl")}:{}},X=rz(w.details);if(Object.keys(D).length>0||X)return{message:Q,...W?{code:W}:{},...X?{details:X}:{},...Object.keys(D).length>0?{context:D}:{}};if(typeof w.error==="string")return{message:w.error,...W?{code:W}:{}};if($)return{message:Q,...W?{code:W}:{}};return{message:Q,...W?{code:W}:{}}}catch{return{message:b}}}async function A(b,w,$,W){let Q=hW("application/json",W),G;try{G=await fetch(`${xW()}${w}`,{method:b,headers:Q,body:$?JSON.stringify($):void 0})}catch(D){throw new ob(D instanceof Error?D.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!G.ok){let D=await G.text(),X=fW(D);throw new ob(X.message,G.status,X.details??D,X.code,X.context)}return G.json()}async function cW(b,w,$,W){let Q=new URL(xW()).origin,G=new URL(b,`${Q}/`);if(G.origin!==Q)throw new ob("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");let D;try{D=await fetch(G,{method:"PUT",headers:hW($,W),body:w})}catch(X){throw new ob(X instanceof Error?X.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!D.ok){let X=await D.text(),Y=fW(X);throw new ob(Y.message,D.status,Y.details??X,Y.code,Y.context)}}var RM=Object.freeze({status:"aborted"});function U(b,w,$){function W(X,Y){var H;Object.defineProperty(X,"_zod",{value:X._zod??{},enumerable:!1}),(H=X._zod).traits??(H.traits=new Set),X._zod.traits.add(b),w(X,Y);for(let J in D.prototype)if(!(J in X))Object.defineProperty(X,J,{value:D.prototype[J].bind(X)});X._zod.constr=D,X._zod.def=Y}let Q=$?.Parent??Object;class G extends Q{}Object.defineProperty(G,"name",{value:b});function D(X){var Y;let H=$?.Parent?new G:this;W(H,X),(Y=H._zod).deferred??(Y.deferred=[]);for(let J of H._zod.deferred)J();return H}return Object.defineProperty(D,"init",{value:W}),Object.defineProperty(D,Symbol.hasInstance,{value:(X)=>{if($?.Parent&&X instanceof $.Parent)return!0;return X?._zod?.traits?.has(b)}}),Object.defineProperty(D,"name",{value:b}),D}var vM=Symbol("zod_brand");class ab extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class A1 extends Error{constructor(b){super(`Encountered unidirectional transform during encode: ${b}`);this.name="ZodEncodeError"}}var A0={};function Rb(b){if(b)Object.assign(A0,b);return A0}var m={};vW(m,{unwrapMessage:()=>O1,uint8ArrayToHex:()=>MA,uint8ArrayToBase64url:()=>FA,uint8ArrayToBase64:()=>oW,stringifyPrimitive:()=>U0,shallowClone:()=>gW,safeExtend:()=>OA,required:()=>UA,randomString:()=>DA,propertyKeyTypes:()=>b4,promiseAllObject:()=>GA,primitiveTypes:()=>mW,prefixIssues:()=>ww,pick:()=>JA,partial:()=>LA,optionalKeys:()=>w4,omit:()=>zA,objectClone:()=>$A,numKeys:()=>XA,nullish:()=>q1,normalizeParams:()=>_,mergeDefs:()=>qw,merge:()=>qA,jsonStringifyReplacer:()=>hw,joinValues:()=>O0,issue:()=>cw,isPlainObject:()=>Lw,isObject:()=>_w,hexToUint8Array:()=>KA,getSizableOrigin:()=>lW,getParsedType:()=>YA,getLengthableOrigin:()=>U1,getEnumValues:()=>e$,getElementAtPath:()=>QA,floatSafeRemainder:()=>s$,finalizeIssue:()=>yb,extend:()=>AA,escapeRegex:()=>bw,esc:()=>q0,defineLazy:()=>d,createTransparentProxy:()=>HA,cloneDef:()=>WA,clone:()=>xb,cleanRegex:()=>L1,cleanEnum:()=>BA,captureStackTrace:()=>L0,cached:()=>fw,base64urlToUint8Array:()=>PA,base64ToUint8Array:()=>pW,assignProp:()=>Ow,assertNotEqual:()=>sz,assertNever:()=>bA,assertIs:()=>az,assertEqual:()=>ez,assert:()=>wA,allowsEval:()=>a$,aborted:()=>Uw,NUMBER_FORMAT_RANGES:()=>$4,Class:()=>dW,BIGINT_FORMAT_RANGES:()=>iW});function ez(b){return b}function sz(b){return b}function az(b){}function bA(b){throw Error()}function wA(b){}function e$(b){let w=Object.values(b).filter((W)=>typeof W==="number");return Object.entries(b).filter(([W,Q])=>w.indexOf(+W)===-1).map(([W,Q])=>Q)}function O0(b,w="|"){return b.map(($)=>U0($)).join(w)}function hw(b,w){if(typeof w==="bigint")return w.toString();return w}function fw(b){return{get value(){{let $=b();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function q1(b){return b===null||b===void 0}function L1(b){let w=b.startsWith("^")?1:0,$=b.endsWith("$")?b.length-1:b.length;return b.slice(w,$)}function s$(b,w){let $=(b.toString().split(".")[1]||"").length,W=w.toString(),Q=(W.split(".")[1]||"").length;if(Q===0&&/\d?e-\d?/.test(W)){let Y=W.match(/\d?e-(\d?)/);if(Y?.[1])Q=Number.parseInt(Y[1])}let G=$>Q?$:Q,D=Number.parseInt(b.toFixed(G).replace(".","")),X=Number.parseInt(w.toFixed(G).replace(".",""));return D%X/10**G}var nW=Symbol("evaluating");function d(b,w,$){let W=void 0;Object.defineProperty(b,w,{get(){if(W===nW)return;if(W===void 0)W=nW,W=$();return W},set(Q){Object.defineProperty(b,w,{value:Q})},configurable:!0})}function $A(b){return Object.create(Object.getPrototypeOf(b),Object.getOwnPropertyDescriptors(b))}function Ow(b,w,$){Object.defineProperty(b,w,{value:$,writable:!0,enumerable:!0,configurable:!0})}function qw(...b){let w={};for(let $ of b){let W=Object.getOwnPropertyDescriptors($);Object.assign(w,W)}return Object.defineProperties({},w)}function WA(b){return qw(b._zod.def)}function QA(b,w){if(!w)return b;return w.reduce(($,W)=>$?.[W],b)}function GA(b){let w=Object.keys(b),$=w.map((W)=>b[W]);return Promise.all($).then((W)=>{let Q={};for(let G=0;G<w.length;G++)Q[w[G]]=W[G];return Q})}function DA(b=10){let $="";for(let W=0;W<b;W++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function q0(b){return JSON.stringify(b)}var L0="captureStackTrace"in Error?Error.captureStackTrace:(...b)=>{};function _w(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}var a$=fw(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(b){return!1}});function Lw(b){if(_w(b)===!1)return!1;let w=b.constructor;if(w===void 0)return!0;let $=w.prototype;if(_w($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function gW(b){if(Lw(b))return{...b};if(Array.isArray(b))return[...b];return b}function XA(b){let w=0;for(let $ in b)if(Object.prototype.hasOwnProperty.call(b,$))w++;return w}var YA=(b)=>{let w=typeof b;switch(w){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(b)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(b))return"array";if(b===null)return"null";if(b.then&&typeof b.then==="function"&&b.catch&&typeof b.catch==="function")return"promise";if(typeof Map<"u"&&b instanceof Map)return"map";if(typeof Set<"u"&&b instanceof Set)return"set";if(typeof Date<"u"&&b instanceof Date)return"date";if(typeof File<"u"&&b instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${w}`)}},b4=new Set(["string","number","symbol"]),mW=new Set(["string","number","bigint","boolean","symbol","undefined"]);function bw(b){return b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xb(b,w,$){let W=new b._zod.constr(w??b._zod.def);if(!w||$?.parent)W._zod.parent=b;return W}function _(b){let w=b;if(!w)return{};if(typeof w==="string")return{error:()=>w};if(w?.message!==void 0){if(w?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");w.error=w.message}if(delete w.message,typeof w.error==="string")return{...w,error:()=>w.error};return w}function HA(b){let w;return new Proxy({},{get($,W,Q){return w??(w=b()),Reflect.get(w,W,Q)},set($,W,Q,G){return w??(w=b()),Reflect.set(w,W,Q,G)},has($,W){return w??(w=b()),Reflect.has(w,W)},deleteProperty($,W){return w??(w=b()),Reflect.deleteProperty(w,W)},ownKeys($){return w??(w=b()),Reflect.ownKeys(w)},getOwnPropertyDescriptor($,W){return w??(w=b()),Reflect.getOwnPropertyDescriptor(w,W)},defineProperty($,W,Q){return w??(w=b()),Reflect.defineProperty(w,W,Q)}})}function U0(b){if(typeof b==="bigint")return b.toString()+"n";if(typeof b==="string")return`"${b}"`;return`${b}`}function w4(b){return Object.keys(b).filter((w)=>{return b[w]._zod.optin==="optional"&&b[w]._zod.optout==="optional"})}var $4={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},iW={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function JA(b,w){let $=b._zod.def,W=qw(b._zod.def,{get shape(){let Q={};for(let G in w){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;Q[G]=$.shape[G]}return Ow(this,"shape",Q),Q},checks:[]});return xb(b,W)}function zA(b,w){let $=b._zod.def,W=qw(b._zod.def,{get shape(){let Q={...b._zod.def.shape};for(let G in w){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;delete Q[G]}return Ow(this,"shape",Q),Q},checks:[]});return xb(b,W)}function AA(b,w){if(!Lw(w))throw Error("Invalid input to extend: expected a plain object");let $=b._zod.def.checks;if($&&$.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let Q=qw(b._zod.def,{get shape(){let G={...b._zod.def.shape,...w};return Ow(this,"shape",G),G},checks:[]});return xb(b,Q)}function OA(b,w){if(!Lw(w))throw Error("Invalid input to safeExtend: expected a plain object");let $={...b._zod.def,get shape(){let W={...b._zod.def.shape,...w};return Ow(this,"shape",W),W},checks:b._zod.def.checks};return xb(b,$)}function qA(b,w){let $=qw(b._zod.def,{get shape(){let W={...b._zod.def.shape,...w._zod.def.shape};return Ow(this,"shape",W),W},get catchall(){return w._zod.def.catchall},checks:[]});return xb(b,$)}function LA(b,w,$){let W=qw(w._zod.def,{get shape(){let Q=w._zod.def.shape,G={...Q};if($)for(let D in $){if(!(D in Q))throw Error(`Unrecognized key: "${D}"`);if(!$[D])continue;G[D]=b?new b({type:"optional",innerType:Q[D]}):Q[D]}else for(let D in Q)G[D]=b?new b({type:"optional",innerType:Q[D]}):Q[D];return Ow(this,"shape",G),G},checks:[]});return xb(w,W)}function UA(b,w,$){let W=qw(w._zod.def,{get shape(){let Q=w._zod.def.shape,G={...Q};if($)for(let D in $){if(!(D in G))throw Error(`Unrecognized key: "${D}"`);if(!$[D])continue;G[D]=new b({type:"nonoptional",innerType:Q[D]})}else for(let D in Q)G[D]=new b({type:"nonoptional",innerType:Q[D]});return Ow(this,"shape",G),G},checks:[]});return xb(w,W)}function Uw(b,w=0){if(b.aborted===!0)return!0;for(let $=w;$<b.issues.length;$++)if(b.issues[$]?.continue!==!0)return!0;return!1}function ww(b,w){return w.map(($)=>{var W;return(W=$).path??(W.path=[]),$.path.unshift(b),$})}function O1(b){return typeof b==="string"?b:b?.message}function yb(b,w,$){let W={...b,path:b.path??[]};if(!b.message){let Q=O1(b.inst?._zod.def?.error?.(b))??O1(w?.error?.(b))??O1($.customError?.(b))??O1($.localeError?.(b))??"Invalid input";W.message=Q}if(delete W.inst,delete W.continue,!w?.reportInput)delete W.input;return W}function lW(b){if(b instanceof Set)return"set";if(b instanceof Map)return"map";if(b instanceof File)return"file";return"unknown"}function U1(b){if(Array.isArray(b))return"array";if(typeof b==="string")return"string";return"unknown"}function cw(...b){let[w,$,W]=b;if(typeof w==="string")return{message:w,code:"custom",input:$,inst:W};return{...w}}function BA(b){return Object.entries(b).filter(([w,$])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}function pW(b){let w=atob(b),$=new Uint8Array(w.length);for(let W=0;W<w.length;W++)$[W]=w.charCodeAt(W);return $}function oW(b){let w="";for(let $=0;$<b.length;$++)w+=String.fromCharCode(b[$]);return btoa(w)}function PA(b){let w=b.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-w.length%4)%4);return pW(w+$)}function FA(b){return oW(b).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function KA(b){let w=b.replace(/^0x/,"");if(w.length%2!==0)throw Error("Invalid hex string length");let $=new Uint8Array(w.length/2);for(let W=0;W<w.length;W+=2)$[W/2]=Number.parseInt(w.slice(W,W+2),16);return $}function MA(b){return Array.from(b).map((w)=>w.toString(16).padStart(2,"0")).join("")}class dW{constructor(...b){}}var tW=(b,w)=>{b.name="$ZodError",Object.defineProperty(b,"_zod",{value:b._zod,enumerable:!1}),Object.defineProperty(b,"issues",{value:w,enumerable:!1}),b.message=JSON.stringify(w,hw,2),Object.defineProperty(b,"toString",{value:()=>b.message,enumerable:!1})},B0=U("$ZodError",tW),W4=U("$ZodError",tW,{Parent:Error});function rW(b,w=($)=>$.message){let $={},W=[];for(let Q of b.issues)if(Q.path.length>0)$[Q.path[0]]=$[Q.path[0]]||[],$[Q.path[0]].push(w(Q));else W.push(w(Q));return{formErrors:W,fieldErrors:$}}function eW(b,w=($)=>$.message){let $={_errors:[]},W=(Q)=>{for(let G of Q.issues)if(G.code==="invalid_union"&&G.errors.length)G.errors.map((D)=>W({issues:D}));else if(G.code==="invalid_key")W({issues:G.issues});else if(G.code==="invalid_element")W({issues:G.issues});else if(G.path.length===0)$._errors.push(w(G));else{let D=$,X=0;while(X<G.path.length){let Y=G.path[X];if(X!==G.path.length-1)D[Y]=D[Y]||{_errors:[]};else D[Y]=D[Y]||{_errors:[]},D[Y]._errors.push(w(G));D=D[Y],X++}}};return W(b),$}var P0=(b)=>(w,$,W,Q)=>{let G=W?Object.assign(W,{async:!1}):{async:!1},D=w._zod.run({value:$,issues:[]},G);if(D instanceof Promise)throw new ab;if(D.issues.length){let X=new(Q?.Err??b)(D.issues.map((Y)=>yb(Y,G,Rb())));throw L0(X,Q?.callee),X}return D.value};var F0=(b)=>async(w,$,W,Q)=>{let G=W?Object.assign(W,{async:!0}):{async:!0},D=w._zod.run({value:$,issues:[]},G);if(D instanceof Promise)D=await D;if(D.issues.length){let X=new(Q?.Err??b)(D.issues.map((Y)=>yb(Y,G,Rb())));throw L0(X,Q?.callee),X}return D.value};var B1=(b)=>(w,$,W)=>{let Q=W?{...W,async:!1}:{async:!1},G=w._zod.run({value:$,issues:[]},Q);if(G instanceof Promise)throw new ab;return G.issues.length?{success:!1,error:new(b??B0)(G.issues.map((D)=>yb(D,Q,Rb())))}:{success:!0,data:G.value}},P1=B1(W4),F1=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{async:!0}):{async:!0},G=w._zod.run({value:$,issues:[]},Q);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new b(G.issues.map((D)=>yb(D,Q,Rb())))}:{success:!0,data:G.value}},K0=F1(W4),sW=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return P0(b)(w,$,Q)};var aW=(b)=>(w,$,W)=>{return P0(b)(w,$,W)};var bQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return F0(b)(w,$,Q)};var wQ=(b)=>async(w,$,W)=>{return F0(b)(w,$,W)};var $Q=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return B1(b)(w,$,Q)};var WQ=(b)=>(w,$,W)=>{return B1(b)(w,$,W)};var QQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return F1(b)(w,$,Q)};var GQ=(b)=>async(w,$,W)=>{return F1(b)(w,$,W)};var DQ=/^[cC][^\s-]{8,}$/,XQ=/^[0-9a-z]+$/,YQ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,HQ=/^[0-9a-vA-V]{20}$/,JQ=/^[A-Za-z0-9]{27}$/,zQ=/^[a-zA-Z0-9_-]{21}$/,AQ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var OQ=/^([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})$/,Q4=(b)=>{if(!b)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${b}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var qQ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function LQ(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var UQ=/^(?:(?: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])$/,BQ=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,PQ=/^((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])$/,FQ=/^(([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])$/,KQ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,G4=/^[A-Za-z0-9_-]*$/,MQ=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var IQ=/^\+(?:[0-9]){6,14}[0-9]$/,ZQ="(?:(?:\\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])))",jQ=new RegExp(`^${ZQ}$`);function VQ(b){return typeof b.precision==="number"?b.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":b.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${b.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function NQ(b){return new RegExp(`^${VQ(b)}$`)}function TQ(b){let w=VQ({precision:b.precision}),$=["Z"];if(b.local)$.push("");if(b.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let W=`${w}(?:${$.join("|")})`;return new RegExp(`^${ZQ}T(?:${W})$`)}var EQ=(b)=>{let w=b?`[\\s\\S]{${b?.minimum??0},${b?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)};var _Q=/^-?\d+$/,SQ=/^-?\d+(?:\.\d+)?/,RQ=/^(?:true|false)$/i,vQ=/^null$/i;var kQ=/^[^A-Z]*$/,CQ=/^[^a-z]*$/;var Hb=U("$ZodCheck",(b,w)=>{var $;b._zod??(b._zod={}),b._zod.def=w,($=b._zod).onattach??($.onattach=[])}),uQ={number:"number",bigint:"bigint",object:"date"},D4=U("$ZodCheckLessThan",(b,w)=>{Hb.init(b,w);let $=uQ[typeof w.value];b._zod.onattach.push((W)=>{let Q=W._zod.bag,G=(w.inclusive?Q.maximum:Q.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(w.value<G)if(w.inclusive)Q.maximum=w.value;else Q.exclusiveMaximum=w.value}),b._zod.check=(W)=>{if(w.inclusive?W.value<=w.value:W.value<w.value)return;W.issues.push({origin:$,code:"too_big",maximum:w.value,input:W.value,inclusive:w.inclusive,inst:b,continue:!w.abort})}}),X4=U("$ZodCheckGreaterThan",(b,w)=>{Hb.init(b,w);let $=uQ[typeof w.value];b._zod.onattach.push((W)=>{let Q=W._zod.bag,G=(w.inclusive?Q.minimum:Q.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(w.value>G)if(w.inclusive)Q.minimum=w.value;else Q.exclusiveMinimum=w.value}),b._zod.check=(W)=>{if(w.inclusive?W.value>=w.value:W.value>w.value)return;W.issues.push({origin:$,code:"too_small",minimum:w.value,input:W.value,inclusive:w.inclusive,inst:b,continue:!w.abort})}}),xQ=U("$ZodCheckMultipleOf",(b,w)=>{Hb.init(b,w),b._zod.onattach.push(($)=>{var W;(W=$._zod.bag).multipleOf??(W.multipleOf=w.value)}),b._zod.check=($)=>{if(typeof $.value!==typeof w.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof $.value==="bigint"?$.value%w.value===BigInt(0):s$($.value,w.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:w.value,input:$.value,inst:b,continue:!w.abort})}}),yQ=U("$ZodCheckNumberFormat",(b,w)=>{Hb.init(b,w),w.format=w.format||"float64";let $=w.format?.includes("int"),W=$?"int":"number",[Q,G]=$4[w.format];b._zod.onattach.push((D)=>{let X=D._zod.bag;if(X.format=w.format,X.minimum=Q,X.maximum=G,$)X.pattern=_Q}),b._zod.check=(D)=>{let X=D.value;if($){if(!Number.isInteger(X)){D.issues.push({expected:W,format:w.format,code:"invalid_type",continue:!1,input:X,inst:b});return}if(!Number.isSafeInteger(X)){if(X>0)D.issues.push({input:X,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:W,continue:!w.abort});else D.issues.push({input:X,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:W,continue:!w.abort});return}}if(X<Q)D.issues.push({origin:"number",input:X,code:"too_small",minimum:Q,inclusive:!0,inst:b,continue:!w.abort});if(X>G)D.issues.push({origin:"number",input:X,code:"too_big",maximum:G,inst:b})}});var hQ=U("$ZodCheckMaxLength",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!q1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag.maximum??Number.POSITIVE_INFINITY;if(w.maximum<Q)W._zod.bag.maximum=w.maximum}),b._zod.check=(W)=>{let Q=W.value;if(Q.length<=w.maximum)return;let D=U1(Q);W.issues.push({origin:D,code:"too_big",maximum:w.maximum,inclusive:!0,input:Q,inst:b,continue:!w.abort})}}),fQ=U("$ZodCheckMinLength",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!q1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(w.minimum>Q)W._zod.bag.minimum=w.minimum}),b._zod.check=(W)=>{let Q=W.value;if(Q.length>=w.minimum)return;let D=U1(Q);W.issues.push({origin:D,code:"too_small",minimum:w.minimum,inclusive:!0,input:Q,inst:b,continue:!w.abort})}}),cQ=U("$ZodCheckLengthEquals",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!q1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.minimum=w.length,Q.maximum=w.length,Q.length=w.length}),b._zod.check=(W)=>{let Q=W.value,G=Q.length;if(G===w.length)return;let D=U1(Q),X=G>w.length;W.issues.push({origin:D,...X?{code:"too_big",maximum:w.length}:{code:"too_small",minimum:w.length},inclusive:!0,exact:!0,input:W.value,inst:b,continue:!w.abort})}}),K1=U("$ZodCheckStringFormat",(b,w)=>{var $,W;if(Hb.init(b,w),b._zod.onattach.push((Q)=>{let G=Q._zod.bag;if(G.format=w.format,w.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(w.pattern)}),w.pattern)($=b._zod).check??($.check=(Q)=>{if(w.pattern.lastIndex=0,w.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:w.format,input:Q.value,...w.pattern?{pattern:w.pattern.toString()}:{},inst:b,continue:!w.abort})});else(W=b._zod).check??(W.check=()=>{})}),nQ=U("$ZodCheckRegex",(b,w)=>{K1.init(b,w),b._zod.check=($)=>{if(w.pattern.lastIndex=0,w.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:"regex",input:$.value,pattern:w.pattern.toString(),inst:b,continue:!w.abort})}}),gQ=U("$ZodCheckLowerCase",(b,w)=>{w.pattern??(w.pattern=kQ),K1.init(b,w)}),mQ=U("$ZodCheckUpperCase",(b,w)=>{w.pattern??(w.pattern=CQ),K1.init(b,w)}),iQ=U("$ZodCheckIncludes",(b,w)=>{Hb.init(b,w);let $=bw(w.includes),W=new RegExp(typeof w.position==="number"?`^.{${w.position}}${$}`:$);w.pattern=W,b._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(W)}),b._zod.check=(Q)=>{if(Q.value.includes(w.includes,w.position))return;Q.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:w.includes,input:Q.value,inst:b,continue:!w.abort})}}),lQ=U("$ZodCheckStartsWith",(b,w)=>{Hb.init(b,w);let $=new RegExp(`^${bw(w.prefix)}.*`);w.pattern??(w.pattern=$),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),b._zod.check=(W)=>{if(W.value.startsWith(w.prefix))return;W.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:w.prefix,input:W.value,inst:b,continue:!w.abort})}}),pQ=U("$ZodCheckEndsWith",(b,w)=>{Hb.init(b,w);let $=new RegExp(`.*${bw(w.suffix)}$`);w.pattern??(w.pattern=$),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),b._zod.check=(W)=>{if(W.value.endsWith(w.suffix))return;W.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:w.suffix,input:W.value,inst:b,continue:!w.abort})}});var oQ=U("$ZodCheckOverwrite",(b,w)=>{Hb.init(b,w),b._zod.check=($)=>{$.value=w.tx($.value)}});class Y4{constructor(b=[]){if(this.content=[],this.indent=0,this)this.args=b}indented(b){this.indent+=1,b(this),this.indent-=1}write(b){if(typeof b==="function"){b(this,{execution:"sync"}),b(this,{execution:"async"});return}let $=b.split(`
10
10
  `).filter((G)=>G),W=Math.min(...$.map((G)=>G.length-G.trimStart().length)),Q=$.map((G)=>G.slice(W)).map((G)=>" ".repeat(this.indent*2)+G);for(let G of Q)this.content.push(G)}compile(){let b=Function,w=this?.args,W=[...(this?.content??[""]).map((Q)=>` ${Q}`)];return new b(...w,W.join(`
11
- `))}}var tQ={major:4,minor:1,patch:12};var e=U("$ZodType",(b,w)=>{var $;b??(b={}),b._zod.def=w,b._zod.bag=b._zod.bag||{},b._zod.version=tQ;let W=[...b._zod.def.checks??[]];if(b._zod.traits.has("$ZodCheck"))W.unshift(b);for(let Q of W)for(let G of Q._zod.onattach)G(b);if(W.length===0)($=b._zod).deferred??($.deferred=[]),b._zod.deferred?.push(()=>{b._zod.run=b._zod.parse});else{let Q=(X,Y,H)=>{let J=Uw(X),D;for(let z of Y){if(z._zod.def.when){if(!z._zod.def.when(X))continue}else if(J)continue;let O=X.issues.length,q=z._zod.check(X);if(q instanceof Promise&&H?.async===!1)throw new ab;if(D||q instanceof Promise)D=(D??Promise.resolve()).then(async()=>{if(await q,X.issues.length===O)return;if(!J)J=Uw(X,O)});else{if(X.issues.length===O)continue;if(!J)J=Uw(X,O)}}if(D)return D.then(()=>{return X});return X},G=(X,Y,H)=>{if(Uw(X))return X.aborted=!0,X;let J=Q(Y,W,H);if(J instanceof Promise){if(H.async===!1)throw new ab;return J.then((D)=>b._zod.parse(D,H))}return b._zod.parse(J,H)};b._zod.run=(X,Y)=>{if(Y.skipChecks)return b._zod.parse(X,Y);if(Y.direction==="backward"){let J=b._zod.parse({value:X.value,issues:[]},{...Y,skipChecks:!0});if(J instanceof Promise)return J.then((D)=>{return G(D,X,Y)});return G(J,X,Y)}let H=b._zod.parse(X,Y);if(H instanceof Promise){if(Y.async===!1)throw new ab;return H.then((J)=>Q(J,W,Y))}return Q(H,W,Y)}}b["~standard"]={validate:(Q)=>{try{let G=F1(b,Q);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return P0(b,Q).then((X)=>X.success?{value:X.data}:{issues:X.error?.issues})}},vendor:"zod",version:1}}),I0=U("$ZodString",(b,w)=>{e.init(b,w),b._zod.pattern=[...b?._zod.bag?.patterns??[]].pop()??EQ(b._zod.bag),b._zod.parse=($,W)=>{if(w.coerce)try{$.value=String($.value)}catch(Q){}if(typeof $.value==="string")return $;return $.issues.push({expected:"string",code:"invalid_type",input:$.value,inst:b}),$}}),s=U("$ZodStringFormat",(b,w)=>{P1.init(b,w),I0.init(b,w)}),Q9=U("$ZodGUID",(b,w)=>{w.pattern??(w.pattern=OQ),s.init(b,w)}),G9=U("$ZodUUID",(b,w)=>{if(w.version){let W={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[w.version];if(W===void 0)throw Error(`Invalid UUID version: "${w.version}"`);w.pattern??(w.pattern=Q4(W))}else w.pattern??(w.pattern=Q4());s.init(b,w)}),X9=U("$ZodEmail",(b,w)=>{w.pattern??(w.pattern=qQ),s.init(b,w)}),Y9=U("$ZodURL",(b,w)=>{s.init(b,w),b._zod.check=($)=>{try{let W=$.value.trim(),Q=new URL(W);if(w.hostname){if(w.hostname.lastIndex=0,!w.hostname.test(Q.hostname))$.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:MQ.source,input:$.value,inst:b,continue:!w.abort})}if(w.protocol){if(w.protocol.lastIndex=0,!w.protocol.test(Q.protocol.endsWith(":")?Q.protocol.slice(0,-1):Q.protocol))$.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:w.protocol.source,input:$.value,inst:b,continue:!w.abort})}if(w.normalize)$.value=Q.href;else $.value=W;return}catch(W){$.issues.push({code:"invalid_format",format:"url",input:$.value,inst:b,continue:!w.abort})}}}),H9=U("$ZodEmoji",(b,w)=>{w.pattern??(w.pattern=LQ()),s.init(b,w)}),J9=U("$ZodNanoID",(b,w)=>{w.pattern??(w.pattern=zQ),s.init(b,w)}),D9=U("$ZodCUID",(b,w)=>{w.pattern??(w.pattern=XQ),s.init(b,w)}),z9=U("$ZodCUID2",(b,w)=>{w.pattern??(w.pattern=YQ),s.init(b,w)}),A9=U("$ZodULID",(b,w)=>{w.pattern??(w.pattern=HQ),s.init(b,w)}),O9=U("$ZodXID",(b,w)=>{w.pattern??(w.pattern=JQ),s.init(b,w)}),q9=U("$ZodKSUID",(b,w)=>{w.pattern??(w.pattern=DQ),s.init(b,w)}),L9=U("$ZodISODateTime",(b,w)=>{w.pattern??(w.pattern=TQ(w)),s.init(b,w)}),U9=U("$ZodISODate",(b,w)=>{w.pattern??(w.pattern=IQ),s.init(b,w)}),B9=U("$ZodISOTime",(b,w)=>{w.pattern??(w.pattern=NQ(w)),s.init(b,w)}),F9=U("$ZodISODuration",(b,w)=>{w.pattern??(w.pattern=AQ),s.init(b,w)}),K9=U("$ZodIPv4",(b,w)=>{w.pattern??(w.pattern=UQ),s.init(b,w),b._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv4"})}),P9=U("$ZodIPv6",(b,w)=>{w.pattern??(w.pattern=BQ),s.init(b,w),b._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv6"}),b._zod.check=($)=>{try{new URL(`http://[${$.value}]`)}catch{$.issues.push({code:"invalid_format",format:"ipv6",input:$.value,inst:b,continue:!w.abort})}}}),M9=U("$ZodCIDRv4",(b,w)=>{w.pattern??(w.pattern=FQ),s.init(b,w)}),Z9=U("$ZodCIDRv6",(b,w)=>{w.pattern??(w.pattern=KQ),s.init(b,w),b._zod.check=($)=>{let W=$.value.split("/");try{if(W.length!==2)throw Error();let[Q,G]=W;if(!G)throw Error();let X=Number(G);if(`${X}`!==G)throw Error();if(X<0||X>128)throw Error();new URL(`http://[${Q}]`)}catch{$.issues.push({code:"invalid_format",format:"cidrv6",input:$.value,inst:b,continue:!w.abort})}}});function j9(b){if(b==="")return!0;if(b.length%4!==0)return!1;try{return atob(b),!0}catch{return!1}}var I9=U("$ZodBase64",(b,w)=>{w.pattern??(w.pattern=PQ),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),b._zod.check=($)=>{if(j9($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:b,continue:!w.abort})}});function P7(b){if(!G4.test(b))return!1;let w=b.replace(/[-_]/g,(W)=>W==="-"?"+":"/"),$=w.padEnd(Math.ceil(w.length/4)*4,"=");return j9($)}var V9=U("$ZodBase64URL",(b,w)=>{w.pattern??(w.pattern=G4),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),b._zod.check=($)=>{if(P7($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:b,continue:!w.abort})}}),N9=U("$ZodE164",(b,w)=>{w.pattern??(w.pattern=ZQ),s.init(b,w)});function M7(b,w=null){try{let $=b.split(".");if($.length!==3)return!1;let[W]=$;if(!W)return!1;let Q=JSON.parse(atob(W));if("typ"in Q&&Q?.typ!=="JWT")return!1;if(!Q.alg)return!1;if(w&&(!("alg"in Q)||Q.alg!==w))return!1;return!0}catch{return!1}}var T9=U("$ZodJWT",(b,w)=>{s.init(b,w),b._zod.check=($)=>{if(M7($.value,w.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:b,continue:!w.abort})}});var D4=U("$ZodNumber",(b,w)=>{e.init(b,w),b._zod.pattern=b._zod.bag.pattern??SQ,b._zod.parse=($,W)=>{if(w.coerce)try{$.value=Number($.value)}catch(X){}let Q=$.value;if(typeof Q==="number"&&!Number.isNaN(Q)&&Number.isFinite(Q))return $;let G=typeof Q==="number"?Number.isNaN(Q)?"NaN":!Number.isFinite(Q)?"Infinity":void 0:void 0;return $.issues.push({expected:"number",code:"invalid_type",input:Q,inst:b,...G?{received:G}:{}}),$}}),E9=U("$ZodNumber",(b,w)=>{yQ.init(b,w),D4.init(b,w)}),_9=U("$ZodBoolean",(b,w)=>{e.init(b,w),b._zod.pattern=RQ,b._zod.parse=($,W)=>{if(w.coerce)try{$.value=Boolean($.value)}catch(G){}let Q=$.value;if(typeof Q==="boolean")return $;return $.issues.push({expected:"boolean",code:"invalid_type",input:Q,inst:b}),$}});var S9=U("$ZodNull",(b,w)=>{e.init(b,w),b._zod.pattern=kQ,b._zod.values=new Set([null]),b._zod.parse=($,W)=>{let Q=$.value;if(Q===null)return $;return $.issues.push({expected:"null",code:"invalid_type",input:Q,inst:b}),$}});var R9=U("$ZodUnknown",(b,w)=>{e.init(b,w),b._zod.parse=($)=>$}),k9=U("$ZodNever",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{return $.issues.push({expected:"never",code:"invalid_type",input:$.value,inst:b}),$}});function rQ(b,w,$){if(b.issues.length)w.issues.push(...ww($,b.issues));w.value[$]=b.value}var v9=U("$ZodArray",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Array.isArray(Q))return $.issues.push({expected:"array",code:"invalid_type",input:Q,inst:b}),$;$.value=Array(Q.length);let G=[];for(let X=0;X<Q.length;X++){let Y=Q[X],H=w.element._zod.run({value:Y,issues:[]},W);if(H instanceof Promise)G.push(H.then((J)=>rQ(J,$,X)));else rQ(H,$,X)}if(G.length)return Promise.all(G).then(()=>$);return $}});function j0(b,w,$,W){if(b.issues.length)w.issues.push(...ww($,b.issues));if(b.value===void 0){if($ in W)w.value[$]=void 0}else w.value[$]=b.value}function C9(b){let w=Object.keys(b.shape);for(let W of w)if(!b.shape?.[W]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${W}": expected a Zod schema`);let $=w4(b.shape);return{...b,keys:w,keySet:new Set(w),numKeys:w.length,optionalKeys:new Set($)}}function x9(b,w,$,W,Q,G){let X=[],Y=Q.keySet,H=Q.catchall._zod,J=H.def.type;for(let D of Object.keys(w)){if(Y.has(D))continue;if(J==="never"){X.push(D);continue}let z=H.run({value:w[D],issues:[]},W);if(z instanceof Promise)b.push(z.then((O)=>j0(O,$,D,w)));else j0(z,$,D,w)}if(X.length)$.issues.push({code:"unrecognized_keys",keys:X,input:w,inst:G});if(!b.length)return $;return Promise.all(b).then(()=>{return $})}var Z7=U("$ZodObject",(b,w)=>{if(e.init(b,w),!Object.getOwnPropertyDescriptor(w,"shape")?.get){let Y=w.shape;Object.defineProperty(w,"shape",{get:()=>{let H={...Y};return Object.defineProperty(w,"shape",{value:H}),H}})}let W=fw(()=>C9(w));o(b._zod,"propValues",()=>{let Y=w.shape,H={};for(let J in Y){let D=Y[J]._zod;if(D.values){H[J]??(H[J]=new Set);for(let z of D.values)H[J].add(z)}}return H});let Q=_w,G=w.catchall,X;b._zod.parse=(Y,H)=>{X??(X=W.value);let J=Y.value;if(!Q(J))return Y.issues.push({expected:"object",code:"invalid_type",input:J,inst:b}),Y;Y.value={};let D=[],z=X.shape;for(let O of X.keys){let B=z[O]._zod.run({value:J[O],issues:[]},H);if(B instanceof Promise)D.push(B.then((K)=>j0(K,Y,O,J)));else j0(B,Y,O,J)}if(!G)return D.length?Promise.all(D).then(()=>Y):Y;return x9(D,J,Y,H,W.value,b)}}),u9=U("$ZodObjectJIT",(b,w)=>{Z7.init(b,w);let $=b._zod.parse,W=fw(()=>C9(w)),Q=(O)=>{let q=new H4(["shape","payload","ctx"]),B=W.value,K=(S)=>{let h=q0(S);return`shape[${h}]._zod.run({ value: input[${h}], issues: [] }, ctx)`};q.write("const input = payload.value;");let Z=Object.create(null),M=0;for(let S of B.keys)Z[S]=`key_${M++}`;q.write("const newResult = {};");for(let S of B.keys){let h=Z[S],R=q0(S);q.write(`const ${h} = ${K(S)};`),q.write(`
11
+ `))}}var tQ={major:4,minor:1,patch:12};var e=U("$ZodType",(b,w)=>{var $;b??(b={}),b._zod.def=w,b._zod.bag=b._zod.bag||{},b._zod.version=tQ;let W=[...b._zod.def.checks??[]];if(b._zod.traits.has("$ZodCheck"))W.unshift(b);for(let Q of W)for(let G of Q._zod.onattach)G(b);if(W.length===0)($=b._zod).deferred??($.deferred=[]),b._zod.deferred?.push(()=>{b._zod.run=b._zod.parse});else{let Q=(D,X,Y)=>{let H=Uw(D),J;for(let z of X){if(z._zod.def.when){if(!z._zod.def.when(D))continue}else if(H)continue;let O=D.issues.length,q=z._zod.check(D);if(q instanceof Promise&&Y?.async===!1)throw new ab;if(J||q instanceof Promise)J=(J??Promise.resolve()).then(async()=>{if(await q,D.issues.length===O)return;if(!H)H=Uw(D,O)});else{if(D.issues.length===O)continue;if(!H)H=Uw(D,O)}}if(J)return J.then(()=>{return D});return D},G=(D,X,Y)=>{if(Uw(D))return D.aborted=!0,D;let H=Q(X,W,Y);if(H instanceof Promise){if(Y.async===!1)throw new ab;return H.then((J)=>b._zod.parse(J,Y))}return b._zod.parse(H,Y)};b._zod.run=(D,X)=>{if(X.skipChecks)return b._zod.parse(D,X);if(X.direction==="backward"){let H=b._zod.parse({value:D.value,issues:[]},{...X,skipChecks:!0});if(H instanceof Promise)return H.then((J)=>{return G(J,D,X)});return G(H,D,X)}let Y=b._zod.parse(D,X);if(Y instanceof Promise){if(X.async===!1)throw new ab;return Y.then((H)=>Q(H,W,X))}return Q(Y,W,X)}}b["~standard"]={validate:(Q)=>{try{let G=P1(b,Q);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return K0(b,Q).then((D)=>D.success?{value:D.data}:{issues:D.error?.issues})}},vendor:"zod",version:1}}),j0=U("$ZodString",(b,w)=>{e.init(b,w),b._zod.pattern=[...b?._zod.bag?.patterns??[]].pop()??EQ(b._zod.bag),b._zod.parse=($,W)=>{if(w.coerce)try{$.value=String($.value)}catch(Q){}if(typeof $.value==="string")return $;return $.issues.push({expected:"string",code:"invalid_type",input:$.value,inst:b}),$}}),s=U("$ZodStringFormat",(b,w)=>{K1.init(b,w),j0.init(b,w)}),Q9=U("$ZodGUID",(b,w)=>{w.pattern??(w.pattern=OQ),s.init(b,w)}),G9=U("$ZodUUID",(b,w)=>{if(w.version){let W={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[w.version];if(W===void 0)throw Error(`Invalid UUID version: "${w.version}"`);w.pattern??(w.pattern=Q4(W))}else w.pattern??(w.pattern=Q4());s.init(b,w)}),D9=U("$ZodEmail",(b,w)=>{w.pattern??(w.pattern=qQ),s.init(b,w)}),X9=U("$ZodURL",(b,w)=>{s.init(b,w),b._zod.check=($)=>{try{let W=$.value.trim(),Q=new URL(W);if(w.hostname){if(w.hostname.lastIndex=0,!w.hostname.test(Q.hostname))$.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:MQ.source,input:$.value,inst:b,continue:!w.abort})}if(w.protocol){if(w.protocol.lastIndex=0,!w.protocol.test(Q.protocol.endsWith(":")?Q.protocol.slice(0,-1):Q.protocol))$.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:w.protocol.source,input:$.value,inst:b,continue:!w.abort})}if(w.normalize)$.value=Q.href;else $.value=W;return}catch(W){$.issues.push({code:"invalid_format",format:"url",input:$.value,inst:b,continue:!w.abort})}}}),Y9=U("$ZodEmoji",(b,w)=>{w.pattern??(w.pattern=LQ()),s.init(b,w)}),H9=U("$ZodNanoID",(b,w)=>{w.pattern??(w.pattern=zQ),s.init(b,w)}),J9=U("$ZodCUID",(b,w)=>{w.pattern??(w.pattern=DQ),s.init(b,w)}),z9=U("$ZodCUID2",(b,w)=>{w.pattern??(w.pattern=XQ),s.init(b,w)}),A9=U("$ZodULID",(b,w)=>{w.pattern??(w.pattern=YQ),s.init(b,w)}),O9=U("$ZodXID",(b,w)=>{w.pattern??(w.pattern=HQ),s.init(b,w)}),q9=U("$ZodKSUID",(b,w)=>{w.pattern??(w.pattern=JQ),s.init(b,w)}),L9=U("$ZodISODateTime",(b,w)=>{w.pattern??(w.pattern=TQ(w)),s.init(b,w)}),U9=U("$ZodISODate",(b,w)=>{w.pattern??(w.pattern=jQ),s.init(b,w)}),B9=U("$ZodISOTime",(b,w)=>{w.pattern??(w.pattern=NQ(w)),s.init(b,w)}),P9=U("$ZodISODuration",(b,w)=>{w.pattern??(w.pattern=AQ),s.init(b,w)}),F9=U("$ZodIPv4",(b,w)=>{w.pattern??(w.pattern=UQ),s.init(b,w),b._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv4"})}),K9=U("$ZodIPv6",(b,w)=>{w.pattern??(w.pattern=BQ),s.init(b,w),b._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv6"}),b._zod.check=($)=>{try{new URL(`http://[${$.value}]`)}catch{$.issues.push({code:"invalid_format",format:"ipv6",input:$.value,inst:b,continue:!w.abort})}}}),M9=U("$ZodCIDRv4",(b,w)=>{w.pattern??(w.pattern=PQ),s.init(b,w)}),I9=U("$ZodCIDRv6",(b,w)=>{w.pattern??(w.pattern=FQ),s.init(b,w),b._zod.check=($)=>{let W=$.value.split("/");try{if(W.length!==2)throw Error();let[Q,G]=W;if(!G)throw Error();let D=Number(G);if(`${D}`!==G)throw Error();if(D<0||D>128)throw Error();new URL(`http://[${Q}]`)}catch{$.issues.push({code:"invalid_format",format:"cidrv6",input:$.value,inst:b,continue:!w.abort})}}});function Z9(b){if(b==="")return!0;if(b.length%4!==0)return!1;try{return atob(b),!0}catch{return!1}}var j9=U("$ZodBase64",(b,w)=>{w.pattern??(w.pattern=KQ),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),b._zod.check=($)=>{if(Z9($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:b,continue:!w.abort})}});function VA(b){if(!G4.test(b))return!1;let w=b.replace(/[-_]/g,(W)=>W==="-"?"+":"/"),$=w.padEnd(Math.ceil(w.length/4)*4,"=");return Z9($)}var V9=U("$ZodBase64URL",(b,w)=>{w.pattern??(w.pattern=G4),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),b._zod.check=($)=>{if(VA($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:b,continue:!w.abort})}}),N9=U("$ZodE164",(b,w)=>{w.pattern??(w.pattern=IQ),s.init(b,w)});function NA(b,w=null){try{let $=b.split(".");if($.length!==3)return!1;let[W]=$;if(!W)return!1;let Q=JSON.parse(atob(W));if("typ"in Q&&Q?.typ!=="JWT")return!1;if(!Q.alg)return!1;if(w&&(!("alg"in Q)||Q.alg!==w))return!1;return!0}catch{return!1}}var T9=U("$ZodJWT",(b,w)=>{s.init(b,w),b._zod.check=($)=>{if(NA($.value,w.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:b,continue:!w.abort})}});var J4=U("$ZodNumber",(b,w)=>{e.init(b,w),b._zod.pattern=b._zod.bag.pattern??SQ,b._zod.parse=($,W)=>{if(w.coerce)try{$.value=Number($.value)}catch(D){}let Q=$.value;if(typeof Q==="number"&&!Number.isNaN(Q)&&Number.isFinite(Q))return $;let G=typeof Q==="number"?Number.isNaN(Q)?"NaN":!Number.isFinite(Q)?"Infinity":void 0:void 0;return $.issues.push({expected:"number",code:"invalid_type",input:Q,inst:b,...G?{received:G}:{}}),$}}),E9=U("$ZodNumber",(b,w)=>{yQ.init(b,w),J4.init(b,w)}),_9=U("$ZodBoolean",(b,w)=>{e.init(b,w),b._zod.pattern=RQ,b._zod.parse=($,W)=>{if(w.coerce)try{$.value=Boolean($.value)}catch(G){}let Q=$.value;if(typeof Q==="boolean")return $;return $.issues.push({expected:"boolean",code:"invalid_type",input:Q,inst:b}),$}});var S9=U("$ZodNull",(b,w)=>{e.init(b,w),b._zod.pattern=vQ,b._zod.values=new Set([null]),b._zod.parse=($,W)=>{let Q=$.value;if(Q===null)return $;return $.issues.push({expected:"null",code:"invalid_type",input:Q,inst:b}),$}});var R9=U("$ZodUnknown",(b,w)=>{e.init(b,w),b._zod.parse=($)=>$}),v9=U("$ZodNever",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{return $.issues.push({expected:"never",code:"invalid_type",input:$.value,inst:b}),$}});function rQ(b,w,$){if(b.issues.length)w.issues.push(...ww($,b.issues));w.value[$]=b.value}var k9=U("$ZodArray",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Array.isArray(Q))return $.issues.push({expected:"array",code:"invalid_type",input:Q,inst:b}),$;$.value=Array(Q.length);let G=[];for(let D=0;D<Q.length;D++){let X=Q[D],Y=w.element._zod.run({value:X,issues:[]},W);if(Y instanceof Promise)G.push(Y.then((H)=>rQ(H,$,D)));else rQ(Y,$,D)}if(G.length)return Promise.all(G).then(()=>$);return $}});function Z0(b,w,$,W){if(b.issues.length)w.issues.push(...ww($,b.issues));if(b.value===void 0){if($ in W)w.value[$]=void 0}else w.value[$]=b.value}function C9(b){let w=Object.keys(b.shape);for(let W of w)if(!b.shape?.[W]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${W}": expected a Zod schema`);let $=w4(b.shape);return{...b,keys:w,keySet:new Set(w),numKeys:w.length,optionalKeys:new Set($)}}function u9(b,w,$,W,Q,G){let D=[],X=Q.keySet,Y=Q.catchall._zod,H=Y.def.type;for(let J of Object.keys(w)){if(X.has(J))continue;if(H==="never"){D.push(J);continue}let z=Y.run({value:w[J],issues:[]},W);if(z instanceof Promise)b.push(z.then((O)=>Z0(O,$,J,w)));else Z0(z,$,J,w)}if(D.length)$.issues.push({code:"unrecognized_keys",keys:D,input:w,inst:G});if(!b.length)return $;return Promise.all(b).then(()=>{return $})}var TA=U("$ZodObject",(b,w)=>{if(e.init(b,w),!Object.getOwnPropertyDescriptor(w,"shape")?.get){let X=w.shape;Object.defineProperty(w,"shape",{get:()=>{let Y={...X};return Object.defineProperty(w,"shape",{value:Y}),Y}})}let W=fw(()=>C9(w));d(b._zod,"propValues",()=>{let X=w.shape,Y={};for(let H in X){let J=X[H]._zod;if(J.values){Y[H]??(Y[H]=new Set);for(let z of J.values)Y[H].add(z)}}return Y});let Q=_w,G=w.catchall,D;b._zod.parse=(X,Y)=>{D??(D=W.value);let H=X.value;if(!Q(H))return X.issues.push({expected:"object",code:"invalid_type",input:H,inst:b}),X;X.value={};let J=[],z=D.shape;for(let O of D.keys){let B=z[O]._zod.run({value:H[O],issues:[]},Y);if(B instanceof Promise)J.push(B.then((K)=>Z0(K,X,O,H)));else Z0(B,X,O,H)}if(!G)return J.length?Promise.all(J).then(()=>X):X;return u9(J,H,X,Y,W.value,b)}}),x9=U("$ZodObjectJIT",(b,w)=>{TA.init(b,w);let $=b._zod.parse,W=fw(()=>C9(w)),Q=(O)=>{let q=new Y4(["shape","payload","ctx"]),B=W.value,K=(S)=>{let h=q0(S);return`shape[${h}]._zod.run({ value: input[${h}], issues: [] }, ctx)`};q.write("const input = payload.value;");let I=Object.create(null),M=0;for(let S of B.keys)I[S]=`key_${M++}`;q.write("const newResult = {};");for(let S of B.keys){let h=I[S],R=q0(S);q.write(`const ${h} = ${K(S)};`),q.write(`
12
12
  if (${h}.issues.length) {
13
13
  payload.issues = payload.issues.concat(${h}.issues.map(iss => ({
14
14
  ...iss,
@@ -25,7 +25,7 @@ var Rz=Object.create;var{getPrototypeOf:kz,defineProperty:d$,getOwnPropertyNames
25
25
  newResult[${R}] = ${h}.value;
26
26
  }
27
27
 
28
- `)}q.write("payload.value = newResult;"),q.write("return payload;");let k=q.compile();return(S,h)=>k(O,S,h)},G,X=_w,Y=!A0.jitless,J=Y&&a$.value,D=w.catchall,z;b._zod.parse=(O,q)=>{z??(z=W.value);let B=O.value;if(!X(B))return O.issues.push({expected:"object",code:"invalid_type",input:B,inst:b}),O;if(Y&&J&&q?.async===!1&&q.jitless!==!0){if(!G)G=Q(w.shape);if(O=G(O,q),!D)return O;return x9([],B,O,q,z,b)}return $(O,q)}});function eQ(b,w,$,W){for(let G of b)if(G.issues.length===0)return w.value=G.value,w;let Q=b.filter((G)=>!Uw(G));if(Q.length===1)return w.value=Q[0].value,Q[0];return w.issues.push({code:"invalid_union",input:w.value,inst:$,errors:b.map((G)=>G.issues.map((X)=>ub(X,W,Sb())))}),w}var z4=U("$ZodUnion",(b,w)=>{e.init(b,w),o(b._zod,"optin",()=>w.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),o(b._zod,"optout",()=>w.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),o(b._zod,"values",()=>{if(w.options.every((Q)=>Q._zod.values))return new Set(w.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),o(b._zod,"pattern",()=>{if(w.options.every((Q)=>Q._zod.pattern)){let Q=w.options.map((G)=>G._zod.pattern);return new RegExp(`^(${Q.map((G)=>L1(G.source)).join("|")})$`)}return});let $=w.options.length===1,W=w.options[0]._zod.run;b._zod.parse=(Q,G)=>{if($)return W(Q,G);let X=!1,Y=[];for(let H of w.options){let J=H._zod.run({value:Q.value,issues:[]},G);if(J instanceof Promise)Y.push(J),X=!0;else{if(J.issues.length===0)return J;Y.push(J)}}if(!X)return eQ(Y,Q,b,G);return Promise.all(Y).then((H)=>{return eQ(H,Q,b,G)})}}),y9=U("$ZodDiscriminatedUnion",(b,w)=>{z4.init(b,w);let $=b._zod.parse;o(b._zod,"propValues",()=>{let Q={};for(let G of w.options){let X=G._zod.propValues;if(!X||Object.keys(X).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(G)}"`);for(let[Y,H]of Object.entries(X)){if(!Q[Y])Q[Y]=new Set;for(let J of H)Q[Y].add(J)}}return Q});let W=fw(()=>{let Q=w.options,G=new Map;for(let X of Q){let Y=X._zod.propValues?.[w.discriminator];if(!Y||Y.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(X)}"`);for(let H of Y){if(G.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);G.set(H,X)}}return G});b._zod.parse=(Q,G)=>{let X=Q.value;if(!_w(X))return Q.issues.push({code:"invalid_type",expected:"object",input:X,inst:b}),Q;let Y=W.value.get(X?.[w.discriminator]);if(Y)return Y._zod.run(Q,G);if(w.unionFallback)return $(Q,G);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:w.discriminator,input:X,path:[w.discriminator],inst:b}),Q}}),h9=U("$ZodIntersection",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value,G=w.left._zod.run({value:Q,issues:[]},W),X=w.right._zod.run({value:Q,issues:[]},W);if(G instanceof Promise||X instanceof Promise)return Promise.all([G,X]).then(([H,J])=>{return sQ($,H,J)});return sQ($,G,X)}});function J4(b,w){if(b===w)return{valid:!0,data:b};if(b instanceof Date&&w instanceof Date&&+b===+w)return{valid:!0,data:b};if(Lw(b)&&Lw(w)){let $=Object.keys(w),W=Object.keys(b).filter((G)=>$.indexOf(G)!==-1),Q={...b,...w};for(let G of W){let X=J4(b[G],w[G]);if(!X.valid)return{valid:!1,mergeErrorPath:[G,...X.mergeErrorPath]};Q[G]=X.data}return{valid:!0,data:Q}}if(Array.isArray(b)&&Array.isArray(w)){if(b.length!==w.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let W=0;W<b.length;W++){let Q=b[W],G=w[W],X=J4(Q,G);if(!X.valid)return{valid:!1,mergeErrorPath:[W,...X.mergeErrorPath]};$.push(X.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function sQ(b,w,$){if(w.issues.length)b.issues.push(...w.issues);if($.issues.length)b.issues.push(...$.issues);if(Uw(b))return b;let W=J4(w.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return b.value=W.data,b}var f9=U("$ZodRecord",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Lw(Q))return $.issues.push({expected:"record",code:"invalid_type",input:Q,inst:b}),$;let G=[];if(w.keyType._zod.values){let X=w.keyType._zod.values;$.value={};for(let H of X)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let J=w.valueType._zod.run({value:Q[H],issues:[]},W);if(J instanceof Promise)G.push(J.then((D)=>{if(D.issues.length)$.issues.push(...ww(H,D.issues));$.value[H]=D.value}));else{if(J.issues.length)$.issues.push(...ww(H,J.issues));$.value[H]=J.value}}let Y;for(let H in Q)if(!X.has(H))Y=Y??[],Y.push(H);if(Y&&Y.length>0)$.issues.push({code:"unrecognized_keys",input:Q,inst:b,keys:Y})}else{$.value={};for(let X of Reflect.ownKeys(Q)){if(X==="__proto__")continue;let Y=w.keyType._zod.run({value:X,issues:[]},W);if(Y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(Y.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:Y.issues.map((J)=>ub(J,W,Sb())),input:X,path:[X],inst:b}),$.value[Y.value]=Y.value;continue}let H=w.valueType._zod.run({value:Q[X],issues:[]},W);if(H instanceof Promise)G.push(H.then((J)=>{if(J.issues.length)$.issues.push(...ww(X,J.issues));$.value[Y.value]=J.value}));else{if(H.issues.length)$.issues.push(...ww(X,H.issues));$.value[Y.value]=H.value}}}if(G.length)return Promise.all(G).then(()=>$);return $}});var c9=U("$ZodEnum",(b,w)=>{e.init(b,w);let $=e$(w.entries),W=new Set($);b._zod.values=W,b._zod.pattern=new RegExp(`^(${$.filter((Q)=>b4.has(typeof Q)).map((Q)=>typeof Q==="string"?bw(Q):Q.toString()).join("|")})$`),b._zod.parse=(Q,G)=>{let X=Q.value;if(W.has(X))return Q;return Q.issues.push({code:"invalid_value",values:$,input:X,inst:b}),Q}}),g9=U("$ZodLiteral",(b,w)=>{if(e.init(b,w),w.values.length===0)throw Error("Cannot create literal schema with no valid values");b._zod.values=new Set(w.values),b._zod.pattern=new RegExp(`^(${w.values.map(($)=>typeof $==="string"?bw($):$?bw($.toString()):String($)).join("|")})$`),b._zod.parse=($,W)=>{let Q=$.value;if(b._zod.values.has(Q))return $;return $.issues.push({code:"invalid_value",values:w.values,input:Q,inst:b}),$}});var m9=U("$ZodTransform",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);let Q=w.transform($.value,$);if(W.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((X)=>{return $.value=X,$});if(Q instanceof Promise)throw new ab;return $.value=Q,$}});function aQ(b,w){if(b.issues.length&&w===void 0)return{issues:[],value:void 0};return b}var n9=U("$ZodOptional",(b,w)=>{e.init(b,w),b._zod.optin="optional",b._zod.optout="optional",o(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),o(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${L1($.source)})?$`):void 0}),b._zod.parse=($,W)=>{if(w.innerType._zod.optin==="optional"){let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>aQ(G,$.value));return aQ(Q,$.value)}if($.value===void 0)return $;return w.innerType._zod.run($,W)}}),l9=U("$ZodNullable",(b,w)=>{e.init(b,w),o(b._zod,"optin",()=>w.innerType._zod.optin),o(b._zod,"optout",()=>w.innerType._zod.optout),o(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${L1($.source)}|null)$`):void 0}),o(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),b._zod.parse=($,W)=>{if($.value===null)return $;return w.innerType._zod.run($,W)}}),i9=U("$ZodDefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",o(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)return $.value=w.defaultValue,$;let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>b9(G,w));return b9(Q,w)}});function b9(b,w){if(b.value===void 0)b.value=w.defaultValue;return b}var p9=U("$ZodPrefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",o(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)$.value=w.defaultValue;return w.innerType._zod.run($,W)}}),o9=U("$ZodNonOptional",(b,w)=>{e.init(b,w),o(b._zod,"values",()=>{let $=w.innerType._zod.values;return $?new Set([...$].filter((W)=>W!==void 0)):void 0}),b._zod.parse=($,W)=>{let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>w9(G,b));return w9(Q,b)}});function w9(b,w){if(!b.issues.length&&b.value===void 0)b.issues.push({code:"invalid_type",expected:"nonoptional",input:b.value,inst:w});return b}var d9=U("$ZodCatch",(b,w)=>{e.init(b,w),o(b._zod,"optin",()=>w.innerType._zod.optin),o(b._zod,"optout",()=>w.innerType._zod.optout),o(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>{if($.value=G.value,G.issues.length)$.value=w.catchValue({...$,error:{issues:G.issues.map((X)=>ub(X,W,Sb()))},input:$.value}),$.issues=[];return $});if($.value=Q.value,Q.issues.length)$.value=w.catchValue({...$,error:{issues:Q.issues.map((G)=>ub(G,W,Sb()))},input:$.value}),$.issues=[];return $}});var t9=U("$ZodPipe",(b,w)=>{e.init(b,w),o(b._zod,"values",()=>w.in._zod.values),o(b._zod,"optin",()=>w.in._zod.optin),o(b._zod,"optout",()=>w.out._zod.optout),o(b._zod,"propValues",()=>w.in._zod.propValues),b._zod.parse=($,W)=>{if(W.direction==="backward"){let G=w.out._zod.run($,W);if(G instanceof Promise)return G.then((X)=>Z0(X,w.in,W));return Z0(G,w.in,W)}let Q=w.in._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>Z0(G,w.out,W));return Z0(Q,w.out,W)}});function Z0(b,w,$){if(b.issues.length)return b.aborted=!0,b;return w._zod.run({value:b.value,issues:b.issues},$)}var r9=U("$ZodReadonly",(b,w)=>{e.init(b,w),o(b._zod,"propValues",()=>w.innerType._zod.propValues),o(b._zod,"values",()=>w.innerType._zod.values),o(b._zod,"optin",()=>w.innerType._zod.optin),o(b._zod,"optout",()=>w.innerType._zod.optout),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then($9);return $9(Q)}});function $9(b){return b.value=Object.freeze(b.value),b}var e9=U("$ZodCustom",(b,w)=>{Jb.init(b,w),e.init(b,w),b._zod.parse=($,W)=>{return $},b._zod.check=($)=>{let W=$.value,Q=w.fn(W);if(Q instanceof Promise)return Q.then((G)=>W9(G,$,W,b));W9(Q,$,W,b);return}});function W9(b,w,$,W){if(!b){let Q={code:"custom",input:$,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)Q.params=W._zod.def.params;w.issues.push(cw(Q))}}var j7=(b)=>{let w=typeof b;switch(w){case"number":return Number.isNaN(b)?"NaN":"number";case"object":{if(Array.isArray(b))return"array";if(b===null)return"null";if(Object.getPrototypeOf(b)!==Object.prototype&&b.constructor)return b.constructor.name}}return w},I7=()=>{let b={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 w(W){return b[W]??null}let $={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(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${j7(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${U0(W.values[0])}`;return`Invalid option: expected one of ${O0(W.values,"|")}`;case"too_big":{let Q=W.inclusive?"<=":"<",G=w(W.origin);if(G)return`Too big: expected ${W.origin??"value"} to have ${Q}${W.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${Q}${W.maximum.toString()}`}case"too_small":{let Q=W.inclusive?">=":">",G=w(W.origin);if(G)return`Too small: expected ${W.origin} to have ${Q}${W.minimum.toString()} ${G.unit}`;return`Too small: expected ${W.origin} to be ${Q}${W.minimum.toString()}`}case"invalid_format":{let Q=W;if(Q.format==="starts_with")return`Invalid string: must start with "${Q.prefix}"`;if(Q.format==="ends_with")return`Invalid string: must end with "${Q.suffix}"`;if(Q.format==="includes")return`Invalid string: must include "${Q.includes}"`;if(Q.format==="regex")return`Invalid string: must match pattern ${Q.pattern}`;return`Invalid ${$[Q.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${O0(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function A4(){return{localeError:I7()}}var gM=Symbol("ZodOutput"),mM=Symbol("ZodInput");class s9{constructor(){this._map=new WeakMap,this._idmap=new Map}add(b,...w){let $=w[0];if(this._map.set(b,$),$&&typeof $==="object"&&"id"in $){if(this._idmap.has($.id))throw Error(`ID ${$.id} already exists in the registry`);this._idmap.set($.id,b)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(b){let w=this._map.get(b);if(w&&typeof w==="object"&&"id"in w)this._idmap.delete(w.id);return this._map.delete(b),this}get(b){let w=b._zod.parent;if(w){let $={...this.get(w)??{}};delete $.id;let W={...$,...this._map.get(b)};return Object.keys(W).length?W:void 0}return this._map.get(b)}has(b){return this._map.has(b)}}function V7(){return new s9}var M1=V7();function a9(b,w){return new b({type:"string",..._(w)})}function b8(b,w){return new b({type:"string",format:"email",check:"string_format",abort:!1,..._(w)})}function O4(b,w){return new b({type:"string",format:"guid",check:"string_format",abort:!1,..._(w)})}function w8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,..._(w)})}function $8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",..._(w)})}function W8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",..._(w)})}function Q8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",..._(w)})}function G8(b,w){return new b({type:"string",format:"url",check:"string_format",abort:!1,..._(w)})}function X8(b,w){return new b({type:"string",format:"emoji",check:"string_format",abort:!1,..._(w)})}function Y8(b,w){return new b({type:"string",format:"nanoid",check:"string_format",abort:!1,..._(w)})}function H8(b,w){return new b({type:"string",format:"cuid",check:"string_format",abort:!1,..._(w)})}function J8(b,w){return new b({type:"string",format:"cuid2",check:"string_format",abort:!1,..._(w)})}function D8(b,w){return new b({type:"string",format:"ulid",check:"string_format",abort:!1,..._(w)})}function z8(b,w){return new b({type:"string",format:"xid",check:"string_format",abort:!1,..._(w)})}function A8(b,w){return new b({type:"string",format:"ksuid",check:"string_format",abort:!1,..._(w)})}function O8(b,w){return new b({type:"string",format:"ipv4",check:"string_format",abort:!1,..._(w)})}function q8(b,w){return new b({type:"string",format:"ipv6",check:"string_format",abort:!1,..._(w)})}function L8(b,w){return new b({type:"string",format:"cidrv4",check:"string_format",abort:!1,..._(w)})}function U8(b,w){return new b({type:"string",format:"cidrv6",check:"string_format",abort:!1,..._(w)})}function B8(b,w){return new b({type:"string",format:"base64",check:"string_format",abort:!1,..._(w)})}function F8(b,w){return new b({type:"string",format:"base64url",check:"string_format",abort:!1,..._(w)})}function K8(b,w){return new b({type:"string",format:"e164",check:"string_format",abort:!1,..._(w)})}function P8(b,w){return new b({type:"string",format:"jwt",check:"string_format",abort:!1,..._(w)})}function M8(b,w){return new b({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,..._(w)})}function Z8(b,w){return new b({type:"string",format:"date",check:"string_format",..._(w)})}function j8(b,w){return new b({type:"string",format:"time",check:"string_format",precision:null,..._(w)})}function I8(b,w){return new b({type:"string",format:"duration",check:"string_format",..._(w)})}function V8(b,w){return new b({type:"number",checks:[],..._(w)})}function N8(b,w){return new b({type:"number",check:"number_format",abort:!1,format:"safeint",..._(w)})}function T8(b,w){return new b({type:"boolean",..._(w)})}function E8(b,w){return new b({type:"null",..._(w)})}function _8(b){return new b({type:"unknown"})}function S8(b,w){return new b({type:"never",..._(w)})}function V0(b,w){return new X4({check:"less_than",..._(w),value:b,inclusive:!1})}function Z1(b,w){return new X4({check:"less_than",..._(w),value:b,inclusive:!0})}function N0(b,w){return new Y4({check:"greater_than",..._(w),value:b,inclusive:!1})}function j1(b,w){return new Y4({check:"greater_than",..._(w),value:b,inclusive:!0})}function T0(b,w){return new uQ({check:"multiple_of",..._(w),value:b})}function E0(b,w){return new hQ({check:"max_length",..._(w),maximum:b})}function gw(b,w){return new fQ({check:"min_length",..._(w),minimum:b})}function _0(b,w){return new cQ({check:"length_equals",..._(w),length:b})}function q4(b,w){return new gQ({check:"string_format",format:"regex",..._(w),pattern:b})}function L4(b){return new mQ({check:"string_format",format:"lowercase",..._(b)})}function U4(b){return new nQ({check:"string_format",format:"uppercase",..._(b)})}function B4(b,w){return new lQ({check:"string_format",format:"includes",..._(w),includes:b})}function F4(b,w){return new iQ({check:"string_format",format:"starts_with",..._(w),prefix:b})}function K4(b,w){return new pQ({check:"string_format",format:"ends_with",..._(w),suffix:b})}function Sw(b){return new oQ({check:"overwrite",tx:b})}function P4(b){return Sw((w)=>w.normalize(b))}function M4(){return Sw((b)=>b.trim())}function Z4(){return Sw((b)=>b.toLowerCase())}function j4(){return Sw((b)=>b.toUpperCase())}function R8(b,w,$){return new b({type:"array",element:w,..._($)})}function k8(b,w,$){let W=_($);return W.abort??(W.abort=!0),new b({type:"custom",check:"custom",fn:w,...W})}function v8(b,w,$){return new b({type:"custom",check:"custom",fn:w,..._($)})}function C8(b){let w=N7(($)=>{return $.addIssue=(W)=>{if(typeof W==="string")$.issues.push(cw(W,$.value,w._zod.def));else{let Q=W;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=$.value),Q.inst??(Q.inst=w),Q.continue??(Q.continue=!w._zod.def.abort),$.issues.push(cw(Q))}},b($.value,$)});return w}function N7(b,w){let $=new Jb({check:"custom",..._(w)});return $._zod.check=b,$}function mw(b){return!!b._zod}function Bw(b,w){if(mw(b))return F1(b,w);return b.safeParse(w)}function S0(b){if(!b)return;let w;if(mw(b))w=b._zod?.def?.shape;else w=b.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function x8(b){if(mw(b)){let G=b._zod?.def;if(G){if(G.value!==void 0)return G.value;if(Array.isArray(G.values)&&G.values.length>0)return G.values[0]}}let $=b._def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}let W=b.value;if(W!==void 0)return W;return}var V1={};kW(V1,{time:()=>N4,duration:()=>T4,datetime:()=>I4,date:()=>V4,ZodISOTime:()=>h8,ZodISODuration:()=>f8,ZodISODateTime:()=>u8,ZodISODate:()=>y8});var u8=U("ZodISODateTime",(b,w)=>{L9.init(b,w),bb.init(b,w)});function I4(b){return M8(u8,b)}var y8=U("ZodISODate",(b,w)=>{U9.init(b,w),bb.init(b,w)});function V4(b){return Z8(y8,b)}var h8=U("ZodISOTime",(b,w)=>{B9.init(b,w),bb.init(b,w)});function N4(b){return j8(h8,b)}var f8=U("ZodISODuration",(b,w)=>{F9.init(b,w),bb.init(b,w)});function T4(b){return I8(f8,b)}var c8=(b,w)=>{B0.init(b,w),b.name="ZodError",Object.defineProperties(b,{format:{value:($)=>eW(b,$)},flatten:{value:($)=>rW(b,$)},addIssue:{value:($)=>{b.issues.push($),b.message=JSON.stringify(b.issues,hw,2)}},addIssues:{value:($)=>{b.issues.push(...$),b.message=JSON.stringify(b.issues,hw,2)}},isEmpty:{get(){return b.issues.length===0}}})},TZ=U("ZodError",c8),Tb=U("ZodError",c8,{Parent:Error});var g8=F0(Tb),m8=K0(Tb),n8=B1(Tb),l8=K1(Tb),i8=sW(Tb),p8=aW(Tb),o8=bQ(Tb),d8=wQ(Tb),t8=$Q(Tb),r8=WQ(Tb),e8=QQ(Tb),s8=GQ(Tb);var Qb=U("ZodType",(b,w)=>{return e.init(b,w),b.def=w,b.type=w.type,Object.defineProperty(b,"_def",{value:w}),b.check=(...$)=>{return b.clone(n.mergeDefs(w,{checks:[...w.checks??[],...$.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},b.clone=($,W)=>xb(b,$,W),b.brand=()=>b,b.register=($,W)=>{return $.add(b,W),b},b.parse=($,W)=>g8(b,$,W,{callee:b.parse}),b.safeParse=($,W)=>n8(b,$,W),b.parseAsync=async($,W)=>m8(b,$,W,{callee:b.parseAsync}),b.safeParseAsync=async($,W)=>l8(b,$,W),b.spa=b.safeParseAsync,b.encode=($,W)=>i8(b,$,W),b.decode=($,W)=>p8(b,$,W),b.encodeAsync=async($,W)=>o8(b,$,W),b.decodeAsync=async($,W)=>d8(b,$,W),b.safeEncode=($,W)=>t8(b,$,W),b.safeDecode=($,W)=>r8(b,$,W),b.safeEncodeAsync=async($,W)=>e8(b,$,W),b.safeDecodeAsync=async($,W)=>s8(b,$,W),b.refine=($,W)=>b.check(Z5($,W)),b.superRefine=($)=>b.check(j5($)),b.overwrite=($)=>b.check(Sw($)),b.optional=()=>Wb(b),b.nullable=()=>wG(b),b.nullish=()=>Wb(wG(b)),b.nonoptional=($)=>U5(b,$),b.array=()=>f(b),b.or=($)=>r([b,$]),b.and=($)=>k0(b,$),b.transform=($)=>_4(b,XG($)),b.default=($)=>O5(b,$),b.prefault=($)=>L5(b,$),b.catch=($)=>F5(b,$),b.pipe=($)=>_4(b,$),b.readonly=()=>M5(b),b.describe=($)=>{let W=b.clone();return M1.add(W,{description:$}),W},Object.defineProperty(b,"description",{get(){return M1.get(b)?.description},configurable:!0}),b.meta=(...$)=>{if($.length===0)return M1.get(b);let W=b.clone();return M1.add(W,$[0]),W},b.isOptional=()=>b.safeParse(void 0).success,b.isNullable=()=>b.safeParse(null).success,b}),$G=U("_ZodString",(b,w)=>{I0.init(b,w),Qb.init(b,w);let $=b._zod.bag;b.format=$.format??null,b.minLength=$.minimum??null,b.maxLength=$.maximum??null,b.regex=(...W)=>b.check(q4(...W)),b.includes=(...W)=>b.check(B4(...W)),b.startsWith=(...W)=>b.check(F4(...W)),b.endsWith=(...W)=>b.check(K4(...W)),b.min=(...W)=>b.check(gw(...W)),b.max=(...W)=>b.check(E0(...W)),b.length=(...W)=>b.check(_0(...W)),b.nonempty=(...W)=>b.check(gw(1,...W)),b.lowercase=(W)=>b.check(L4(W)),b.uppercase=(W)=>b.check(U4(W)),b.trim=()=>b.check(M4()),b.normalize=(...W)=>b.check(P4(...W)),b.toLowerCase=()=>b.check(Z4()),b.toUpperCase=()=>b.check(j4())}),x7=U("ZodString",(b,w)=>{I0.init(b,w),$G.init(b,w),b.email=($)=>b.check(b8(u7,$)),b.url=($)=>b.check(G8(y7,$)),b.jwt=($)=>b.check(P8(s7,$)),b.emoji=($)=>b.check(X8(h7,$)),b.guid=($)=>b.check(O4(a8,$)),b.uuid=($)=>b.check(w8(R0,$)),b.uuidv4=($)=>b.check($8(R0,$)),b.uuidv6=($)=>b.check(W8(R0,$)),b.uuidv7=($)=>b.check(Q8(R0,$)),b.nanoid=($)=>b.check(Y8(f7,$)),b.guid=($)=>b.check(O4(a8,$)),b.cuid=($)=>b.check(H8(c7,$)),b.cuid2=($)=>b.check(J8(g7,$)),b.ulid=($)=>b.check(D8(m7,$)),b.base64=($)=>b.check(B8(t7,$)),b.base64url=($)=>b.check(F8(r7,$)),b.xid=($)=>b.check(z8(n7,$)),b.ksuid=($)=>b.check(A8(l7,$)),b.ipv4=($)=>b.check(O8(i7,$)),b.ipv6=($)=>b.check(q8(p7,$)),b.cidrv4=($)=>b.check(L8(o7,$)),b.cidrv6=($)=>b.check(U8(d7,$)),b.e164=($)=>b.check(K8(e7,$)),b.datetime=($)=>b.check(I4($)),b.date=($)=>b.check(V4($)),b.time=($)=>b.check(N4($)),b.duration=($)=>b.check(T4($))});function L(b){return a9(x7,b)}var bb=U("ZodStringFormat",(b,w)=>{s.init(b,w),$G.init(b,w)}),u7=U("ZodEmail",(b,w)=>{X9.init(b,w),bb.init(b,w)});var a8=U("ZodGUID",(b,w)=>{Q9.init(b,w),bb.init(b,w)});var R0=U("ZodUUID",(b,w)=>{G9.init(b,w),bb.init(b,w)});var y7=U("ZodURL",(b,w)=>{Y9.init(b,w),bb.init(b,w)});var h7=U("ZodEmoji",(b,w)=>{H9.init(b,w),bb.init(b,w)});var f7=U("ZodNanoID",(b,w)=>{J9.init(b,w),bb.init(b,w)});var c7=U("ZodCUID",(b,w)=>{D9.init(b,w),bb.init(b,w)});var g7=U("ZodCUID2",(b,w)=>{z9.init(b,w),bb.init(b,w)});var m7=U("ZodULID",(b,w)=>{A9.init(b,w),bb.init(b,w)});var n7=U("ZodXID",(b,w)=>{O9.init(b,w),bb.init(b,w)});var l7=U("ZodKSUID",(b,w)=>{q9.init(b,w),bb.init(b,w)});var i7=U("ZodIPv4",(b,w)=>{K9.init(b,w),bb.init(b,w)});var p7=U("ZodIPv6",(b,w)=>{P9.init(b,w),bb.init(b,w)});var o7=U("ZodCIDRv4",(b,w)=>{M9.init(b,w),bb.init(b,w)});var d7=U("ZodCIDRv6",(b,w)=>{Z9.init(b,w),bb.init(b,w)});var t7=U("ZodBase64",(b,w)=>{I9.init(b,w),bb.init(b,w)});var r7=U("ZodBase64URL",(b,w)=>{V9.init(b,w),bb.init(b,w)});var e7=U("ZodE164",(b,w)=>{N9.init(b,w),bb.init(b,w)});var s7=U("ZodJWT",(b,w)=>{T9.init(b,w),bb.init(b,w)});var WG=U("ZodNumber",(b,w)=>{D4.init(b,w),Qb.init(b,w),b.gt=(W,Q)=>b.check(N0(W,Q)),b.gte=(W,Q)=>b.check(j1(W,Q)),b.min=(W,Q)=>b.check(j1(W,Q)),b.lt=(W,Q)=>b.check(V0(W,Q)),b.lte=(W,Q)=>b.check(Z1(W,Q)),b.max=(W,Q)=>b.check(Z1(W,Q)),b.int=(W)=>b.check(bG(W)),b.safe=(W)=>b.check(bG(W)),b.positive=(W)=>b.check(N0(0,W)),b.nonnegative=(W)=>b.check(j1(0,W)),b.negative=(W)=>b.check(V0(0,W)),b.nonpositive=(W)=>b.check(Z1(0,W)),b.multipleOf=(W,Q)=>b.check(T0(W,Q)),b.step=(W,Q)=>b.check(T0(W,Q)),b.finite=()=>b;let $=b._zod.bag;b.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,b.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,b.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),b.isFinite=!0,b.format=$.format??null});function i(b){return V8(WG,b)}var a7=U("ZodNumberFormat",(b,w)=>{E9.init(b,w),WG.init(b,w)});function bG(b){return N8(a7,b)}var b5=U("ZodBoolean",(b,w)=>{_9.init(b,w),Qb.init(b,w)});function Hb(b){return T8(b5,b)}var w5=U("ZodNull",(b,w)=>{S9.init(b,w),Qb.init(b,w)});function S4(b){return E8(w5,b)}var $5=U("ZodUnknown",(b,w)=>{R9.init(b,w),Qb.init(b,w)});function wb(){return _8($5)}var W5=U("ZodNever",(b,w)=>{k9.init(b,w),Qb.init(b,w)});function Q5(b){return S8(W5,b)}var G5=U("ZodArray",(b,w)=>{v9.init(b,w),Qb.init(b,w),b.element=w.element,b.min=($,W)=>b.check(gw($,W)),b.nonempty=($)=>b.check(gw(1,$)),b.max=($,W)=>b.check(E0($,W)),b.length=($,W)=>b.check(_0($,W)),b.unwrap=()=>b.element});function f(b,w){return R8(G5,b,w)}var QG=U("ZodObject",(b,w)=>{u9.init(b,w),Qb.init(b,w),n.defineLazy(b,"shape",()=>{return w.shape}),b.keyof=()=>Pb(Object.keys(b._zod.def.shape)),b.catchall=($)=>b.clone({...b._zod.def,catchall:$}),b.passthrough=()=>b.clone({...b._zod.def,catchall:wb()}),b.loose=()=>b.clone({...b._zod.def,catchall:wb()}),b.strict=()=>b.clone({...b._zod.def,catchall:Q5()}),b.strip=()=>b.clone({...b._zod.def,catchall:void 0}),b.extend=($)=>{return n.extend(b,$)},b.safeExtend=($)=>{return n.safeExtend(b,$)},b.merge=($)=>n.merge(b,$),b.pick=($)=>n.pick(b,$),b.omit=($)=>n.omit(b,$),b.partial=(...$)=>n.partial(YG,b,$[0]),b.required=(...$)=>n.required(HG,b,$[0])});function V(b,w){let $={type:"object",shape:b??{},...n.normalizeParams(w)};return new QG($)}function Ub(b,w){return new QG({type:"object",shape:b,catchall:wb(),...n.normalizeParams(w)})}var GG=U("ZodUnion",(b,w)=>{z4.init(b,w),Qb.init(b,w),b.options=w.options});function r(b,w){return new GG({type:"union",options:b,...n.normalizeParams(w)})}var X5=U("ZodDiscriminatedUnion",(b,w)=>{GG.init(b,w),y9.init(b,w)});function R4(b,w,$){return new X5({type:"union",options:w,discriminator:b,...n.normalizeParams($)})}var Y5=U("ZodIntersection",(b,w)=>{h9.init(b,w),Qb.init(b,w)});function k0(b,w){return new Y5({type:"intersection",left:b,right:w})}var H5=U("ZodRecord",(b,w)=>{f9.init(b,w),Qb.init(b,w),b.keyType=w.keyType,b.valueType=w.valueType});function $b(b,w,$){return new H5({type:"record",keyType:b,valueType:w,...n.normalizeParams($)})}var E4=U("ZodEnum",(b,w)=>{c9.init(b,w),Qb.init(b,w),b.enum=w.entries,b.options=Object.values(w.entries);let $=new Set(Object.keys(w.entries));b.extract=(W,Q)=>{let G={};for(let X of W)if($.has(X))G[X]=w.entries[X];else throw Error(`Key ${X} not found in enum`);return new E4({...w,checks:[],...n.normalizeParams(Q),entries:G})},b.exclude=(W,Q)=>{let G={...w.entries};for(let X of W)if($.has(X))delete G[X];else throw Error(`Key ${X} not found in enum`);return new E4({...w,checks:[],...n.normalizeParams(Q),entries:G})}});function Pb(b,w){let $=Array.isArray(b)?Object.fromEntries(b.map((W)=>[W,W])):b;return new E4({type:"enum",entries:$,...n.normalizeParams(w)})}var J5=U("ZodLiteral",(b,w)=>{g9.init(b,w),Qb.init(b,w),b.values=new Set(w.values),Object.defineProperty(b,"value",{get(){if(w.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return w.values[0]}})});function T(b,w){return new J5({type:"literal",values:Array.isArray(b)?b:[b],...n.normalizeParams(w)})}var D5=U("ZodTransform",(b,w)=>{m9.init(b,w),Qb.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);$.addIssue=(G)=>{if(typeof G==="string")$.issues.push(n.issue(G,$.value,w));else{let X=G;if(X.fatal)X.continue=!1;X.code??(X.code="custom"),X.input??(X.input=$.value),X.inst??(X.inst=b),$.issues.push(n.issue(X))}};let Q=w.transform($.value,$);if(Q instanceof Promise)return Q.then((G)=>{return $.value=G,$});return $.value=Q,$}});function XG(b){return new D5({type:"transform",transform:b})}var YG=U("ZodOptional",(b,w)=>{n9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Wb(b){return new YG({type:"optional",innerType:b})}var z5=U("ZodNullable",(b,w)=>{l9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function wG(b){return new z5({type:"nullable",innerType:b})}var A5=U("ZodDefault",(b,w)=>{i9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeDefault=b.unwrap});function O5(b,w){return new A5({type:"default",innerType:b,get defaultValue(){return typeof w==="function"?w():n.shallowClone(w)}})}var q5=U("ZodPrefault",(b,w)=>{p9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function L5(b,w){return new q5({type:"prefault",innerType:b,get defaultValue(){return typeof w==="function"?w():n.shallowClone(w)}})}var HG=U("ZodNonOptional",(b,w)=>{o9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function U5(b,w){return new HG({type:"nonoptional",innerType:b,...n.normalizeParams(w)})}var B5=U("ZodCatch",(b,w)=>{d9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeCatch=b.unwrap});function F5(b,w){return new B5({type:"catch",innerType:b,catchValue:typeof w==="function"?w:()=>w})}var K5=U("ZodPipe",(b,w)=>{t9.init(b,w),Qb.init(b,w),b.in=w.in,b.out=w.out});function _4(b,w){return new K5({type:"pipe",in:b,out:w})}var P5=U("ZodReadonly",(b,w)=>{r9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function M5(b){return new P5({type:"readonly",innerType:b})}var JG=U("ZodCustom",(b,w)=>{e9.init(b,w),Qb.init(b,w)});function DG(b,w){return k8(JG,b??(()=>!0),w)}function Z5(b,w={}){return v8(JG,b,w)}function j5(b){return C8(b)}function k4(b,w){return _4(XG(b),w)}Sb(A4());var v4="2025-11-25";var zG=[v4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Fw="io.modelcontextprotocol/related-task",C0="2.0",Db=DG((b)=>b!==null&&(typeof b==="object"||typeof b==="function")),AG=r([L(),i().int()]),OG=L(),Zj=Ub({ttl:r([i(),S4()]).optional(),pollInterval:i().optional()}),I5=V({ttl:i().optional()}),V5=V({taskId:L()}),C4=Ub({progressToken:AG.optional(),[Fw]:V5.optional()}),Eb=V({_meta:C4.optional()}),N1=Eb.extend({task:I5.optional()}),qG=(b)=>N1.safeParse(b).success,zb=V({method:L(),params:Eb.loose().optional()}),Rb=V({_meta:C4.optional()}),kb=V({method:L(),params:Rb.loose().optional()}),Ab=Ub({_meta:C4.optional()}),x0=r([L(),i().int()]),LG=V({jsonrpc:T(C0),id:x0,...zb.shape}).strict(),x4=(b)=>LG.safeParse(b).success,UG=V({jsonrpc:T(C0),...kb.shape}).strict(),BG=(b)=>UG.safeParse(b).success,u4=V({jsonrpc:T(C0),id:x0,result:Ab}).strict(),T1=(b)=>u4.safeParse(b).success;var c;(function(b){b[b.ConnectionClosed=-32000]="ConnectionClosed",b[b.RequestTimeout=-32001]="RequestTimeout",b[b.ParseError=-32700]="ParseError",b[b.InvalidRequest=-32600]="InvalidRequest",b[b.MethodNotFound=-32601]="MethodNotFound",b[b.InvalidParams=-32602]="InvalidParams",b[b.InternalError=-32603]="InternalError",b[b.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(c||(c={}));var y4=V({jsonrpc:T(C0),id:x0.optional(),error:V({code:i().int(),message:L(),data:wb().optional()})}).strict();var FG=(b)=>y4.safeParse(b).success;var jj=r([LG,UG,u4,y4]),Ij=r([u4,y4]),u0=Ab.strict(),N5=Rb.extend({requestId:x0.optional(),reason:L().optional()}),y0=kb.extend({method:T("notifications/cancelled"),params:N5}),T5=V({src:L(),mimeType:L().optional(),sizes:f(L()).optional(),theme:Pb(["light","dark"]).optional()}),E1=V({icons:f(T5).optional()}),nw=V({name:L(),title:L().optional()}),KG=nw.extend({...nw.shape,...E1.shape,version:L(),websiteUrl:L().optional(),description:L().optional()}),E5=k0(V({applyDefaults:Hb().optional()}),$b(L(),wb())),_5=k4((b)=>{if(b&&typeof b==="object"&&!Array.isArray(b)){if(Object.keys(b).length===0)return{form:{}}}return b},k0(V({form:E5.optional(),url:Db.optional()}),$b(L(),wb()).optional())),S5=Ub({list:Db.optional(),cancel:Db.optional(),requests:Ub({sampling:Ub({createMessage:Db.optional()}).optional(),elicitation:Ub({create:Db.optional()}).optional()}).optional()}),R5=Ub({list:Db.optional(),cancel:Db.optional(),requests:Ub({tools:Ub({call:Db.optional()}).optional()}).optional()}),k5=V({experimental:$b(L(),Db).optional(),sampling:V({context:Db.optional(),tools:Db.optional()}).optional(),elicitation:_5.optional(),roots:V({listChanged:Hb().optional()}).optional(),tasks:S5.optional()}),v5=Eb.extend({protocolVersion:L(),capabilities:k5,clientInfo:KG}),h4=zb.extend({method:T("initialize"),params:v5});var C5=V({experimental:$b(L(),Db).optional(),logging:Db.optional(),completions:Db.optional(),prompts:V({listChanged:Hb().optional()}).optional(),resources:V({subscribe:Hb().optional(),listChanged:Hb().optional()}).optional(),tools:V({listChanged:Hb().optional()}).optional(),tasks:R5.optional()}),x5=Ab.extend({protocolVersion:L(),capabilities:C5,serverInfo:KG,instructions:L().optional()}),f4=kb.extend({method:T("notifications/initialized"),params:Rb.optional()});var h0=zb.extend({method:T("ping"),params:Eb.optional()}),u5=V({progress:i(),total:Wb(i()),message:Wb(L())}),y5=V({...Rb.shape,...u5.shape,progressToken:AG}),f0=kb.extend({method:T("notifications/progress"),params:y5}),h5=Eb.extend({cursor:OG.optional()}),_1=zb.extend({params:h5.optional()}),S1=Ab.extend({nextCursor:OG.optional()}),f5=Pb(["working","input_required","completed","failed","cancelled"]),R1=V({taskId:L(),status:f5,ttl:r([i(),S4()]),createdAt:L(),lastUpdatedAt:L(),pollInterval:Wb(i()),statusMessage:Wb(L())}),lw=Ab.extend({task:R1}),c5=Rb.merge(R1),k1=kb.extend({method:T("notifications/tasks/status"),params:c5}),c0=zb.extend({method:T("tasks/get"),params:Eb.extend({taskId:L()})}),g0=Ab.merge(R1),m0=zb.extend({method:T("tasks/result"),params:Eb.extend({taskId:L()})}),Vj=Ab.loose(),n0=_1.extend({method:T("tasks/list")}),l0=S1.extend({tasks:f(R1)}),i0=zb.extend({method:T("tasks/cancel"),params:Eb.extend({taskId:L()})}),PG=Ab.merge(R1),MG=V({uri:L(),mimeType:Wb(L()),_meta:$b(L(),wb()).optional()}),ZG=MG.extend({text:L()}),c4=L().refine((b)=>{try{return atob(b),!0}catch{return!1}},{message:"Invalid Base64 string"}),jG=MG.extend({blob:c4}),v1=Pb(["user","assistant"]),iw=V({audience:f(v1).optional(),priority:i().min(0).max(1).optional(),lastModified:V1.datetime({offset:!0}).optional()}),IG=V({...nw.shape,...E1.shape,uri:L(),description:Wb(L()),mimeType:Wb(L()),annotations:iw.optional(),_meta:Wb(Ub({}))}),g5=V({...nw.shape,...E1.shape,uriTemplate:L(),description:Wb(L()),mimeType:Wb(L()),annotations:iw.optional(),_meta:Wb(Ub({}))}),g4=_1.extend({method:T("resources/list")}),m5=S1.extend({resources:f(IG)}),n5=_1.extend({method:T("resources/templates/list")}),l5=S1.extend({resourceTemplates:f(g5)}),m4=Eb.extend({uri:L()}),i5=m4,n4=zb.extend({method:T("resources/read"),params:i5}),p5=Ab.extend({contents:f(r([ZG,jG]))}),o5=kb.extend({method:T("notifications/resources/list_changed"),params:Rb.optional()}),d5=m4,t5=zb.extend({method:T("resources/subscribe"),params:d5}),r5=m4,e5=zb.extend({method:T("resources/unsubscribe"),params:r5}),s5=Rb.extend({uri:L()}),a5=kb.extend({method:T("notifications/resources/updated"),params:s5}),bA=V({name:L(),description:Wb(L()),required:Wb(Hb())}),wA=V({...nw.shape,...E1.shape,description:Wb(L()),arguments:Wb(f(bA)),_meta:Wb(Ub({}))}),$A=_1.extend({method:T("prompts/list")}),WA=S1.extend({prompts:f(wA)}),QA=Eb.extend({name:L(),arguments:$b(L(),L()).optional()}),GA=zb.extend({method:T("prompts/get"),params:QA}),l4=V({type:T("text"),text:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),i4=V({type:T("image"),data:c4,mimeType:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),p4=V({type:T("audio"),data:c4,mimeType:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),XA=V({type:T("tool_use"),name:L(),id:L(),input:$b(L(),wb()),_meta:$b(L(),wb()).optional()}),YA=V({type:T("resource"),resource:r([ZG,jG]),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),HA=IG.extend({type:T("resource_link")}),o4=r([l4,i4,p4,HA,YA]),JA=V({role:v1,content:o4}),DA=Ab.extend({description:L().optional(),messages:f(JA)}),zA=kb.extend({method:T("notifications/prompts/list_changed"),params:Rb.optional()}),AA=V({title:L().optional(),readOnlyHint:Hb().optional(),destructiveHint:Hb().optional(),idempotentHint:Hb().optional(),openWorldHint:Hb().optional()}),OA=V({taskSupport:Pb(["required","optional","forbidden"]).optional()}),VG=V({...nw.shape,...E1.shape,description:L().optional(),inputSchema:V({type:T("object"),properties:$b(L(),Db).optional(),required:f(L()).optional()}).catchall(wb()),outputSchema:V({type:T("object"),properties:$b(L(),Db).optional(),required:f(L()).optional()}).catchall(wb()).optional(),annotations:AA.optional(),execution:OA.optional(),_meta:$b(L(),wb()).optional()}),d4=_1.extend({method:T("tools/list")}),qA=S1.extend({tools:f(VG)}),p0=Ab.extend({content:f(o4).default([]),structuredContent:$b(L(),wb()).optional(),isError:Hb().optional()}),Nj=p0.or(Ab.extend({toolResult:wb()})),LA=N1.extend({name:L(),arguments:$b(L(),wb()).optional()}),C1=zb.extend({method:T("tools/call"),params:LA}),UA=kb.extend({method:T("notifications/tools/list_changed"),params:Rb.optional()}),Tj=V({autoRefresh:Hb().default(!0),debounceMs:i().int().nonnegative().default(300)}),x1=Pb(["debug","info","notice","warning","error","critical","alert","emergency"]),BA=Eb.extend({level:x1}),t4=zb.extend({method:T("logging/setLevel"),params:BA}),FA=Rb.extend({level:x1,logger:L().optional(),data:wb()}),KA=kb.extend({method:T("notifications/message"),params:FA}),PA=V({name:L().optional()}),MA=V({hints:f(PA).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),ZA=V({mode:Pb(["auto","required","none"]).optional()}),jA=V({type:T("tool_result"),toolUseId:L().describe("The unique identifier for the corresponding tool call."),content:f(o4).default([]),structuredContent:V({}).loose().optional(),isError:Hb().optional(),_meta:$b(L(),wb()).optional()}),IA=R4("type",[l4,i4,p4]),v0=R4("type",[l4,i4,p4,XA,jA]),VA=V({role:v1,content:r([v0,f(v0)]),_meta:$b(L(),wb()).optional()}),NA=N1.extend({messages:f(VA),modelPreferences:MA.optional(),systemPrompt:L().optional(),includeContext:Pb(["none","thisServer","allServers"]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:f(L()).optional(),metadata:Db.optional(),tools:f(VG).optional(),toolChoice:ZA.optional()}),TA=zb.extend({method:T("sampling/createMessage"),params:NA}),r4=Ab.extend({model:L(),stopReason:Wb(Pb(["endTurn","stopSequence","maxTokens"]).or(L())),role:v1,content:IA}),e4=Ab.extend({model:L(),stopReason:Wb(Pb(["endTurn","stopSequence","maxTokens","toolUse"]).or(L())),role:v1,content:r([v0,f(v0)])}),EA=V({type:T("boolean"),title:L().optional(),description:L().optional(),default:Hb().optional()}),_A=V({type:T("string"),title:L().optional(),description:L().optional(),minLength:i().optional(),maxLength:i().optional(),format:Pb(["email","uri","date","date-time"]).optional(),default:L().optional()}),SA=V({type:Pb(["number","integer"]),title:L().optional(),description:L().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),RA=V({type:T("string"),title:L().optional(),description:L().optional(),enum:f(L()),default:L().optional()}),kA=V({type:T("string"),title:L().optional(),description:L().optional(),oneOf:f(V({const:L(),title:L()})),default:L().optional()}),vA=V({type:T("string"),title:L().optional(),description:L().optional(),enum:f(L()),enumNames:f(L()).optional(),default:L().optional()}),CA=r([RA,kA]),xA=V({type:T("array"),title:L().optional(),description:L().optional(),minItems:i().optional(),maxItems:i().optional(),items:V({type:T("string"),enum:f(L())}),default:f(L()).optional()}),uA=V({type:T("array"),title:L().optional(),description:L().optional(),minItems:i().optional(),maxItems:i().optional(),items:V({anyOf:f(V({const:L(),title:L()}))}),default:f(L()).optional()}),yA=r([xA,uA]),hA=r([vA,CA,yA]),fA=r([hA,EA,_A,SA]),cA=N1.extend({mode:T("form").optional(),message:L(),requestedSchema:V({type:T("object"),properties:$b(L(),fA),required:f(L()).optional()})}),gA=N1.extend({mode:T("url"),message:L(),elicitationId:L(),url:L().url()}),mA=r([cA,gA]),nA=zb.extend({method:T("elicitation/create"),params:mA}),lA=Rb.extend({elicitationId:L()}),iA=kb.extend({method:T("notifications/elicitation/complete"),params:lA}),o0=Ab.extend({action:Pb(["accept","decline","cancel"]),content:k4((b)=>b===null?void 0:b,$b(L(),r([L(),i(),Hb(),f(L())])).optional())}),pA=V({type:T("ref/resource"),uri:L()});var oA=V({type:T("ref/prompt"),name:L()}),dA=Eb.extend({ref:r([oA,pA]),argument:V({name:L(),value:L()}),context:V({arguments:$b(L(),L()).optional()}).optional()}),tA=zb.extend({method:T("completion/complete"),params:dA});var rA=Ab.extend({completion:Ub({values:f(L()).max(100),total:Wb(i().int()),hasMore:Wb(Hb())})}),eA=V({uri:L().startsWith("file://"),name:L().optional(),_meta:$b(L(),wb()).optional()}),sA=zb.extend({method:T("roots/list"),params:Eb.optional()}),s4=Ab.extend({roots:f(eA)}),aA=kb.extend({method:T("notifications/roots/list_changed"),params:Rb.optional()}),Ej=r([h0,h4,tA,t4,GA,$A,g4,n5,n4,t5,e5,C1,d4,c0,m0,n0,i0]),_j=r([y0,f0,f4,aA,k1]),Sj=r([u0,r4,e4,o0,s4,g0,l0,lw]),Rj=r([h0,TA,nA,sA,c0,m0,n0,i0]),kj=r([y0,f0,KA,a5,o5,UA,zA,k1,iA]),vj=r([u0,x5,rA,DA,WA,m5,l5,p5,p0,qA,g0,l0,lw]);class x extends Error{constructor(b,w,$){super(`MCP error ${b}: ${w}`);this.code=b,this.data=$,this.name="McpError"}static fromError(b,w,$){if(b===c.UrlElicitationRequired&&$){let W=$;if(W.elicitations)return new NG(W.elicitations,w)}return new x(b,w,$)}}class NG extends x{constructor(b,w=`URL elicitation${b.length>1?"s":""} required`){super(c.UrlElicitationRequired,w,{elicitations:b})}get elicitations(){return this.data?.elicitations??[]}}function Kw(b){return b==="completed"||b==="failed"||b==="cancelled"}var bO=Symbol("Let zodToJsonSchema decide on which parser to use");var AI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function a4(b){let $=S0(b)?.method;if(!$)throw Error("Schema is missing a method literal");let W=x8($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function b6(b,w){let $=Bw(b,w);if(!$.success)throw $.error;return $.data}var XO=60000;class w6{constructor(b){if(this._options=b,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(y0,(w)=>{this._oncancel(w)}),this.setNotificationHandler(f0,(w)=>{this._onprogress(w)}),this.setRequestHandler(h0,(w)=>({})),this._taskStore=b?.taskStore,this._taskMessageQueue=b?.taskMessageQueue,this._taskStore)this.setRequestHandler(c0,async(w,$)=>{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new x(c.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(m0,async(w,$)=>{let W=async()=>{let Q=w.params.taskId;if(this._taskMessageQueue){let X;while(X=await this._taskMessageQueue.dequeue(Q,$.sessionId)){if(X.type==="response"||X.type==="error"){let Y=X.message,H=Y.id,J=this._requestResolvers.get(H);if(J)if(this._requestResolvers.delete(H),X.type==="response")J(Y);else{let D=Y,z=new x(D.error.code,D.error.message,D.error.data);J(z)}else{let D=X.type==="response"?"Response":"Error";this._onerror(Error(`${D} handler missing for request ${H}`))}continue}await this._transport?.send(X.message,{relatedRequestId:$.requestId})}}let G=await this._taskStore.getTask(Q,$.sessionId);if(!G)throw new x(c.InvalidParams,`Task not found: ${Q}`);if(!Kw(G.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(Kw(G.status)){let X=await this._taskStore.getTaskResult(Q,$.sessionId);return this._clearTaskQueue(Q),{...X,_meta:{...X._meta,[Fw]:{taskId:Q}}}}return await W()};return await W()}),this.setRequestHandler(n0,async(w,$)=>{try{let{tasks:W,nextCursor:Q}=await this._taskStore.listTasks(w.params?.cursor,$.sessionId);return{tasks:W,nextCursor:Q,_meta:{}}}catch(W){throw new x(c.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(i0,async(w,$)=>{try{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new x(c.InvalidParams,`Task not found: ${w.params.taskId}`);if(Kw(W.status))throw new x(c.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(w.params.taskId);let Q=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!Q)throw new x(c.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...Q}}catch(W){if(W instanceof x)throw W;throw new x(c.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(b){if(!b.params.requestId)return;this._requestHandlerAbortControllers.get(b.params.requestId)?.abort(b.params.reason)}_setupTimeout(b,w,$,W,Q=!1){this._timeoutInfo.set(b,{timeoutId:setTimeout(W,w),startTime:Date.now(),timeout:w,maxTotalTimeout:$,resetTimeoutOnProgress:Q,onTimeout:W})}_resetTimeout(b){let w=this._timeoutInfo.get(b);if(!w)return!1;let $=Date.now()-w.startTime;if(w.maxTotalTimeout&&$>=w.maxTotalTimeout)throw this._timeoutInfo.delete(b),x.fromError(c.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:$});return clearTimeout(w.timeoutId),w.timeoutId=setTimeout(w.onTimeout,w.timeout),!0}_cleanupTimeout(b){let w=this._timeoutInfo.get(b);if(w)clearTimeout(w.timeoutId),this._timeoutInfo.delete(b)}async connect(b){this._transport=b;let w=this.transport?.onclose;this._transport.onclose=()=>{w?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(Q)=>{$?.(Q),this._onerror(Q)};let W=this._transport?.onmessage;this._transport.onmessage=(Q,G)=>{if(W?.(Q,G),T1(Q)||FG(Q))this._onresponse(Q);else if(x4(Q))this._onrequest(Q,G);else if(BG(Q))this._onnotification(Q);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Q)}`))},await this._transport.start()}_onclose(){let b=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let w=x.fromError(c.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of b.values())$(w)}_onerror(b){this.onerror?.(b)}_onnotification(b){let w=this._notificationHandlers.get(b.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w(b)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(b,w){let $=this._requestHandlers.get(b.method)??this.fallbackRequestHandler,W=this._transport,Q=b.params?._meta?.[Fw]?.taskId;if($===void 0){let J={jsonrpc:"2.0",id:b.id,error:{code:c.MethodNotFound,message:"Method not found"}};if(Q&&this._taskMessageQueue)this._enqueueTaskMessage(Q,{type:"error",message:J,timestamp:Date.now()},W?.sessionId).catch((D)=>this._onerror(Error(`Failed to enqueue error response: ${D}`)));else W?.send(J).catch((D)=>this._onerror(Error(`Failed to send an error response: ${D}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set(b.id,G);let X=qG(b.params)?b.params.task:void 0,Y=this._taskStore?this.requestTaskStore(b,W?.sessionId):void 0,H={signal:G.signal,sessionId:W?.sessionId,_meta:b.params?._meta,sendNotification:async(J)=>{let D={relatedRequestId:b.id};if(Q)D.relatedTask={taskId:Q};await this.notification(J,D)},sendRequest:async(J,D,z)=>{let O={...z,relatedRequestId:b.id};if(Q&&!O.relatedTask)O.relatedTask={taskId:Q};let q=O.relatedTask?.taskId??Q;if(q&&Y)await Y.updateTaskStatus(q,"input_required");return await this.request(J,D,O)},authInfo:w?.authInfo,requestId:b.id,requestInfo:w?.requestInfo,taskId:Q,taskStore:Y,taskRequestedTtl:X?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(X)this.assertTaskHandlerCapability(b.method)}).then(()=>$(b,H)).then(async(J)=>{if(G.signal.aborted)return;let D={result:J,jsonrpc:"2.0",id:b.id};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"response",message:D,timestamp:Date.now()},W?.sessionId);else await W?.send(D)},async(J)=>{if(G.signal.aborted)return;let D={jsonrpc:"2.0",id:b.id,error:{code:Number.isSafeInteger(J.code)?J.code:c.InternalError,message:J.message??"Internal error",...J.data!==void 0&&{data:J.data}}};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"error",message:D,timestamp:Date.now()},W?.sessionId);else await W?.send(D)}).catch((J)=>this._onerror(Error(`Failed to send response: ${J}`))).finally(()=>{this._requestHandlerAbortControllers.delete(b.id)})}_onprogress(b){let{progressToken:w,...$}=b.params,W=Number(w),Q=this._progressHandlers.get(W);if(!Q){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(b)}`));return}let G=this._responseHandlers.get(W),X=this._timeoutInfo.get(W);if(X&&G&&X.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(Y){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),G(Y);return}Q($)}_onresponse(b){let w=Number(b.id),$=this._requestResolvers.get(w);if($){if(this._requestResolvers.delete(w),T1(b))$(b);else{let G=new x(b.error.code,b.error.message,b.error.data);$(G)}return}let W=this._responseHandlers.get(w);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(b)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let Q=!1;if(T1(b)&&b.result&&typeof b.result==="object"){let G=b.result;if(G.task&&typeof G.task==="object"){let X=G.task;if(typeof X.taskId==="string")Q=!0,this._taskProgressTokens.set(X.taskId,w)}}if(!Q)this._progressHandlers.delete(w);if(T1(b))W(b);else{let G=x.fromError(b.error.code,b.error.message,b.error.data);W(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(b,w,$){let{task:W}=$??{};if(!W){try{yield{type:"result",result:await this.request(b,w,$)}}catch(G){yield{type:"error",error:G instanceof x?G:new x(c.InternalError,String(G))}}return}let Q;try{let G=await this.request(b,lw,$);if(G.task)Q=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new x(c.InternalError,"Task creation did not return a task");while(!0){let X=await this.getTask({taskId:Q},$);if(yield{type:"taskStatus",task:X},Kw(X.status)){if(X.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};else if(X.status==="failed")yield{type:"error",error:new x(c.InternalError,`Task ${Q} failed`)};else if(X.status==="cancelled")yield{type:"error",error:new x(c.InternalError,`Task ${Q} was cancelled`)};return}if(X.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};return}let Y=X.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,Y)),$?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof x?G:new x(c.InternalError,String(G))}}}request(b,w,$){let{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G,task:X,relatedTask:Y}=$??{};return new Promise((H,J)=>{let D=(M)=>{J(M)};if(!this._transport){D(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(b.method),X)this.assertTaskCapability(b.method)}catch(M){D(M);return}$?.signal?.throwIfAborted();let z=this._requestMessageId++,O={...b,jsonrpc:"2.0",id:z};if($?.onprogress)this._progressHandlers.set(z,$.onprogress),O.params={...b.params,_meta:{...b.params?._meta||{},progressToken:z}};if(X)O.params={...O.params,task:X};if(Y)O.params={...O.params,_meta:{...O.params?._meta||{},[Fw]:Y}};let q=(M)=>{this._responseHandlers.delete(z),this._progressHandlers.delete(z),this._cleanupTimeout(z),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:z,reason:String(M)}},{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let k=M instanceof x?M:new x(c.RequestTimeout,String(M));J(k)};this._responseHandlers.set(z,(M)=>{if($?.signal?.aborted)return;if(M instanceof Error)return J(M);try{let k=Bw(w,M.result);if(!k.success)J(k.error);else H(k.data)}catch(k){J(k)}}),$?.signal?.addEventListener("abort",()=>{q($?.signal?.reason)});let B=$?.timeout??XO,K=()=>q(x.fromError(c.RequestTimeout,"Request timed out",{timeout:B}));this._setupTimeout(z,B,$?.maxTotalTimeout,K,$?.resetTimeoutOnProgress??!1);let Z=Y?.taskId;if(Z){let M=(k)=>{let S=this._responseHandlers.get(z);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${z}`))};this._requestResolvers.set(z,M),this._enqueueTaskMessage(Z,{type:"request",message:O,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(z),J(k)})}else this._transport.send(O,{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((M)=>{this._cleanupTimeout(z),J(M)})})}async getTask(b,w){return this.request({method:"tasks/get",params:b},g0,w)}async getTaskResult(b,w,$){return this.request({method:"tasks/result",params:b},w,$)}async listTasks(b,w){return this.request({method:"tasks/list",params:b},l0,w)}async cancelTask(b,w){return this.request({method:"tasks/cancel",params:b},PG,w)}async notification(b,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(b.method);let $=w?.relatedTask?.taskId;if($){let X={...b,jsonrpc:"2.0",params:{...b.params,_meta:{...b.params?._meta||{},[Fw]:w.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:X,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(b.method)&&!b.params&&!w?.relatedRequestId&&!w?.relatedTask){if(this._pendingDebouncedNotifications.has(b.method))return;this._pendingDebouncedNotifications.add(b.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(b.method),!this._transport)return;let X={...b,jsonrpc:"2.0"};if(w?.relatedTask)X={...X,params:{...X.params,_meta:{...X.params?._meta||{},[Fw]:w.relatedTask}}};this._transport?.send(X,w).catch((Y)=>this._onerror(Y))});return}let G={...b,jsonrpc:"2.0"};if(w?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[Fw]:w.relatedTask}}};await this._transport.send(G,w)}setRequestHandler(b,w){let $=a4(b);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let G=b6(b,W);return Promise.resolve(w(G,Q))})}removeRequestHandler(b){this._requestHandlers.delete(b)}assertCanSetRequestHandler(b){if(this._requestHandlers.has(b))throw Error(`A request handler for ${b} already exists, which would be overridden`)}setNotificationHandler(b,w){let $=a4(b);this._notificationHandlers.set($,(W)=>{let Q=b6(b,W);return Promise.resolve(w(Q))})}removeNotificationHandler(b){this._notificationHandlers.delete(b)}_cleanupTaskProgressHandler(b){let w=this._taskProgressTokens.get(b);if(w!==void 0)this._progressHandlers.delete(w),this._taskProgressTokens.delete(b)}async _enqueueTaskMessage(b,w,$){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(b,w,$,W)}async _clearTaskQueue(b,w){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(b,w);for(let W of $)if(W.type==="request"&&x4(W.message)){let Q=W.message.id,G=this._requestResolvers.get(Q);if(G)G(new x(c.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Q);else this._onerror(Error(`Resolver missing for request ${Q} during task ${b} cleanup`))}}}async _waitForTaskUpdate(b,w){let $=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(b);if(W?.pollInterval)$=W.pollInterval}catch{}return new Promise((W,Q)=>{if(w.aborted){Q(new x(c.InvalidRequest,"Request cancelled"));return}let G=setTimeout(W,$);w.addEventListener("abort",()=>{clearTimeout(G),Q(new x(c.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(b,w){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(W)=>{if(!b)throw Error("No request provided");return await $.createTask(W,b.id,{method:b.method,params:b.params},w)},getTask:async(W)=>{let Q=await $.getTask(W,w);if(!Q)throw new x(c.InvalidParams,"Failed to retrieve task: Task not found");return Q},storeTaskResult:async(W,Q,G)=>{await $.storeTaskResult(W,Q,G,w);let X=await $.getTask(W,w);if(X){let Y=k1.parse({method:"notifications/tasks/status",params:X});if(await this.notification(Y),Kw(X.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return $.getTaskResult(W,w)},updateTaskStatus:async(W,Q,G)=>{let X=await $.getTask(W,w);if(!X)throw new x(c.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(Kw(X.status))throw new x(c.InvalidParams,`Cannot update task "${W}" from terminal status "${X.status}" to "${Q}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(W,Q,G,w);let Y=await $.getTask(W,w);if(Y){let H=k1.parse({method:"notifications/tasks/status",params:Y});if(await this.notification(H),Kw(Y.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,w)}}}}function TG(b){return b!==null&&typeof b==="object"&&!Array.isArray(b)}function EG(b,w){let $={...b};for(let W in w){let Q=W,G=w[Q];if(G===void 0)continue;let X=$[Q];if(TG(X)&&TG(G))$[Q]={...X,...G};else $[Q]=G}return $}var GD=RW(t6(),1),XD=RW(QD(),1);function LP(){let b=new GD.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return XD.default(b),b}class GW{constructor(b){this._ajv=b??LP()}getValidator(b){let w="$id"in b&&typeof b.$id==="string"?this._ajv.getSchema(b.$id)??this._ajv.compile(b):this._ajv.compile(b);return($)=>{if(w($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}class XW{constructor(b){this._server=b}requestStream(b,w,$){return this._server.requestStream(b,w,$)}async getTask(b,w){return this._server.getTask({taskId:b},w)}async getTaskResult(b,w,$){return this._server.getTaskResult({taskId:b},w,$)}async listTasks(b,w){return this._server.listTasks(b?{cursor:b}:void 0,w)}async cancelTask(b,w){return this._server.cancelTask({taskId:b},w)}}function YD(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"tools/call":if(!b.tools?.call)throw Error(`${$} does not support task creation for tools/call (required for ${w})`);break;default:break}}function HD(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!b.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!b.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}class YW extends w6{constructor(b,w){super(w);if(this._serverInfo=b,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(x1.options.map(($,W)=>[$,W])),this.isMessageIgnored=($,W)=>{let Q=this._loggingLevels.get(W);return Q?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(Q):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new GW,this.setRequestHandler(h4,($)=>this._oninitialize($)),this.setNotificationHandler(f4,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(t4,async($,W)=>{let Q=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=$.params,X=x1.safeParse(G);if(X.success)this._loggingLevels.set(Q,X.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new XW(this)};return this._experimental}registerCapabilities(b){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=EG(this._capabilities,b)}setRequestHandler(b,w){let W=S0(b)?.method;if(!W)throw Error("Schema is missing a method literal");let Q;if(mw(W)){let X=W;Q=X._zod?.def?.value??X.value}else{let X=W;Q=X._def?.value??X.value}if(typeof Q!=="string")throw Error("Schema method literal must be a string");if(Q==="tools/call"){let X=async(Y,H)=>{let J=Bw(C1,Y);if(!J.success){let q=J.error instanceof Error?J.error.message:String(J.error);throw new x(c.InvalidParams,`Invalid tools/call request: ${q}`)}let{params:D}=J.data,z=await Promise.resolve(w(Y,H));if(D.task){let q=Bw(lw,z);if(!q.success){let B=q.error instanceof Error?q.error.message:String(q.error);throw new x(c.InvalidParams,`Invalid task creation result: ${B}`)}return q.data}let O=Bw(p0,z);if(!O.success){let q=O.error instanceof Error?O.error.message:String(O.error);throw new x(c.InvalidParams,`Invalid tools/call result: ${q}`)}return O.data};return super.setRequestHandler(b,X)}return super.setRequestHandler(b,w)}assertCapabilityForMethod(b){switch(b){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${b})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${b})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${b})`);break;case"ping":break}}assertNotificationCapability(b){switch(b){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${b})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${b})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${b})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${b})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(b){if(!this._capabilities)return;switch(b){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${b})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${b})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${b})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${b})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${b})`);break;case"ping":case"initialize":break}}assertTaskCapability(b){HD(this._clientCapabilities?.tasks?.requests,b,"Client")}assertTaskHandlerCapability(b){if(!this._capabilities)return;YD(this._capabilities.tasks?.requests,b,"Server")}async _oninitialize(b){let w=b.params.protocolVersion;return this._clientCapabilities=b.params.capabilities,this._clientVersion=b.params.clientInfo,{protocolVersion:zG.includes(w)?w:v4,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"},u0)}async createMessage(b,w){if(b.tools||b.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(b.messages.length>0){let $=b.messages[b.messages.length-1],W=Array.isArray($.content)?$.content:[$.content],Q=W.some((H)=>H.type==="tool_result"),G=b.messages.length>1?b.messages[b.messages.length-2]:void 0,X=G?Array.isArray(G.content)?G.content:[G.content]:[],Y=X.some((H)=>H.type==="tool_use");if(Q){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!Y)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(Y){let H=new Set(X.filter((D)=>D.type==="tool_use").map((D)=>D.id)),J=new Set(W.filter((D)=>D.type==="tool_result").map((D)=>D.toolUseId));if(H.size!==J.size||![...H].every((D)=>J.has(D)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(b.tools)return this.request({method:"sampling/createMessage",params:b},e4,w);return this.request({method:"sampling/createMessage",params:b},r4,w)}async elicitInput(b,w){switch(b.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=b;return this.request({method:"elicitation/create",params:W},o0,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=b.mode==="form"?b:{...b,mode:"form"},Q=await this.request({method:"elicitation/create",params:W},o0,w);if(Q.action==="accept"&&Q.content&&W.requestedSchema)try{let X=this._jsonSchemaValidator.getValidator(W.requestedSchema)(Q.content);if(!X.valid)throw new x(c.InvalidParams,`Elicitation response content does not match requested schema: ${X.errorMessage}`)}catch(G){if(G instanceof x)throw G;throw new x(c.InternalError,`Error validating elicitation response: ${G instanceof Error?G.message:String(G)}`)}return Q}}}createElicitationCompletionNotifier(b,w){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:b}},w)}async listRoots(b,w){return this.request({method:"roots/list",params:b},s4,w)}async sendLoggingMessage(b,w){if(this._capabilities.logging){if(!this.isMessageIgnored(b.level,w))return this.notification({method:"notifications/message",params:b})}}async sendResourceUpdated(b){return this.notification({method:"notifications/resources/updated",params:b})}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 JD={name:"@sequenzy/mcp",version:"0.0.114",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"bunx --bun tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^7.0.2"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var HW=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],DD={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function BP(b){let $=(b??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return $.length>0?$:"https://sequenzy.com"}function nb(b){let w=b?.trim();return w?w:void 0}function eb(b){return encodeURIComponent(b)}function Xb(b,w){return`${b}${w}`}function Yb(b,w=""){return`/dashboard/company/${eb(b)}${w}`}function zD(b,w,$){return Xb(b,`${Yb(w,"/settings")}?tab=${encodeURIComponent($)}`)}function FP(b,w){let $=HW.map((W)=>[W,w?zD(b,w,W):""]);return Object.fromEntries($)}function Hw(b={},w){let $=BP(w),W=nb(b.companyId),Q={},G=FP($,W);if(!W)return{appUrl:$,routeTemplates:DD,settingsTabValues:HW,urls:Q,settingsUrls:G};Q.dashboard=Xb($,Yb(W)),Q.campaigns=Xb($,Yb(W,"/campaign")),Q.landingPages=Xb($,Yb(W,"/landing-pages")),Q.sequences=Xb($,Yb(W,"/sequences")),Q.settings=Xb($,Yb(W,"/settings")),Q.emails=Xb($,Yb(W,"/emails")),Q.subscribers=Xb($,Yb(W,"/subscribers")),Q.sentEmails=Xb($,Yb(W,"/sent-emails")),Q.segments=Xb($,Yb(W,"/segments")),Q.metrics=Xb($,Yb(W,"/metrics")),Q.transactional=Xb($,Yb(W,"/transactional"));let X=nb(b.campaignId);if(X)Q.campaign=Xb($,Yb(W,`/campaign/${eb(X)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let Y=nb(b.landingPageId);if(Y)Q.landingPage=Xb($,Yb(W,`/landing-pages/${eb(Y)}`));let H=nb(b.sequenceId);if(H)Q.sequence=Xb($,Yb(W,`/sequences/${eb(H)}`));let J=nb(b.emailId)??nb(b.templateId);if(J)Q.email=Xb($,Yb(W,`/emails/${eb(J)}`)),Q.template=Q.email;let D=nb(b.transactionalId);if(D)Q.transactionalEmail=Xb($,Yb(W,`/transactional/${eb(D)}`));let z=nb(b.emailSendId);if(z)Q.emailSend=Xb($,Yb(W,`/sent-emails/${eb(z)}`));let O=nb(b.domainId);if(O)Q.domain=Xb($,Yb(W,`/settings/domain/${eb(O)}`)),Q.domainVerify=`${Q.domain}/verify`;let q=nb(b.status);if(q)Q.campaignList=Xb($,Yb(W,`/campaign/list/${eb(q)}`)),Q.sequenceList=Xb($,Yb(W,`/sequences/list/${eb(q)}`));let B=nb(b.settingsTab);if(B)Q.settingsTab=zD($,W,B);return{appUrl:$,routeTemplates:DD,settingsTabValues:HW,urls:Q,settingsUrls:G}}var AD=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function OD(b){try{let w;switch(b){case"sequenzy://dashboard":w=await A("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await A("GET","/api/v1/account"),W=Ew()??$.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");w=await A("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":w=await A("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":w=await A("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":w=await A("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":w=await A("GET","/api/v1/sequences");break;case"sequenzy://templates":w=await A("GET","/api/v1/templates");break;case"sequenzy://segments":w=await A("GET","/api/v1/segments");break;case"sequenzy://tags":w=await A("GET","/api/v1/tags");break;case"sequenzy://health":w=await A("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":w=Hw();break;default:throw Error(`Unknown resource: ${b}`)}return{contents:[{uri:b,mimeType:"application/json",text:JSON.stringify(w,null,2)}]}}catch(w){return{contents:[{uri:b,mimeType:"text/plain",text:yw(w)}]}}}function y(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}function F(b,w){let $=b[w];if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function j(b,w,$){let W=F(w,$);if(W===void 0)throw Error(`\`${$}\` is required when calling \`${b}\`.`);return W}var Tw='For exact historical Poll/NPS respondents, use field `pollResponse`, operator `is`, and a JSON value shaped like {"v":1,"campaignId":"camp_123","blockId":"poll_1","match":{"kind":"answer","value":"loved"}}. For NPS buckets, use match {"kind":"npsBucket","bucket":"promoters"}; bucket may be `promoters`, `passives`, or `detractors`.',Jw='Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the `html` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Repeat blocks use { type: \'repeat\', source: \'items\', itemAlias: \'item\', children: [...] }. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',Dw='Replacement Sequenzy email blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',W1='Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer `html`; Sequenzy stores it as one raw HTML block and does not recreate it as native blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Blocks can include repeat blocks over array variables such as items. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',X0="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",qD="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",JW=500,DW=500,lb={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},k$=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],v$={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},KP={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},Q1={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:KP,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},G1={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date"],description:"Use duration for a fixed wait, or until_date to resolve a date from the trigger event."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},zW={type:"object",description:"Type-aware patch for the existing node. Start from get_sequence.sequence.nodes[].config. For logic_delay, set exactly one of delay ({ days, hours, minutes }), delayMs, or waitUntil; optional label is also accepted. For action_email, use name/label, subject, previewText, html/htmlContent or blocks, isTransactional, and sender/reply identity fields. For action_sms, use text, blocks, imageUrls, label, or ineligibleAction. Other node types accept their editable config keys. Managed IDs, nodeType conversion, and branch path IDs/count are not editable here; use edit_sequence_graph for topology. Webhook header patches are merged, and redacted values from get_sequence must be omitted or replaced with a real new value.",additionalProperties:!0},C$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:zW,expectedUpdatedAt:{type:"string",description:"Required optimistic-concurrency value from get_sequence.sequence.nodes[].updatedAt. The update is rejected if that node or its linked email content changed after it was read."}},required:["nodeId","changes","expectedUpdatedAt"],additionalProperties:!1},X1=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],Y1=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var PP=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_websites","check_website","get_integration_guide","get_subscriber","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_subject_lines","generate_sms","get_sms_settings"]),MP=new Set(["select_company","create_company","update_company","update_sync_rules","update_shopify_automation_settings","create_api_key","add_sending_domain","add_website","verify_sending_domain","add_subscriber","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","upsert_products","delete_product","attach_product_file","remove_product_file","upload_image_asset","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","set_template_localization","sync_template_localizations","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback"]),ZP=new Set(["send_test_email","send_test_sms","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","add_sending_domain","add_website","verify_sending_domain","enable_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery"]),jP=new Set(["remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function IP(b){let w=PP.has(b),$=MP.has(b);if(w===$)throw Error(`MCP tool "${b}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:w,destructiveHint:w?!1:jP.has(b),openWorldHint:ZP.has(b)}}function LD(b){return{...b,annotations:{...b.annotations,...IP(b.name)}}}var AW={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],pollResponse:["is"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"]},VP=Object.entries(AW).map(([b,w])=>`${b}: ${w.join(", ")}`).join("; "),OW={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","pollResponse","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct"],description:`Filter field. Use \`phone\` with is_not_empty/is_empty to check whether a subscriber has a phone number, and \`smsStatus\` (is/is_not one of \`subscribed\`, \`unsubscribed\`, \`not_subscribed\`) for SMS marketing consent. Use \`event\` for custom subscriber events, \`segment\` for saved segment membership, \`stripeProduct\`/\`stripeCurrentProduct\`/\`stripeTrialProduct\` for Stripe product-based segments, and \`commerceProduct\` for products purchased through commerce orders - the value is \`provider:productId\` (provider one of \`shopify\`, \`woocommerce\`, \`api\`; product ids are provider-scoped), optionally with an order-count threshold (\`provider:productId:count\`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (\`emailSent\`, \`emailDelivered\`, \`emailOpened\`, \`emailClicked\`, \`emailBounced\`, \`emailComplained\`) accept a time range as the value, a specific campaign via \`campaign:<campaign_id>\`, or \`count:timeRange\` (e.g. \`10:30d\`, \`10:all\`) with at_least/less_than_count to segment by number of opens/clicks. ${Tw}`},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${VP}.`},value:{type:"string",description:`Filter value. For custom attribute empty checks, use \`attributeName:\` such as \`last_logged_in:\`. Event examples: \`saas.purchase:30d\`, \`saas.purchase:all\`, or \`saas.purchase:5:30d\` for thresholds. Segment values are segment IDs. Stripe product examples: \`prod_123\` for bought/didn't buy/current/trialing, \`prod_123:3\` for payment thresholds, \`prod_123:is_canceled\` for products set to cancel, \`prod_123:cancels_at:2026-05-26\`, \`prod_123:end_at:2026-05-26\`, or \`prod_123:start_at:7 days ago\` for product-scoped dates. Engagement examples: \`7d\`, \`30d\`, \`90d\`, \`180d\`, \`all\` for rolling time windows, \`campaign:<campaign_id>\` to scope to a specific sent campaign (use \`list_campaigns\` to find IDs), or \`count:timeRange\` like \`10:30d\` / \`10:all\` with at_least/less_than_count operators (e.g. emailClicked at_least \`10:all\` = clicked 10 or more times ever). ${Tw}`}},required:["field","operator","value"],additionalProperties:!1},qW={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function x$(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(typeof w!=="object"||w===null)return w;let $=w;if(typeof $.id==="string"&&$.id.trim()!=="")return $;return{...$,id:crypto.randomUUID()}})}function u$(b){if(typeof b!=="object"||b===null)return b;let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=x$([w]);return Array.isArray($)?$[0]:w}if(w.kind!=="group")return b;return{...w,id:typeof w.id==="string"&&w.id.trim()!==""?w.id:crypto.randomUUID(),children:Array.isArray(w.children)?w.children.map(u$):[]}}function NP(b){let w=b.indexOf(":");return w!==-1&&b.substring(0,w).trim().length>0}function TP(b){let w=b.indexOf(":");return w!==-1&&b.substring(w+1).trim().length>0}function UD(b){if(b==="all")return!0;let w=b.match(/^(\d+)d$/);if(!w?.[1])return!1;let $=Number.parseInt(w[1],10);return Number.isInteger($)&&$>0}function EP(b,w){let $=w.split(":");if(b==="at_least"||b==="less_than_count"){if($.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let G=$.slice(0,-2).join(":").trim(),X=$.at(-2),Y=$.at(-1),H=X===void 0?Number.NaN:Number.parseInt(X,10);return G&&Number.isInteger(H)&&H>0&&Y!==void 0&&UD(Y)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if($.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=$.slice(0,-1).join(":").trim(),Q=$.at(-1);return W&&Q!==void 0&&UD(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function _P(b){let w=b.indexOf(":");if(w===-1)return{productId:b,subfilter:null,rawValue:null};let $=b.substring(0,w),W=b.substring(w+1),Q=W.indexOf(":");if(Q===-1)return{productId:$,subfilter:W,rawValue:null};return{productId:$,subfilter:W.substring(0,Q),rawValue:W.substring(Q+1)}}function SP(b){return b.trim().toLowerCase().replace(/[-\s]+/g,"_")}function RP(b){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(b)}function kP(b,w){if(w==="cancels_at"||w==="cancel_at"||w==="cancellation_at")return!0;if(b==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(w);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(w)}function vP(b){return["is","is_not","gte","lte","gt","lt"].includes(b)}function CP(b,w,$){if(b==="stripeProduct"){if(w!=="at_least"&&w!=="less_than_count")return null;let Y=$.indexOf(":");if(Y===-1)return null;let H=$.substring(0,Y).trim(),J=Number.parseInt($.substring(Y+1).trim(),10);return H&&Number.isInteger(J)&&J>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(b!=="stripeCurrentProduct"&&b!=="stripeTrialProduct")return null;let{productId:W,subfilter:Q,rawValue:G}=_P($);if(!W.trim())return"Stripe product filters must include a product ID.";if(!Q)return w==="is"||w==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let X=SP(Q);if(RP(X))return w==="is"||w==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!kP(b,X))return`Unsupported Stripe product subfilter "${Q}".`;if(!vP(w))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return G?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var xP=new Set(["shopify","woocommerce","api"]);function uP(b,w){let $=w.trim(),W=$.indexOf(":");if(W!==-1&&xP.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Product filters must include a product ID, like "shopify:42".';if(b!=="at_least"&&b!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let G=$.substring(0,Q).trim(),X=Number.parseInt($.substring(Q+1).trim(),10);return G&&Number.isInteger(X)&&X>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function yP(b){let w;try{w=JSON.parse(b)}catch{return`Poll response filters must use valid JSON. ${Tw}`}if(!y(w)||w.v!==1||typeof w.campaignId!=="string"||!w.campaignId.trim()||typeof w.blockId!=="string"||!w.blockId.trim()||!y(w.match))return`Poll response filter context is invalid. ${Tw}`;let $=w.match;if($.kind==="answer"&&typeof $.value==="string"&&$.value.length>0)return null;if($.kind==="npsBucket"&&($.bucket==="promoters"||$.bucket==="passives"||$.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${Tw}`}function y$(b){if(typeof b!=="object"||b===null)return"Segment filters must be objects.";let w=b,$=w.field,W=w.operator,Q=w.value;if(typeof $!=="string"||!($ in AW))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let G=AW[$];if(!G.includes(W))return`Operator "${W}" is not supported for ${$} filters. Use one of: ${G.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof Q!=="string"||Q.trim().length===0))return`Segment filter "${$}" must include a value.`;if($==="attribute"&&typeof Q==="string"){if(!NP(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!TP(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let X=EP(W,Q);if(X)return X}if($==="pollResponse"&&typeof Q==="string"){let X=yP(Q);if(X)return X}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof Q==="string"){let X=CP($,W,Q);if(X)return X}if($==="commerceProduct"&&typeof Q==="string"){let X=uP(W,Q);if(X)return X}if($==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof Q==="string"&&Q.split(",").map((Y)=>Y.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function h$(b){if(typeof b!=="object"||b===null)return[];let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=y$(w);return $?[$]:[]}if(Array.isArray(w.children))return w.children.flatMap(h$);return[]}function _b(b,w,$){if(w.html!==void 0&&w.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`, not both.`);if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error(`\`blocks\` must be an array when calling \`${b}\`.`);if($?.requireContent&&w.html===void 0&&w.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`.`)}function H1(b,w){if(w.labels===void 0)return;if(!Array.isArray(w.labels))throw Error(`\`labels\` must be an array when calling \`${b}\`.`);if(w.labels.some(($)=>typeof $!=="string"||$.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${b}\`.`)}function KD(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!w&&!$)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=y$(Q);return G?[G]:[]}):h$(b.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function PD(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(b.name===void 0&&b.filterJoinOperator===void 0&&!w&&!$)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=y$(Q);return G?[G]:[]}):$?h$(b.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var LW=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"];function UW(b,w,$){if(w[$]!==void 0&&!y(w[$]))throw Error(`\`${$}\` must be an object when calling \`${b}\`.`)}function BD(b,w,$){if(w[$]!==void 0&&!Array.isArray(w[$]))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`)}function MD(b){let w=new Set(["companyId",...LW]),$=Object.keys(b).filter((Q)=>!w.has(Q));if($.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${$.length===1?"":"s"}: ${$.map((Q)=>`\`${Q}\``).join(", ")}.`);let W={};for(let Q of LW)if(b[Q]!==void 0)W[Q]=b[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${LW.map((Q)=>`\`${Q}\``).join(", ")} when calling \`update_company\`.`);for(let Q of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"])if(b[Q]!==void 0&&typeof b[Q]!=="string")throw Error(`\`${Q}\` must be a string when calling \`update_company\`.`);if(UW("update_company",b,"brandColors"),UW("update_company",b,"socialLinks"),UW("update_company",b,"pricing"),BD("update_company",b,"valueProps"),BD("update_company",b,"testimonials"),typeof b.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(b.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let Q of["fromEmail","replyTo"]){let G=b[Q];if(typeof G==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G.trim()))throw Error(`\`${Q}\` must be a valid email address when calling \`update_company\`.`)}if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_company`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_company`.");return W}var ZD=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function hP(b){return ZD.some((w)=>b[w]!==void 0)}function fP(b){if(typeof b.nodeType==="string")return b.nodeType==="action_email";return b.type===void 0||b.type==="email"}function f$(b,w,$){for(let W of ZD){let Q=$[W];if(Q!==void 0&&typeof Q!=="string")throw Error(`\`${W}\` must be a string for ${w} when calling \`${b}\`.`)}if($.senderProfileId!==void 0&&$.fromEmail!==void 0)throw Error(`Provide either \`senderProfileId\` or \`fromEmail\` for ${w} when calling \`${b}\`, not both.`);if($.replyProfileId!==void 0&&$.replyTo!==void 0)throw Error(`Provide either \`replyProfileId\` or \`replyTo\` for ${w} when calling \`${b}\`, not both.`);if($.replyToName!==void 0&&$.replyTo===void 0)throw Error(`\`replyToName\` requires \`replyTo\` for ${w} when calling \`${b}\`.`)}function FW(b,w,$){if(hP($)&&!fP($))throw Error(`Sender identity fields are only supported for email steps at ${w} when calling \`${b}\`.`);f$(b,w,$)}function FD(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))f$(b,`${w}[${Q}]`,W)})}function BW(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))FW(b,`${w}[${Q}]`,W)})}function cP(b){if(FD("update_sequence","emails",b.emails),FD("update_sequence","steps",b.steps),y(b.insertSteps))BW("update_sequence","insertSteps.steps",b.insertSteps.steps);if(!y(b.branch))return;if(Array.isArray(b.branch.branches))b.branch.branches.forEach(($,W)=>{if(y($))BW("update_sequence",`branch.branches[${W}].steps`,$.steps)});BW("update_sequence","branch.elseSteps",b.branch.elseSteps)}function jD(b){if(b.fromEmail!==void 0&&b.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(b.replyTo!==void 0&&b.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(b.clearEnrollmentFieldPath===!0&&b.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(b.clearSendingWindow===!0&&b.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(b.clearBccEmails===!0&&b.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(b.branch!==void 0&&b.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");cP(b);let w={...b};if(delete w.clearEnrollmentFieldPath,delete w.clearSendingWindow,delete w.clearBccEmails,b.clearEnrollmentFieldPath===!0)w.enrollmentFieldPath=null;if(b.clearSendingWindow===!0)w.sendingWindow=null;if(b.clearBccEmails===!0)w.bccEmails=null;return w}function ID(b,w,$){let W=j(b,w,"nodeId");if(!y(w.changes)||Object.keys(w.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${b}\`.`);let Q=j(b,w,"expectedUpdatedAt");return{nodeId:W,changes:w.changes,expectedUpdatedAt:Q}}function VD(b){let w=ID("update_sequence_node",b,"the node update");return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:[w]}}function ND(b){if(!Array.isArray(b.updates)||b.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let w=new Set,$=b.updates.map((W,Q)=>{if(!y(W))throw Error(`\`updates[${Q}]\` must be an object when calling \`update_sequence_nodes\`.`);let G=ID("update_sequence_nodes",W,`updates[${Q}]`),X=String(G.nodeId);if(w.has(X))throw Error(`\`updates[${Q}]\` targets duplicate nodeId '${X}' when calling \`update_sequence_nodes\`.`);return w.add(X),G});return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:$}}function TD(b){let w=j("edit_sequence_graph",b,"action"),$=j("edit_sequence_graph",b,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(w))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let Q=F(b,"nodeId"),G=F(b,"afterNodeId"),X=F(b,"beforeNodeId"),Y=b.edges;if(w!=="replace_edges"&&!Q)throw Error(`\`nodeId\` is required for ${w} when calling \`edit_sequence_graph\`.`);if(w==="replace_edges"&&Q)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let H=w==="move_node"||w==="duplicate_node";if(H&&(G?1:0)+(X?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${w} when calling \`edit_sequence_graph\`.`);if(!H&&(G||X))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${w} when calling \`edit_sequence_graph\`.`);if((w==="replace_edges"||w==="delete_node"&&Y!==void 0)&&(!Array.isArray(Y)||Y.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${w} when calling \`edit_sequence_graph\`.`);if((w==="move_node"||w==="duplicate_node")&&Y!==void 0)throw Error(`\`edges\` is not used with ${w} when calling \`edit_sequence_graph\`.`);let J=Array.isArray(Y)?Y.map((D,z)=>{if(!y(D))throw Error(`\`edges\` item ${z+1} must be an object when calling \`edit_sequence_graph\`.`);let O=j("edit_sequence_graph",D,"sourceNodeId"),q=j("edit_sequence_graph",D,"targetNodeId");if(D.condition!==void 0&&D.condition!==null&&!y(D.condition))throw Error(`\`edges\` item ${z+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:O,targetNodeId:q,...y(D.condition)?{condition:D.condition}:{}}}):void 0;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},graphEdit:{action:w,expectedRevision:$,...Q?{nodeId:Q}:{},...G?{afterNodeId:G}:{},...X?{beforeNodeId:X}:{},...J?{edges:J}:{}}}}function ED(b){let w=b.type==="sms",$;if(w){FW("insert_sequence_step","SMS step",b);let Q=F(b,"text"),G=Array.isArray(b.blocks)&&b.blocks.length>0;if(Q===void 0&&!G)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");$={type:"sms"};for(let X of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(b[X]!==void 0)$[X]=b[X]}else{_b("insert_sequence_step",b,{requireContent:!0}),f$("insert_sequence_step","email step",b),$={subject:j("insert_sequence_step",b,"subject")};for(let Q of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"])if(b[Q]!==void 0)$[Q]=b[Q]}let W={steps:[$]};if(b.afterNodeId!==void 0)W.afterNodeId=b.afterNodeId;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},insertSteps:W}}function _D(b){let w=F(b,"subscriberId"),$=b.fieldValues,W=$===void 0?void 0:Array.isArray($)?$:void 0;if($!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let Q=W?.map((Y)=>typeof Y==="string"?Y.trim():"").filter((Y)=>Y.length>0)??[];if(W?.some((Y)=>typeof Y!=="string")||W!==void 0&&Q.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(w!==void 0===Q.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let G=F(b,"fieldPath"),X=F(b,"reason");return{...w!==void 0&&{subscriberId:w},...G!==void 0&&{fieldPath:G},...Q.length>0&&{fieldValues:Q},...typeof b.dryRun==="boolean"&&{dryRun:b.dryRun},...X!==void 0&&{reason:X}}}function SD(b){_b("create_campaign",b),H1("create_campaign",b);let w=F(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0,Q=b.templateId!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(w&&($||W||Q))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!w&&F(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function RD(b){_b("create_template",b),H1("create_template",b);let w=F(b,"prompt")!==void 0,$=[w,b.html!==void 0,b.blocks!==void 0].filter(Boolean).length;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_template`.");if($!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!w&&F(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function kD(b){if(F(b,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(b.targetLists!==void 0&&!y(b.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(b.sendTimeOptimization!==void 0){if(typeof b.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(b.spreadOverHours!==void 0){if(typeof b.spreadOverHours!=="number"||!Number.isInteger(b.spreadOverHours)||b.spreadOverHours<1||b.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(b.recurringInterval!==void 0&&b.recurringInterval!=="weekly"&&b.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function c$(b,w,$){let W=new Set(["companyId","landingPageId","name","slug","content"]),Q=Object.keys(w).filter((G)=>!W.has(G));if(Q.length>0)throw Error(`\`${b}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${Q.length===1?"":"s"}: ${Q.map((G)=>`\`${G}\``).join(", ")}.`);if($.requireUpdate&&w.name===void 0&&w.slug===void 0&&w.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${b}\`.`);return{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.content!==void 0&&{content:w.content}}}function vD(b){let w=new Set(["companyId","domain","verify"]),$=Object.keys(b).filter((W)=>!w.has(W));if($.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}.`);if(b.domain===void 0&&b.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...b.domain!==void 0&&{domain:b.domain},...typeof b.verify==="boolean"&&{verify:b.verify}}}function CD(b){_b("create_transactional_email",b);let w=F(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(w&&($||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!w&&!$&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!w&&F(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var Y0={type:"object",description:"Update Subscriber config. firstName, lastName, and customAttributeUpdates values may use trigger-event merge tags such as {{event.plan}}. Number and boolean values must be a literal or one standalone merge tag and are coerced after resolution.",properties:{label:{type:"string"},firstName:{type:["string","null"],description:"First name literal or merge tag; null clears the field."},lastName:{type:["string","null"],description:"Last name literal or merge tag; null clears the field."},status:{type:"string",enum:["active","unsubscribed","bounced"]},customAttributeUpdates:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:["string","number","boolean","null"],description:"Literal scalar, null to delete, or a standalone merge tag such as {{event.plan}}, {{event.amount}}, or {{event.active}}."},valueType:{type:"string",enum:["text","number","boolean"]}},required:["name","value"]}}},additionalProperties:!0},KW={senderProfileId:{type:"string",description:"Sender profile for this step's From identity. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"From address for this step. Its domain must be configured and verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this step. Alone it only changes the visible name; with fromEmail it also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this step's Reply-To. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Reply-To address for this step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."}},g$={type:"object",description:"A step to create inside a sequence path. Use type:'delay' for a standalone delay, type:'email' for an email, type:'create_discount' for a discount action, or type:'condition' for a condition gate.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","update_subscriber","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for standalone waits or update_subscriber for action_update_attributes."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","logic_condition","action_webhook"],description:"Advanced sequence path node type. Prefer type unless creating a non-email action."},config:{...Y0,description:"Config for advanced nodeType steps. For action_update_attributes, use the documented Update Subscriber fields and trigger-event merge tags; other node types accept their normal config fields.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:W1,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},delay:G1,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:Q1,name:{type:"string",description:"Email template name for email steps."},senderProfileId:{type:"string",description:"Sender profile for this email step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"From address for this email step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this email step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this email step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},replyTo:{type:"string",description:"Reply-To address for this email step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1};function xD(b){if(!b||typeof b!=="object")return null;let w=b;if(w.success!==!1)return null;if(typeof w.error==="string")return Error(w.error);if(w.error&&typeof w.error==="object"&&typeof w.error.message==="string")return Error(w.error.message);if(typeof w.message==="string")return Error(w.message);return Error("The tool returned an unsuccessful response.")}function PW(b){return b.trim().toLowerCase().replace(/\s+/g,"-")}function gP(b){let w=new URLSearchParams;if(typeof b.query==="string"&&b.query.trim()!=="")w.set("query",b.query.trim());if(Array.isArray(b.tags)&&b.tags.length>0)w.set("tags",b.tags.filter(($)=>typeof $==="string"&&$.trim()!=="").join(","));if(typeof b.list==="string"&&b.list.trim()!=="")w.set("list",b.list.trim());if(typeof b.listId==="string"&&b.listId.trim()!=="")w.set("listId",b.listId.trim());if(typeof b.listName==="string"&&b.listName.trim()!=="")w.set("listName",b.listName.trim());if(typeof b.segmentId==="string"&&b.segmentId.trim()!=="")w.set("segmentId",b.segmentId);if(typeof b.status==="string"&&b.status.trim()!=="")w.set("status",b.status.trim());return w.set("page",String(b.page)),w.set("limit",String(b.pageSize)),w}async function yD(b,w){let $=typeof b.limit==="number"&&Number.isFinite(b.limit)?Math.max(1,Math.trunc(b.limit)):void 0,W=Math.min(100,Math.max(1,$??100)),Q=[],G=1,X=0,Y=0,H=0;while(!0){let D=gP({query:b.query,tags:b.tags,list:b.list,listId:b.listId,listName:b.listName,segmentId:b.segmentId,status:b.status,page:G,pageSize:W}),z=await A("GET",`/api/v1/subscribers?${D.toString()}`,void 0,w);X=z.pagination?.total??z.subscribers.length,Y=z.pagination?.totalPages??1,H+=1,Q.push(...z.subscribers??[]);let O=$!==void 0&&Q.length>=$,q=z.pagination?G>=z.pagination.totalPages:(z.subscribers??[]).length<W;if(O||q)break;G+=1}let J=$!==void 0?Q.slice(0,$):Q;return{success:!0,subscribers:J,pagination:{page:1,limit:W,total:X,totalPages:Y,fetchedPages:H},returned:J.length,truncated:$!==void 0&&X>0&&J.length<X}}function mP(b){let w=typeof b.email==="string"&&b.email.trim()!==""?b.email.trim():void 0,$=typeof b.externalId==="string"&&b.externalId.trim()!==""?b.externalId.trim():void 0;return{...w?{email:w}:{},...$?{externalId:$}:{}}}function Aw(b,w){let $=mP(w);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${b}\`.`);return $}function m$(b,w){let $=new URLSearchParams;if(w?.includeMachineEngagement)$.set("includeMachineEngagement","true");let W=$.toString(),Q=W?`?${W}`:"";if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}${Q}`;return $.set("externalId",String(b.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function MW(b){if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}/notes`;let w=new URLSearchParams;return w.set("externalId",String(b.externalId)),`/api/v1/subscribers/external/notes?${w.toString()}`}async function H0(b,w,$){return A("GET",m$(b,$),void 0,w)}function Vb(b,w,$,W){let Q=F(w,$);if(Q===void 0)return;if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function J0(b,w,$,W){let Q=j(b,w,$);if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function zw(b,w,$,W,Q){let G=w[$];if(G===void 0)return;if(typeof G!=="number"||!Number.isInteger(G)||G<W||G>Q)throw Error(`\`${$}\` must be an integer between ${W} and ${Q} when calling \`${b}\`.`);return G}function nP(b,w){let $=[],W=Vb(b,w,"eventType",k$);if(W)$.push(W);if(w.eventTypes!==void 0){if(!Array.isArray(w.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${b}\`.`);w.eventTypes.forEach((Q,G)=>{if(typeof Q!=="string")throw Error(`\`eventTypes\` item ${G+1} must be a string when calling \`${b}\`.`);let X=Q.trim();if(!k$.includes(X))throw Error(`\`eventTypes\` item ${G+1} must be one of ${k$.join(", ")} when calling \`${b}\`.`);$.push(X)})}return[...new Set($)]}function ZW(b,w){let $=new URLSearchParams,W=nP(b,w);if(W.length>0)$.set("eventTypes",W.join(","));let Q=Vb(b,w,"period",["1h","24h","7d","30d","90d"]);if(Q)$.set("period",Q);let G=F(w,"start");if(G)$.set("start",G);let X=F(w,"end");if(X)$.set("end",X);let Y=zw(b,w,"page",1,1e6);if(Y!==void 0)$.set("page",String(Y));let H=zw(b,w,"limit",1,500);if(H!==void 0)$.set("limit",String(H));if(w.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function jW(b,w){if(w.events===void 0)return;if(!Array.isArray(w.events))throw Error(`\`events\` must be an array when calling \`${b}\`.`);let $=w.events.map((W,Q)=>{if(typeof W!=="string"||!Y1.includes(W))throw Error(`\`events\` item ${Q+1} must be one of ${Y1.join(", ")} when calling \`${b}\`.`);return W});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${b}\`.`);return $}function IW(b,w){if(!Array.isArray(w.emails))throw Error(`\`emails\` must be an array when calling \`${b}\`.`);let $=[];if(w.emails.forEach((W,Q)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${Q+1} must be a string when calling \`${b}\`.`);let G=W.trim();if(G.length>0)$.push(G)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${b}\`.`);if($.length>JW)throw Error(`\`emails\` must include no more than ${JW} email addresses when calling \`${b}\`. Split larger batches into multiple calls.`);return $}function uD(b,w,$,W){let Q=w[$];if(Q===void 0)return;if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`);let G=[];if(Q.forEach((X,Y)=>{if(typeof X!=="string")throw Error(`\`${$}\` item ${Y+1} must be a string when calling \`${b}\`.`);let H=X.trim();if(H.length>0)G.push(H)}),G.length===0)throw Error(`\`${$}\` must include at least one ${W} when calling \`${b}\`.`);return G}function hD(b){let $=uD("enroll_subscribers_in_sequence",b,"emails","email address"),W=uD("enroll_subscribers_in_sequence",b,"subscriberIds","subscriber ID"),Q=($?.length??0)+(W?.length??0);if(Q===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(Q>DW)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${DW} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let G=F(b,"targetNodeId");return{...$!==void 0&&{emails:$},...W!==void 0&&{subscriberIds:W},...G!==void 0&&{targetNodeId:G}}}import{readFileSync as lP,statSync as iP}from"node:fs";import{basename as pP}from"node:path";var oP={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function dP(b){let w=b.split(".").pop()?.toLowerCase()??"";return oP[w]??null}var tP=104857600;async function fD(b,w){if(!z0())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let $=dP(b);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=iP(b).size;if(W>tP)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=lP(b),G=await A("POST","/api/v1/products/delivery/upload-url",{filename:pP(b),contentType:$,fileSizeBytes:W},w),X=await fetch(G.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:Q});if(!X.ok)throw Error(`File upload failed (${X.status})`);return{url:G.publicUrl,fileName:G.fileName,fileSizeBytes:W,mimeType:$}}async function n$(b){let w=F(b,"companyId");if(w)return w;let $=Ew();if($)return $;try{return(await A("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function cD(b,w){let $=await n$(w);if(!$)throw Error(`A company is required when calling \`${b}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function J1(b,w){if(!y(b)||!w)return b;return{...b,url:w}}function gD(b,w){if(!y(b))return b;return{...b,...w.campaign!==void 0&&{url:w.campaign},...w.campaignPreview!==void 0&&{previewUrl:w.campaignPreview}}}function D0(b,w,$){if(!Array.isArray(b)||!w)return b;return b.map((W)=>{if(!y(W))return W;let Q=F(W,"id");if(!Q)return W;let G=Hw({companyId:w,...$==="campaign"&&{campaignId:Q},...$==="landingPage"&&{landingPageId:Q},...$==="sequence"&&{sequenceId:Q},...$==="template"&&{emailId:Q},...$==="transactional"&&{transactionalId:Q}});if($==="campaign")return gD(W,G.urls);let X=$==="sequence"?G.urls.sequence:$==="landingPage"?G.urls.landingPage:$==="template"?G.urls.email:G.urls.transactionalEmail;return J1(W,X)})}function rP(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(!y(w))return w;let $=F(w,"id");if(!$)return w;let W=Hw({companyId:$});return{...w,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var VW=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","set_template_localization","sync_template_localizations","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function mD(b,w,$){if(!y($)||!VW.has(b))return $;let W=y($.company)?$.company:void 0,G=F($,"selectedCompanyId")??F($,"currentCompanyId")??F($,"companyId")??(W?F(W,"id"):void 0)??(W?F(W,"companyId"):void 0)??await n$(w);if(!G)return $;let X=y($.campaign)?$.campaign:void 0,Y=y($.sequence)?$.sequence:void 0,H=y($.landingPage)?$.landingPage:void 0,J=y($.template)?$.template:void 0,D=y($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,z={companyId:G,campaignId:F(w,"campaignId")??F($,"campaignId")??(X?F(X,"id"):void 0),landingPageId:F(w,"landingPageId")??F($,"landingPageId")??(H?F(H,"id"):void 0),sequenceId:F(w,"sequenceId")??F($,"sequenceId")??(Y?F(Y,"id"):void 0),emailId:F($,"templateId")??(J?F(J,"id"):void 0)??(D?F(D,"emailId"):void 0)??F(w,"templateId"),transactionalId:F(w,"transactionalId")??(D?F(D,"id"):void 0)??F(w,"idOrSlug"),emailSendId:F(w,"emailSendId")??F($,"emailSendId")??(y($.emailSend)?F($.emailSend,"id"):void 0),status:F(w,"status")},O=Hw(z),q=W?Hw({companyId:G}):void 0;return{...$,...Array.isArray($.companies)&&{companies:rP($.companies)},...Array.isArray($.campaigns)&&{campaigns:D0($.campaigns,G,"campaign")},...Array.isArray($.landingPages)&&{landingPages:D0($.landingPages,G,"landingPage")},...Array.isArray($.sequences)&&{sequences:D0($.sequences,G,"sequence")},...Array.isArray($.templates)&&{templates:D0($.templates,G,"template")},...Array.isArray($.transactional)&&{transactional:D0($.transactional,G,"transactional")},...W&&q!==void 0&&{company:{...W,url:q.urls.dashboard,settingsUrl:q.urls.settings}},...X&&O.urls.campaign!==void 0&&{campaign:gD(X,O.urls)},...Y&&O.urls.sequence!==void 0&&{sequence:J1(Y,O.urls.sequence)},...H&&O.urls.landingPage!==void 0&&{landingPage:J1(H,O.urls.landingPage)},...J&&O.urls.email!==void 0&&{template:J1(J,O.urls.email)},...D&&O.urls.transactionalEmail!==void 0&&{transactional:J1(D,O.urls.transactionalEmail)},...y($.emailSend)&&O.urls.emailSend!==void 0&&{emailSend:J1($.emailSend,O.urls.emailSend)},appUrls:O.urls}}import{readFileSync as eP,statSync as sP}from"node:fs";import{basename as aP,extname as lD}from"node:path";var TW=5242880,bM=Math.ceil(TW/3)*4,wM=Math.ceil(bM*1.05)+256,iD={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},$M=new Set(Object.values(iD));function NW(b){return b?.split(";")[0]?.trim().toLowerCase()||void 0}function WM(b){return iD[lD(b).toLowerCase()]}function QM(b){let w=lD(b);return(w?b.slice(0,-w.length):b).replace(/[-_]+/g," ").trim()||"Image"}function GM(b){if(b.length>wM)throw Error("Image assets must be 5MB or smaller.")}function XM(b){let w=0,$=0;for(let Q=0;Q<b.length;Q+=1){let G=b.charCodeAt(Q);if(G===9||G===10||G===11||G===12||G===13||G===32)continue;w+=1,$=G===61?$+1:0}if(Math.floor(w*3/4)-Math.min($,2)>TW)throw Error("Image assets must be 5MB or smaller.")}function YM(b){GM(b);let w=b.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(w),W=$?.[2]??w;XM(W);let Q=W.replace(/\s+/g,"");if(Q.length===0||Q.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(Q))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(Q,"base64"),...$?.[1]?{dataUrlContentType:NW($[1])}:{}}}function nD(b){if(b<=0)throw Error("The image file is empty.");if(b>TW)throw Error("Image assets must be 5MB or smaller.")}function HM(b){let w=WM(b.filename)??NW(b.explicitContentType)??NW(b.dataUrlContentType);if(!w||!$M.has(w))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return w}function JM(b){let w,$,W;if(b.filePath!==void 0){if(!z0())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. For a remote MCP connection, pass `imageBase64` and `filename` instead.");let G=sP(b.filePath).size;nD(G),w=eP(b.filePath),$=b.filename??aP(b.filePath)}else{if(!b.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!b.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let G=YM(b.imageBase64);w=G.bytes,W=G.dataUrlContentType,$=b.filename,nD(w.byteLength)}let Q=HM({filename:$,explicitContentType:b.contentType,dataUrlContentType:W});return{bytes:w,filename:$,contentType:Q,altText:b.altText??QM($)}}async function pD(b){let w=JM(b),$=w.bytes.byteLength,W=await A("POST","/api/v1/media/upload-url",{filename:w.filename,contentType:w.contentType,fileSizeBytes:$},b.companyId);return await cW(W.uploadUrl,w.bytes,w.contentType,b.companyId),(await A("POST","/api/v1/media/complete-upload",{key:W.key,filename:W.fileName,contentType:w.contentType,fileSizeBytes:$,...b.sourceWidth!==void 0&&{width:b.sourceWidth},...b.sourceHeight!==void 0&&{height:b.sourceHeight},altText:w.altText},b.companyId)).asset}var DM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},zM={type:"string",description:"Human-readable status, confirmation, or next-step message."},AM={type:"string",description:"Additional context about the result."};function t(b){return{type:"object",description:b,additionalProperties:!0}}function OM(b){return{type:"array",description:b,items:t("One item in the returned collection.")}}function N(b){return{type:"string",description:b}}function Kb(b){return{type:"number",description:b}}function ib(b){return{type:"boolean",description:b}}function P(b){return t(`The ${b} record returned by Sequenzy.`)}function p(b){return OM(`List of ${b} records returned by Sequenzy.`)}var qM={appUrls:t("Dashboard URLs for relevant Sequenzy resources."),url:N("Primary dashboard URL for this result."),settingsUrl:N("Company settings URL when available.")},LM={success:DM,message:zM,note:AM,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:t("One returned item.")},value:t("Fallback object wrapper used only when a tool returns a non-object value.")},UM={get_account:{account:P("account"),companies:p("company"),apiKeyPermissions:t("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:N("Company ID selected by the authenticated API key, when available."),selectedCompanyId:N("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:N("Selected company ID."),companyName:N("Selected company name.")},get_app_urls:{dashboard:N("Company dashboard URL."),settings:N("Company settings URL."),campaign:N("Campaign editor URL."),landingPage:N("Landing page editor URL."),sequence:N("Sequence editor URL."),email:N("Email editor URL."),transactionalEmail:N("Transactional email URL."),emailSend:N("Sent email detail URL."),domain:N("Sending domain settings URL."),urls:t("All generated URLs keyed by resource type.")},create_company:{company:P("company"),autoSelected:ib("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:P("company")},get_company:{company:P("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:t("One sync rule.")},isDefault:ib("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:t("One sync rule.")},isDefault:ib("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:t("Effective browse-abandonment settings (defaults applied)."),priceDrop:t("Effective price-drop settings (defaults applied)."),shopDomain:N("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:t("Effective browse-abandonment settings after the update."),priceDrop:t("Effective price-drop settings after the update."),shopDomain:N("Connected Shopify store domain.")},create_api_key:{apiKey:t("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:N("Newly created API key if the API response uses the short key field.")},list_websites:{websites:p("sender website")},add_website:{website:P("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:P("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:P("sender website"),ready:ib("Whether the sender website is ready."),status:N("Current processing or verification status.")},verify_sending_domain:{website:P("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:ib("Whether the sending domain passed the fresh verification check."),message:N("Verification result summary.")},get_integration_guide:{guide:P("integration guide"),code:N("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:t("One setup step.")}},add_subscriber:{subscriber:P("subscriber")},update_subscriber:{subscriber:P("subscriber")},remove_subscriber:{subscriber:P("subscriber"),hardDeleted:ib("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:P("subscriber")},list_subscriber_notes:{notes:p("subscriber note")},add_subscriber_note:{note:P("subscriber note")},delete_subscriber_note:{id:N("Deleted subscriber note ID."),deleted:ib("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:p("subscriber"),pagination:t("Pagination metadata."),returned:Kb("Number of subscribers returned."),truncated:ib("Whether the result was truncated by the requested limit.")},list_products:{products:p("product")},upsert_products:{products:p("product"),created:Kb("Number of products created."),updated:Kb("Number of products updated.")},delete_product:{productId:N("Deleted product ID.")},attach_product_file:{product:P("product"),delivery:P("digital delivery file")},remove_product_file:{product:P("product")},upload_image_asset:{asset:P("hosted image asset"),imageBlock:t("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:P("product sync job"),jobId:N("Queued product sync job ID.")},list_tags:{tags:p("tag")},create_tag:{tag:P("tag")},update_tag:{tag:P("tag")},delete_tag:{tagId:N("Deleted tag ID.")},list_lists:{lists:p("list")},create_list:{list:P("list")},update_list:{list:P("list")},delete_list:{listId:N("Deleted list ID.")},add_subscribers_to_list:{list:P("list"),added:Kb("Number of subscribers added to the list."),skipped:Kb("Number of subscribers skipped.")},remove_subscribers_from_list:{list:P("list"),removed:Kb("Number of subscribers removed from the list."),skipped:Kb("Number of subscribers skipped.")},list_segments:{segments:p("segment")},create_segment:{segment:P("segment")},update_segment:{segment:P("segment")},delete_segment:{segmentId:N("Deleted segment ID.")},get_segment_count:{count:Kb("Number of subscribers matching the segment."),segmentId:N("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:p("audience sync")},list_ad_accounts:{adAccounts:p("ad account")},create_audience_sync:{audienceSync:P("audience sync")},update_audience_sync:{audienceSync:P("audience sync")},delete_audience_sync:{audienceSyncId:N("Deleted audience sync ID.")},sync_audience_now:{audienceSync:P("audience sync"),job:P("audience sync job"),jobId:N("Queued audience sync job ID.")},list_templates:{templates:p("email template")},get_template:{template:P("email template")},create_template:{template:P("email template")},update_template:{template:P("email template")},set_template_localization:{templateId:N("Localized template ID."),localization:P("template localization")},sync_template_localizations:{templateId:N("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:N("One queued locale code.")},queuedVariantCount:Kb("Number of localized variants queued for translation.")},delete_template:{templateId:N("Deleted template ID.")},list_ab_tests:{abTests:p("A/B test")},get_ab_test:{abTest:P("A/B test")},get_ab_test_stats:{abTest:P("A/B test"),stats:P("A/B test statistics")},restart_ab_test:{abTest:P("A/B test")},update_ab_test_variant:{abTest:P("A/B test"),variant:P("A/B test variant")},create_ab_test:{abTest:P("A/B test")},add_ab_test_variant:{abTest:P("A/B test"),variant:P("A/B test variant")},delete_ab_test_variant:{abTest:P("A/B test"),variantId:N("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:N("Deleted A/B test ID.")},list_campaigns:{campaigns:p("campaign")},get_campaign:{campaign:P("campaign")},get_email_send:{emailSend:P("email send")},create_campaign:{campaign:P("campaign")},update_campaign:{campaign:P("campaign")},schedule_campaign:{campaign:P("campaign"),scheduledAt:N("Scheduled send timestamp.")},send_test_email:{emailSend:P("test email send"),recipient:N("Test email recipient.")},send_test_sms:{smsSendId:N("Created test SMS send ID."),toPhone:N("Normalized E.164 destination phone.")},cancel_campaign:{campaign:P("campaign")},pause_campaign:{campaign:P("campaign")},resume_campaign:{campaign:P("campaign")},delete_campaign:{campaignId:N("Deleted campaign ID.")},duplicate_campaign:{campaign:P("duplicated campaign")},resend_campaign_to_non_openers:{campaign:P("non-opener resend draft campaign"),estimatedNonOpenerCount:Kb("Estimated number of subscribers who haven't opened the original campaign.")},list_landing_pages:{landingPages:p("landing page")},get_landing_page:{landingPage:P("landing page")},create_landing_page:{landingPage:P("landing page")},update_landing_page:{landingPage:P("landing page")},delete_landing_page:{landingPageId:N("Deleted landing page ID.")},publish_landing_page:{landingPage:P("landing page")},unpublish_landing_page:{landingPage:P("landing page")},connect_landing_page_domain:{landingPage:P("landing page"),domain:N("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:P("landing page"),domain:N("Landing page domain.")},list_sequences:{sequences:p("sequence")},get_sequence:{sequence:P("sequence")},create_sequence:{sequence:P("sequence"),eventTrackingCode:N("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:t("Custom-event endpoint, payload contract, example payload, documentation URL, and get_integration_guide arguments."),requiredEvents:{type:"array",description:"Event names the application or an integration must send.",items:N("One required event name.")}},update_sequence:{sequence:P("sequence")},update_sequence_node:{sequence:P("sequence")},update_sequence_nodes:{sequence:P("sequence")},edit_sequence_graph:{sequence:P("sequence")},insert_sequence_step:{sequence:P("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:N("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:N("Inserted email template ID.")},insertedEmailCount:Kb("Number of email steps inserted.")},enable_sequence:{sequence:P("sequence")},disable_sequence:{sequence:P("sequence")},pause_sequence_enrollments:{sequenceId:N("Sequence ID."),enrollmentPaused:ib("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:N("Sequence ID."),enrollmentPaused:ib("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:P("sequence"),enrollments:p("sequence enrollment"),enrolled:Kb("Number of subscribers enrolled."),skipped:Kb("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:P("sequence"),cancelled:Kb("Number of enrollments cancelled."),skipped:Kb("Number of enrollments skipped.")},delete_sequence:{sequenceId:N("Deleted sequence ID.")},list_transactional_emails:{transactional:p("transactional email")},get_transactional_email:{transactional:P("transactional email")},create_transactional_email:{transactional:P("transactional email")},update_transactional_email:{transactional:P("transactional email")},send_email:{emailSend:P("transactional email send"),transactional:P("transactional email")},get_stats:{stats:P("account or company statistics")},get_campaign_stats:{campaign:P("campaign"),stats:P("campaign statistics"),clickedLinks:{type:"array",description:"Per-link click breakdown, most clicked first (top 20). Each entry has url, clicks, and percentage (that link's share of every recorded link click). Present only when the campaign has tracked link clicks.",items:t("One clicked link with url/clicks/share.")},polls:{type:"array",description:`Poll and NPS summaries. Each subscriber counts once per campaign poll block using their latest answer to that block; NPS entries include score, average, and promoter/passive/detractor counts. To list the exact historical respondents behind a count, use the summary blockId and the get_campaign_stats campaignId with create_segment. ${Tw} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response and may be overwritten by a later poll that reuses the key.`,items:t("One poll or NPS results summary.")}},get_sequence_stats:{sequence:P("sequence"),stats:P("sequence statistics")},list_campaign_events:{events:p("campaign email event"),pagination:t("Pagination metadata.")},list_sequence_events:{events:p("sequence email event"),pagination:t("Pagination metadata.")},get_subscriber_activity:{activity:p("subscriber activity event"),subscribers:p("subscriber"),pagination:t("Pagination metadata.")},list_team_members:{members:p("team member"),invitations:p("team invitation")},invite_team_member:{invitation:P("team invitation")},cancel_team_invitation:{invitationId:N("Cancelled invitation ID.")},list_conversations:{conversations:p("inbox conversation"),pagination:t("Pagination metadata.")},get_conversation:{conversation:P("inbox conversation"),messages:p("conversation message")},reply_to_conversation:{conversation:P("inbox conversation"),message:P("conversation message")},update_conversation_status:{conversation:P("inbox conversation")},mark_conversation_read:{conversation:P("inbox conversation")},list_webhooks:{webhooks:p("outbound webhook")},create_webhook:{webhook:P("outbound webhook")},update_webhook:{webhook:P("outbound webhook")},delete_webhook:{webhookId:N("Deleted outbound webhook ID.")},test_webhook:{webhook:P("outbound webhook"),delivery:P("test webhook delivery")},list_webhook_deliveries:{deliveries:p("webhook delivery")},replay_webhook_delivery:{delivery:P("webhook delivery"),job:P("webhook replay job")},generate_email:{email:P("generated email"),html:N("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:t("One generated email block.")},subject:N("Generated subject line."),previewText:N("Generated inbox preview text.")},generate_sequence:{sequence:P("persisted AI-generated sequence draft"),deprecated:ib("Always true for this deprecated alias."),deprecationMessage:N("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:N("One generated subject line.")},variants:p("generated subject line variant")},generate_sms:{prompt:N("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:t("One generated SMS message.")}},get_sms_settings:{sms:t("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function BM(b){let w=UM[b];if(w===void 0)throw Error(`MCP tool "${b}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${b}\` MCP tool.`,properties:{...LM,...w,...VW.has(b)?qM:{}},additionalProperties:!0}}function oD(b){return{...b,outputSchema:BM(b.name)}}function dD(b){if(y(b))return b;if(Array.isArray(b))return{items:b};return{value:b}}var tD=[{name:"list_ab_tests",description:"List A/B tests and their variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Optional sequence ID to filter automation A/B tests."}}}},{name:"get_ab_test",description:"Get A/B test details, variants, and per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"}},required:["abTestId"]}},{name:"get_ab_test_stats",description:"Get A/B test aggregate stats and per-variant stats. Supports period or custom start/end ranges.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},period:{type:"string",description:"Optional period: 1h, 24h, 7d, 30d, or 90d."},start:{type:"string",description:"Custom range start as ISO 8601. Requires end."},end:{type:"string",description:"Custom range end as ISO 8601. Requires start."},includeMachineEngagement:lb},required:["abTestId"]}},{name:"restart_ab_test",description:"Run another sequence A/B test after a winner is selected. By default the winner becomes the new control; pass sourceVariantId to use another variant as the control email.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to restart"},sourceVariantId:{type:"string",description:"Optional variant ID to use as the new control email. Defaults to the selected winner."},testType:{type:"string",description:"Optional test type: subject or content."},winnerThreshold:{type:"number",description:"Optional number of subscribers before selecting a winner. Must be from 10 to 1000."},variantCount:{type:"number",description:"Optional total variants including the control. Must be from 2 to 4."}},required:["abTestId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update a draft A/B test variant. Provide at least one of subject, previewText, html, or blocks. Use either html or blocks, not both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID"},subject:{type:"string",description:"Variant subject line"},previewText:{type:"string",description:"Variant preview text. Pass an empty string to clear it."},html:{type:"string",description:"Replacement HTML body. Mutually exclusive with blocks."},blocks:{type:"array",description:`${Dw} Mutually exclusive with html.`,items:{type:"object"}}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test. Control variant A is created automatically from the campaign's current email; optionally provide extra variants. The campaign must be in draft or rejected status, and each campaign can only have one A/B test.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Draft campaign ID to create the A/B test for."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Percentage of the audience used for the test phase, from 5 to 50. Defaults to 20."},testDurationMinutes:{type:"number",description:"Test phase duration in minutes before the winner is selected, from 15 to 1440. Defaults to 240."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Defaults to open_rate."},variants:{type:"array",description:"Optional extra variants to create in addition to control variant A.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Dw,items:{type:"object"}}},required:["subject"]}}},required:["campaignId"]}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign A/B test. Variants cannot be added after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Dw,items:{type:"object"}}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign A/B test. This cannot be undone. Variant A is the control and cannot be deleted, and the test must keep at least the minimum number of variants. Variants cannot be removed after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID to delete."}},required:["abTestId","variantId"]}},{name:"delete_ab_test",description:"Permanently delete a campaign A/B test and all of its variants. This cannot be undone. Running tests (testing or winner_selected) cannot be deleted, and the linked campaign must be in draft or rejected status.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to delete."}},required:["abTestId"]}}];var rD=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. IMPORTANT: If you have access to multiple companies, you MUST either:
28
+ `)}q.write("payload.value = newResult;"),q.write("return payload;");let v=q.compile();return(S,h)=>v(O,S,h)},G,D=_w,X=!A0.jitless,H=X&&a$.value,J=w.catchall,z;b._zod.parse=(O,q)=>{z??(z=W.value);let B=O.value;if(!D(B))return O.issues.push({expected:"object",code:"invalid_type",input:B,inst:b}),O;if(X&&H&&q?.async===!1&&q.jitless!==!0){if(!G)G=Q(w.shape);if(O=G(O,q),!J)return O;return u9([],B,O,q,z,b)}return $(O,q)}});function eQ(b,w,$,W){for(let G of b)if(G.issues.length===0)return w.value=G.value,w;let Q=b.filter((G)=>!Uw(G));if(Q.length===1)return w.value=Q[0].value,Q[0];return w.issues.push({code:"invalid_union",input:w.value,inst:$,errors:b.map((G)=>G.issues.map((D)=>yb(D,W,Rb())))}),w}var z4=U("$ZodUnion",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),d(b._zod,"optout",()=>w.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),d(b._zod,"values",()=>{if(w.options.every((Q)=>Q._zod.values))return new Set(w.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),d(b._zod,"pattern",()=>{if(w.options.every((Q)=>Q._zod.pattern)){let Q=w.options.map((G)=>G._zod.pattern);return new RegExp(`^(${Q.map((G)=>L1(G.source)).join("|")})$`)}return});let $=w.options.length===1,W=w.options[0]._zod.run;b._zod.parse=(Q,G)=>{if($)return W(Q,G);let D=!1,X=[];for(let Y of w.options){let H=Y._zod.run({value:Q.value,issues:[]},G);if(H instanceof Promise)X.push(H),D=!0;else{if(H.issues.length===0)return H;X.push(H)}}if(!D)return eQ(X,Q,b,G);return Promise.all(X).then((Y)=>{return eQ(Y,Q,b,G)})}}),y9=U("$ZodDiscriminatedUnion",(b,w)=>{z4.init(b,w);let $=b._zod.parse;d(b._zod,"propValues",()=>{let Q={};for(let G of w.options){let D=G._zod.propValues;if(!D||Object.keys(D).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(G)}"`);for(let[X,Y]of Object.entries(D)){if(!Q[X])Q[X]=new Set;for(let H of Y)Q[X].add(H)}}return Q});let W=fw(()=>{let Q=w.options,G=new Map;for(let D of Q){let X=D._zod.propValues?.[w.discriminator];if(!X||X.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(D)}"`);for(let Y of X){if(G.has(Y))throw Error(`Duplicate discriminator value "${String(Y)}"`);G.set(Y,D)}}return G});b._zod.parse=(Q,G)=>{let D=Q.value;if(!_w(D))return Q.issues.push({code:"invalid_type",expected:"object",input:D,inst:b}),Q;let X=W.value.get(D?.[w.discriminator]);if(X)return X._zod.run(Q,G);if(w.unionFallback)return $(Q,G);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:w.discriminator,input:D,path:[w.discriminator],inst:b}),Q}}),h9=U("$ZodIntersection",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value,G=w.left._zod.run({value:Q,issues:[]},W),D=w.right._zod.run({value:Q,issues:[]},W);if(G instanceof Promise||D instanceof Promise)return Promise.all([G,D]).then(([Y,H])=>{return sQ($,Y,H)});return sQ($,G,D)}});function H4(b,w){if(b===w)return{valid:!0,data:b};if(b instanceof Date&&w instanceof Date&&+b===+w)return{valid:!0,data:b};if(Lw(b)&&Lw(w)){let $=Object.keys(w),W=Object.keys(b).filter((G)=>$.indexOf(G)!==-1),Q={...b,...w};for(let G of W){let D=H4(b[G],w[G]);if(!D.valid)return{valid:!1,mergeErrorPath:[G,...D.mergeErrorPath]};Q[G]=D.data}return{valid:!0,data:Q}}if(Array.isArray(b)&&Array.isArray(w)){if(b.length!==w.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let W=0;W<b.length;W++){let Q=b[W],G=w[W],D=H4(Q,G);if(!D.valid)return{valid:!1,mergeErrorPath:[W,...D.mergeErrorPath]};$.push(D.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function sQ(b,w,$){if(w.issues.length)b.issues.push(...w.issues);if($.issues.length)b.issues.push(...$.issues);if(Uw(b))return b;let W=H4(w.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return b.value=W.data,b}var f9=U("$ZodRecord",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Lw(Q))return $.issues.push({expected:"record",code:"invalid_type",input:Q,inst:b}),$;let G=[];if(w.keyType._zod.values){let D=w.keyType._zod.values;$.value={};for(let Y of D)if(typeof Y==="string"||typeof Y==="number"||typeof Y==="symbol"){let H=w.valueType._zod.run({value:Q[Y],issues:[]},W);if(H instanceof Promise)G.push(H.then((J)=>{if(J.issues.length)$.issues.push(...ww(Y,J.issues));$.value[Y]=J.value}));else{if(H.issues.length)$.issues.push(...ww(Y,H.issues));$.value[Y]=H.value}}let X;for(let Y in Q)if(!D.has(Y))X=X??[],X.push(Y);if(X&&X.length>0)$.issues.push({code:"unrecognized_keys",input:Q,inst:b,keys:X})}else{$.value={};for(let D of Reflect.ownKeys(Q)){if(D==="__proto__")continue;let X=w.keyType._zod.run({value:D,issues:[]},W);if(X instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(X.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:X.issues.map((H)=>yb(H,W,Rb())),input:D,path:[D],inst:b}),$.value[X.value]=X.value;continue}let Y=w.valueType._zod.run({value:Q[D],issues:[]},W);if(Y instanceof Promise)G.push(Y.then((H)=>{if(H.issues.length)$.issues.push(...ww(D,H.issues));$.value[X.value]=H.value}));else{if(Y.issues.length)$.issues.push(...ww(D,Y.issues));$.value[X.value]=Y.value}}}if(G.length)return Promise.all(G).then(()=>$);return $}});var c9=U("$ZodEnum",(b,w)=>{e.init(b,w);let $=e$(w.entries),W=new Set($);b._zod.values=W,b._zod.pattern=new RegExp(`^(${$.filter((Q)=>b4.has(typeof Q)).map((Q)=>typeof Q==="string"?bw(Q):Q.toString()).join("|")})$`),b._zod.parse=(Q,G)=>{let D=Q.value;if(W.has(D))return Q;return Q.issues.push({code:"invalid_value",values:$,input:D,inst:b}),Q}}),n9=U("$ZodLiteral",(b,w)=>{if(e.init(b,w),w.values.length===0)throw Error("Cannot create literal schema with no valid values");b._zod.values=new Set(w.values),b._zod.pattern=new RegExp(`^(${w.values.map(($)=>typeof $==="string"?bw($):$?bw($.toString()):String($)).join("|")})$`),b._zod.parse=($,W)=>{let Q=$.value;if(b._zod.values.has(Q))return $;return $.issues.push({code:"invalid_value",values:w.values,input:Q,inst:b}),$}});var g9=U("$ZodTransform",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);let Q=w.transform($.value,$);if(W.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((D)=>{return $.value=D,$});if(Q instanceof Promise)throw new ab;return $.value=Q,$}});function aQ(b,w){if(b.issues.length&&w===void 0)return{issues:[],value:void 0};return b}var m9=U("$ZodOptional",(b,w)=>{e.init(b,w),b._zod.optin="optional",b._zod.optout="optional",d(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),d(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${L1($.source)})?$`):void 0}),b._zod.parse=($,W)=>{if(w.innerType._zod.optin==="optional"){let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>aQ(G,$.value));return aQ(Q,$.value)}if($.value===void 0)return $;return w.innerType._zod.run($,W)}}),i9=U("$ZodNullable",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),d(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${L1($.source)}|null)$`):void 0}),d(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),b._zod.parse=($,W)=>{if($.value===null)return $;return w.innerType._zod.run($,W)}}),l9=U("$ZodDefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)return $.value=w.defaultValue,$;let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>b9(G,w));return b9(Q,w)}});function b9(b,w){if(b.value===void 0)b.value=w.defaultValue;return b}var p9=U("$ZodPrefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)$.value=w.defaultValue;return w.innerType._zod.run($,W)}}),o9=U("$ZodNonOptional",(b,w)=>{e.init(b,w),d(b._zod,"values",()=>{let $=w.innerType._zod.values;return $?new Set([...$].filter((W)=>W!==void 0)):void 0}),b._zod.parse=($,W)=>{let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>w9(G,b));return w9(Q,b)}});function w9(b,w){if(!b.issues.length&&b.value===void 0)b.issues.push({code:"invalid_type",expected:"nonoptional",input:b.value,inst:w});return b}var d9=U("$ZodCatch",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>{if($.value=G.value,G.issues.length)$.value=w.catchValue({...$,error:{issues:G.issues.map((D)=>yb(D,W,Rb()))},input:$.value}),$.issues=[];return $});if($.value=Q.value,Q.issues.length)$.value=w.catchValue({...$,error:{issues:Q.issues.map((G)=>yb(G,W,Rb()))},input:$.value}),$.issues=[];return $}});var t9=U("$ZodPipe",(b,w)=>{e.init(b,w),d(b._zod,"values",()=>w.in._zod.values),d(b._zod,"optin",()=>w.in._zod.optin),d(b._zod,"optout",()=>w.out._zod.optout),d(b._zod,"propValues",()=>w.in._zod.propValues),b._zod.parse=($,W)=>{if(W.direction==="backward"){let G=w.out._zod.run($,W);if(G instanceof Promise)return G.then((D)=>I0(D,w.in,W));return I0(G,w.in,W)}let Q=w.in._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>I0(G,w.out,W));return I0(Q,w.out,W)}});function I0(b,w,$){if(b.issues.length)return b.aborted=!0,b;return w._zod.run({value:b.value,issues:b.issues},$)}var r9=U("$ZodReadonly",(b,w)=>{e.init(b,w),d(b._zod,"propValues",()=>w.innerType._zod.propValues),d(b._zod,"values",()=>w.innerType._zod.values),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then($9);return $9(Q)}});function $9(b){return b.value=Object.freeze(b.value),b}var e9=U("$ZodCustom",(b,w)=>{Hb.init(b,w),e.init(b,w),b._zod.parse=($,W)=>{return $},b._zod.check=($)=>{let W=$.value,Q=w.fn(W);if(Q instanceof Promise)return Q.then((G)=>W9(G,$,W,b));W9(Q,$,W,b);return}});function W9(b,w,$,W){if(!b){let Q={code:"custom",input:$,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)Q.params=W._zod.def.params;w.issues.push(cw(Q))}}var EA=(b)=>{let w=typeof b;switch(w){case"number":return Number.isNaN(b)?"NaN":"number";case"object":{if(Array.isArray(b))return"array";if(b===null)return"null";if(Object.getPrototypeOf(b)!==Object.prototype&&b.constructor)return b.constructor.name}}return w},_A=()=>{let b={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 w(W){return b[W]??null}let $={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(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${EA(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${U0(W.values[0])}`;return`Invalid option: expected one of ${O0(W.values,"|")}`;case"too_big":{let Q=W.inclusive?"<=":"<",G=w(W.origin);if(G)return`Too big: expected ${W.origin??"value"} to have ${Q}${W.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${Q}${W.maximum.toString()}`}case"too_small":{let Q=W.inclusive?">=":">",G=w(W.origin);if(G)return`Too small: expected ${W.origin} to have ${Q}${W.minimum.toString()} ${G.unit}`;return`Too small: expected ${W.origin} to be ${Q}${W.minimum.toString()}`}case"invalid_format":{let Q=W;if(Q.format==="starts_with")return`Invalid string: must start with "${Q.prefix}"`;if(Q.format==="ends_with")return`Invalid string: must end with "${Q.suffix}"`;if(Q.format==="includes")return`Invalid string: must include "${Q.includes}"`;if(Q.format==="regex")return`Invalid string: must match pattern ${Q.pattern}`;return`Invalid ${$[Q.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${O0(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function A4(){return{localeError:_A()}}var pM=Symbol("ZodOutput"),oM=Symbol("ZodInput");class s9{constructor(){this._map=new WeakMap,this._idmap=new Map}add(b,...w){let $=w[0];if(this._map.set(b,$),$&&typeof $==="object"&&"id"in $){if(this._idmap.has($.id))throw Error(`ID ${$.id} already exists in the registry`);this._idmap.set($.id,b)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(b){let w=this._map.get(b);if(w&&typeof w==="object"&&"id"in w)this._idmap.delete(w.id);return this._map.delete(b),this}get(b){let w=b._zod.parent;if(w){let $={...this.get(w)??{}};delete $.id;let W={...$,...this._map.get(b)};return Object.keys(W).length?W:void 0}return this._map.get(b)}has(b){return this._map.has(b)}}function SA(){return new s9}var M1=SA();function a9(b,w){return new b({type:"string",..._(w)})}function b8(b,w){return new b({type:"string",format:"email",check:"string_format",abort:!1,..._(w)})}function O4(b,w){return new b({type:"string",format:"guid",check:"string_format",abort:!1,..._(w)})}function w8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,..._(w)})}function $8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",..._(w)})}function W8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",..._(w)})}function Q8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",..._(w)})}function G8(b,w){return new b({type:"string",format:"url",check:"string_format",abort:!1,..._(w)})}function D8(b,w){return new b({type:"string",format:"emoji",check:"string_format",abort:!1,..._(w)})}function X8(b,w){return new b({type:"string",format:"nanoid",check:"string_format",abort:!1,..._(w)})}function Y8(b,w){return new b({type:"string",format:"cuid",check:"string_format",abort:!1,..._(w)})}function H8(b,w){return new b({type:"string",format:"cuid2",check:"string_format",abort:!1,..._(w)})}function J8(b,w){return new b({type:"string",format:"ulid",check:"string_format",abort:!1,..._(w)})}function z8(b,w){return new b({type:"string",format:"xid",check:"string_format",abort:!1,..._(w)})}function A8(b,w){return new b({type:"string",format:"ksuid",check:"string_format",abort:!1,..._(w)})}function O8(b,w){return new b({type:"string",format:"ipv4",check:"string_format",abort:!1,..._(w)})}function q8(b,w){return new b({type:"string",format:"ipv6",check:"string_format",abort:!1,..._(w)})}function L8(b,w){return new b({type:"string",format:"cidrv4",check:"string_format",abort:!1,..._(w)})}function U8(b,w){return new b({type:"string",format:"cidrv6",check:"string_format",abort:!1,..._(w)})}function B8(b,w){return new b({type:"string",format:"base64",check:"string_format",abort:!1,..._(w)})}function P8(b,w){return new b({type:"string",format:"base64url",check:"string_format",abort:!1,..._(w)})}function F8(b,w){return new b({type:"string",format:"e164",check:"string_format",abort:!1,..._(w)})}function K8(b,w){return new b({type:"string",format:"jwt",check:"string_format",abort:!1,..._(w)})}function M8(b,w){return new b({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,..._(w)})}function I8(b,w){return new b({type:"string",format:"date",check:"string_format",..._(w)})}function Z8(b,w){return new b({type:"string",format:"time",check:"string_format",precision:null,..._(w)})}function j8(b,w){return new b({type:"string",format:"duration",check:"string_format",..._(w)})}function V8(b,w){return new b({type:"number",checks:[],..._(w)})}function N8(b,w){return new b({type:"number",check:"number_format",abort:!1,format:"safeint",..._(w)})}function T8(b,w){return new b({type:"boolean",..._(w)})}function E8(b,w){return new b({type:"null",..._(w)})}function _8(b){return new b({type:"unknown"})}function S8(b,w){return new b({type:"never",..._(w)})}function V0(b,w){return new D4({check:"less_than",..._(w),value:b,inclusive:!1})}function I1(b,w){return new D4({check:"less_than",..._(w),value:b,inclusive:!0})}function N0(b,w){return new X4({check:"greater_than",..._(w),value:b,inclusive:!1})}function Z1(b,w){return new X4({check:"greater_than",..._(w),value:b,inclusive:!0})}function T0(b,w){return new xQ({check:"multiple_of",..._(w),value:b})}function E0(b,w){return new hQ({check:"max_length",..._(w),maximum:b})}function nw(b,w){return new fQ({check:"min_length",..._(w),minimum:b})}function _0(b,w){return new cQ({check:"length_equals",..._(w),length:b})}function q4(b,w){return new nQ({check:"string_format",format:"regex",..._(w),pattern:b})}function L4(b){return new gQ({check:"string_format",format:"lowercase",..._(b)})}function U4(b){return new mQ({check:"string_format",format:"uppercase",..._(b)})}function B4(b,w){return new iQ({check:"string_format",format:"includes",..._(w),includes:b})}function P4(b,w){return new lQ({check:"string_format",format:"starts_with",..._(w),prefix:b})}function F4(b,w){return new pQ({check:"string_format",format:"ends_with",..._(w),suffix:b})}function Sw(b){return new oQ({check:"overwrite",tx:b})}function K4(b){return Sw((w)=>w.normalize(b))}function M4(){return Sw((b)=>b.trim())}function I4(){return Sw((b)=>b.toLowerCase())}function Z4(){return Sw((b)=>b.toUpperCase())}function R8(b,w,$){return new b({type:"array",element:w,..._($)})}function v8(b,w,$){let W=_($);return W.abort??(W.abort=!0),new b({type:"custom",check:"custom",fn:w,...W})}function k8(b,w,$){return new b({type:"custom",check:"custom",fn:w,..._($)})}function C8(b){let w=RA(($)=>{return $.addIssue=(W)=>{if(typeof W==="string")$.issues.push(cw(W,$.value,w._zod.def));else{let Q=W;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=$.value),Q.inst??(Q.inst=w),Q.continue??(Q.continue=!w._zod.def.abort),$.issues.push(cw(Q))}},b($.value,$)});return w}function RA(b,w){let $=new Hb({check:"custom",..._(w)});return $._zod.check=b,$}function gw(b){return!!b._zod}function Bw(b,w){if(gw(b))return P1(b,w);return b.safeParse(w)}function S0(b){if(!b)return;let w;if(gw(b))w=b._zod?.def?.shape;else w=b.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function u8(b){if(gw(b)){let G=b._zod?.def;if(G){if(G.value!==void 0)return G.value;if(Array.isArray(G.values)&&G.values.length>0)return G.values[0]}}let $=b._def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}let W=b.value;if(W!==void 0)return W;return}var V1={};vW(V1,{time:()=>N4,duration:()=>T4,datetime:()=>j4,date:()=>V4,ZodISOTime:()=>h8,ZodISODuration:()=>f8,ZodISODateTime:()=>x8,ZodISODate:()=>y8});var x8=U("ZodISODateTime",(b,w)=>{L9.init(b,w),bb.init(b,w)});function j4(b){return M8(x8,b)}var y8=U("ZodISODate",(b,w)=>{U9.init(b,w),bb.init(b,w)});function V4(b){return I8(y8,b)}var h8=U("ZodISOTime",(b,w)=>{B9.init(b,w),bb.init(b,w)});function N4(b){return Z8(h8,b)}var f8=U("ZodISODuration",(b,w)=>{P9.init(b,w),bb.init(b,w)});function T4(b){return j8(f8,b)}var c8=(b,w)=>{B0.init(b,w),b.name="ZodError",Object.defineProperties(b,{format:{value:($)=>eW(b,$)},flatten:{value:($)=>rW(b,$)},addIssue:{value:($)=>{b.issues.push($),b.message=JSON.stringify(b.issues,hw,2)}},addIssues:{value:($)=>{b.issues.push(...$),b.message=JSON.stringify(b.issues,hw,2)}},isEmpty:{get(){return b.issues.length===0}}})},vI=U("ZodError",c8),Tb=U("ZodError",c8,{Parent:Error});var n8=P0(Tb),g8=F0(Tb),m8=B1(Tb),i8=F1(Tb),l8=sW(Tb),p8=aW(Tb),o8=bQ(Tb),d8=wQ(Tb),t8=$Q(Tb),r8=WQ(Tb),e8=QQ(Tb),s8=GQ(Tb);var Qb=U("ZodType",(b,w)=>{return e.init(b,w),b.def=w,b.type=w.type,Object.defineProperty(b,"_def",{value:w}),b.check=(...$)=>{return b.clone(m.mergeDefs(w,{checks:[...w.checks??[],...$.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},b.clone=($,W)=>xb(b,$,W),b.brand=()=>b,b.register=($,W)=>{return $.add(b,W),b},b.parse=($,W)=>n8(b,$,W,{callee:b.parse}),b.safeParse=($,W)=>m8(b,$,W),b.parseAsync=async($,W)=>g8(b,$,W,{callee:b.parseAsync}),b.safeParseAsync=async($,W)=>i8(b,$,W),b.spa=b.safeParseAsync,b.encode=($,W)=>l8(b,$,W),b.decode=($,W)=>p8(b,$,W),b.encodeAsync=async($,W)=>o8(b,$,W),b.decodeAsync=async($,W)=>d8(b,$,W),b.safeEncode=($,W)=>t8(b,$,W),b.safeDecode=($,W)=>r8(b,$,W),b.safeEncodeAsync=async($,W)=>e8(b,$,W),b.safeDecodeAsync=async($,W)=>s8(b,$,W),b.refine=($,W)=>b.check(T7($,W)),b.superRefine=($)=>b.check(E7($)),b.overwrite=($)=>b.check(Sw($)),b.optional=()=>Wb(b),b.nullable=()=>wG(b),b.nullish=()=>Wb(wG(b)),b.nonoptional=($)=>M7(b,$),b.array=()=>f(b),b.or=($)=>r([b,$]),b.and=($)=>v0(b,$),b.transform=($)=>_4(b,DG($)),b.default=($)=>P7(b,$),b.prefault=($)=>K7(b,$),b.catch=($)=>Z7(b,$),b.pipe=($)=>_4(b,$),b.readonly=()=>N7(b),b.describe=($)=>{let W=b.clone();return M1.add(W,{description:$}),W},Object.defineProperty(b,"description",{get(){return M1.get(b)?.description},configurable:!0}),b.meta=(...$)=>{if($.length===0)return M1.get(b);let W=b.clone();return M1.add(W,$[0]),W},b.isOptional=()=>b.safeParse(void 0).success,b.isNullable=()=>b.safeParse(null).success,b}),$G=U("_ZodString",(b,w)=>{j0.init(b,w),Qb.init(b,w);let $=b._zod.bag;b.format=$.format??null,b.minLength=$.minimum??null,b.maxLength=$.maximum??null,b.regex=(...W)=>b.check(q4(...W)),b.includes=(...W)=>b.check(B4(...W)),b.startsWith=(...W)=>b.check(P4(...W)),b.endsWith=(...W)=>b.check(F4(...W)),b.min=(...W)=>b.check(nw(...W)),b.max=(...W)=>b.check(E0(...W)),b.length=(...W)=>b.check(_0(...W)),b.nonempty=(...W)=>b.check(nw(1,...W)),b.lowercase=(W)=>b.check(L4(W)),b.uppercase=(W)=>b.check(U4(W)),b.trim=()=>b.check(M4()),b.normalize=(...W)=>b.check(K4(...W)),b.toLowerCase=()=>b.check(I4()),b.toUpperCase=()=>b.check(Z4())}),cA=U("ZodString",(b,w)=>{j0.init(b,w),$G.init(b,w),b.email=($)=>b.check(b8(nA,$)),b.url=($)=>b.check(G8(gA,$)),b.jwt=($)=>b.check(K8(W7,$)),b.emoji=($)=>b.check(D8(mA,$)),b.guid=($)=>b.check(O4(a8,$)),b.uuid=($)=>b.check(w8(R0,$)),b.uuidv4=($)=>b.check($8(R0,$)),b.uuidv6=($)=>b.check(W8(R0,$)),b.uuidv7=($)=>b.check(Q8(R0,$)),b.nanoid=($)=>b.check(X8(iA,$)),b.guid=($)=>b.check(O4(a8,$)),b.cuid=($)=>b.check(Y8(lA,$)),b.cuid2=($)=>b.check(H8(pA,$)),b.ulid=($)=>b.check(J8(oA,$)),b.base64=($)=>b.check(B8(b7,$)),b.base64url=($)=>b.check(P8(w7,$)),b.xid=($)=>b.check(z8(dA,$)),b.ksuid=($)=>b.check(A8(tA,$)),b.ipv4=($)=>b.check(O8(rA,$)),b.ipv6=($)=>b.check(q8(eA,$)),b.cidrv4=($)=>b.check(L8(sA,$)),b.cidrv6=($)=>b.check(U8(aA,$)),b.e164=($)=>b.check(F8($7,$)),b.datetime=($)=>b.check(j4($)),b.date=($)=>b.check(V4($)),b.time=($)=>b.check(N4($)),b.duration=($)=>b.check(T4($))});function L(b){return a9(cA,b)}var bb=U("ZodStringFormat",(b,w)=>{s.init(b,w),$G.init(b,w)}),nA=U("ZodEmail",(b,w)=>{D9.init(b,w),bb.init(b,w)});var a8=U("ZodGUID",(b,w)=>{Q9.init(b,w),bb.init(b,w)});var R0=U("ZodUUID",(b,w)=>{G9.init(b,w),bb.init(b,w)});var gA=U("ZodURL",(b,w)=>{X9.init(b,w),bb.init(b,w)});var mA=U("ZodEmoji",(b,w)=>{Y9.init(b,w),bb.init(b,w)});var iA=U("ZodNanoID",(b,w)=>{H9.init(b,w),bb.init(b,w)});var lA=U("ZodCUID",(b,w)=>{J9.init(b,w),bb.init(b,w)});var pA=U("ZodCUID2",(b,w)=>{z9.init(b,w),bb.init(b,w)});var oA=U("ZodULID",(b,w)=>{A9.init(b,w),bb.init(b,w)});var dA=U("ZodXID",(b,w)=>{O9.init(b,w),bb.init(b,w)});var tA=U("ZodKSUID",(b,w)=>{q9.init(b,w),bb.init(b,w)});var rA=U("ZodIPv4",(b,w)=>{F9.init(b,w),bb.init(b,w)});var eA=U("ZodIPv6",(b,w)=>{K9.init(b,w),bb.init(b,w)});var sA=U("ZodCIDRv4",(b,w)=>{M9.init(b,w),bb.init(b,w)});var aA=U("ZodCIDRv6",(b,w)=>{I9.init(b,w),bb.init(b,w)});var b7=U("ZodBase64",(b,w)=>{j9.init(b,w),bb.init(b,w)});var w7=U("ZodBase64URL",(b,w)=>{V9.init(b,w),bb.init(b,w)});var $7=U("ZodE164",(b,w)=>{N9.init(b,w),bb.init(b,w)});var W7=U("ZodJWT",(b,w)=>{T9.init(b,w),bb.init(b,w)});var WG=U("ZodNumber",(b,w)=>{J4.init(b,w),Qb.init(b,w),b.gt=(W,Q)=>b.check(N0(W,Q)),b.gte=(W,Q)=>b.check(Z1(W,Q)),b.min=(W,Q)=>b.check(Z1(W,Q)),b.lt=(W,Q)=>b.check(V0(W,Q)),b.lte=(W,Q)=>b.check(I1(W,Q)),b.max=(W,Q)=>b.check(I1(W,Q)),b.int=(W)=>b.check(bG(W)),b.safe=(W)=>b.check(bG(W)),b.positive=(W)=>b.check(N0(0,W)),b.nonnegative=(W)=>b.check(Z1(0,W)),b.negative=(W)=>b.check(V0(0,W)),b.nonpositive=(W)=>b.check(I1(0,W)),b.multipleOf=(W,Q)=>b.check(T0(W,Q)),b.step=(W,Q)=>b.check(T0(W,Q)),b.finite=()=>b;let $=b._zod.bag;b.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,b.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,b.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),b.isFinite=!0,b.format=$.format??null});function p(b){return V8(WG,b)}var Q7=U("ZodNumberFormat",(b,w)=>{E9.init(b,w),WG.init(b,w)});function bG(b){return N8(Q7,b)}var G7=U("ZodBoolean",(b,w)=>{_9.init(b,w),Qb.init(b,w)});function Yb(b){return T8(G7,b)}var D7=U("ZodNull",(b,w)=>{S9.init(b,w),Qb.init(b,w)});function S4(b){return E8(D7,b)}var X7=U("ZodUnknown",(b,w)=>{R9.init(b,w),Qb.init(b,w)});function wb(){return _8(X7)}var Y7=U("ZodNever",(b,w)=>{v9.init(b,w),Qb.init(b,w)});function H7(b){return S8(Y7,b)}var J7=U("ZodArray",(b,w)=>{k9.init(b,w),Qb.init(b,w),b.element=w.element,b.min=($,W)=>b.check(nw($,W)),b.nonempty=($)=>b.check(nw(1,$)),b.max=($,W)=>b.check(E0($,W)),b.length=($,W)=>b.check(_0($,W)),b.unwrap=()=>b.element});function f(b,w){return R8(J7,b,w)}var QG=U("ZodObject",(b,w)=>{x9.init(b,w),Qb.init(b,w),m.defineLazy(b,"shape",()=>{return w.shape}),b.keyof=()=>Mb(Object.keys(b._zod.def.shape)),b.catchall=($)=>b.clone({...b._zod.def,catchall:$}),b.passthrough=()=>b.clone({...b._zod.def,catchall:wb()}),b.loose=()=>b.clone({...b._zod.def,catchall:wb()}),b.strict=()=>b.clone({...b._zod.def,catchall:H7()}),b.strip=()=>b.clone({...b._zod.def,catchall:void 0}),b.extend=($)=>{return m.extend(b,$)},b.safeExtend=($)=>{return m.safeExtend(b,$)},b.merge=($)=>m.merge(b,$),b.pick=($)=>m.pick(b,$),b.omit=($)=>m.omit(b,$),b.partial=(...$)=>m.partial(XG,b,$[0]),b.required=(...$)=>m.required(YG,b,$[0])});function V(b,w){let $={type:"object",shape:b??{},...m.normalizeParams(w)};return new QG($)}function Bb(b,w){return new QG({type:"object",shape:b,catchall:wb(),...m.normalizeParams(w)})}var GG=U("ZodUnion",(b,w)=>{z4.init(b,w),Qb.init(b,w),b.options=w.options});function r(b,w){return new GG({type:"union",options:b,...m.normalizeParams(w)})}var z7=U("ZodDiscriminatedUnion",(b,w)=>{GG.init(b,w),y9.init(b,w)});function R4(b,w,$){return new z7({type:"union",options:w,discriminator:b,...m.normalizeParams($)})}var A7=U("ZodIntersection",(b,w)=>{h9.init(b,w),Qb.init(b,w)});function v0(b,w){return new A7({type:"intersection",left:b,right:w})}var O7=U("ZodRecord",(b,w)=>{f9.init(b,w),Qb.init(b,w),b.keyType=w.keyType,b.valueType=w.valueType});function $b(b,w,$){return new O7({type:"record",keyType:b,valueType:w,...m.normalizeParams($)})}var E4=U("ZodEnum",(b,w)=>{c9.init(b,w),Qb.init(b,w),b.enum=w.entries,b.options=Object.values(w.entries);let $=new Set(Object.keys(w.entries));b.extract=(W,Q)=>{let G={};for(let D of W)if($.has(D))G[D]=w.entries[D];else throw Error(`Key ${D} not found in enum`);return new E4({...w,checks:[],...m.normalizeParams(Q),entries:G})},b.exclude=(W,Q)=>{let G={...w.entries};for(let D of W)if($.has(D))delete G[D];else throw Error(`Key ${D} not found in enum`);return new E4({...w,checks:[],...m.normalizeParams(Q),entries:G})}});function Mb(b,w){let $=Array.isArray(b)?Object.fromEntries(b.map((W)=>[W,W])):b;return new E4({type:"enum",entries:$,...m.normalizeParams(w)})}var q7=U("ZodLiteral",(b,w)=>{n9.init(b,w),Qb.init(b,w),b.values=new Set(w.values),Object.defineProperty(b,"value",{get(){if(w.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return w.values[0]}})});function T(b,w){return new q7({type:"literal",values:Array.isArray(b)?b:[b],...m.normalizeParams(w)})}var L7=U("ZodTransform",(b,w)=>{g9.init(b,w),Qb.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);$.addIssue=(G)=>{if(typeof G==="string")$.issues.push(m.issue(G,$.value,w));else{let D=G;if(D.fatal)D.continue=!1;D.code??(D.code="custom"),D.input??(D.input=$.value),D.inst??(D.inst=b),$.issues.push(m.issue(D))}};let Q=w.transform($.value,$);if(Q instanceof Promise)return Q.then((G)=>{return $.value=G,$});return $.value=Q,$}});function DG(b){return new L7({type:"transform",transform:b})}var XG=U("ZodOptional",(b,w)=>{m9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Wb(b){return new XG({type:"optional",innerType:b})}var U7=U("ZodNullable",(b,w)=>{i9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function wG(b){return new U7({type:"nullable",innerType:b})}var B7=U("ZodDefault",(b,w)=>{l9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeDefault=b.unwrap});function P7(b,w){return new B7({type:"default",innerType:b,get defaultValue(){return typeof w==="function"?w():m.shallowClone(w)}})}var F7=U("ZodPrefault",(b,w)=>{p9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function K7(b,w){return new F7({type:"prefault",innerType:b,get defaultValue(){return typeof w==="function"?w():m.shallowClone(w)}})}var YG=U("ZodNonOptional",(b,w)=>{o9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function M7(b,w){return new YG({type:"nonoptional",innerType:b,...m.normalizeParams(w)})}var I7=U("ZodCatch",(b,w)=>{d9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeCatch=b.unwrap});function Z7(b,w){return new I7({type:"catch",innerType:b,catchValue:typeof w==="function"?w:()=>w})}var j7=U("ZodPipe",(b,w)=>{t9.init(b,w),Qb.init(b,w),b.in=w.in,b.out=w.out});function _4(b,w){return new j7({type:"pipe",in:b,out:w})}var V7=U("ZodReadonly",(b,w)=>{r9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function N7(b){return new V7({type:"readonly",innerType:b})}var HG=U("ZodCustom",(b,w)=>{e9.init(b,w),Qb.init(b,w)});function JG(b,w){return v8(HG,b??(()=>!0),w)}function T7(b,w={}){return k8(HG,b,w)}function E7(b){return C8(b)}function v4(b,w){return _4(DG(b),w)}Rb(A4());var k4="2025-11-25";var zG=[k4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Pw="io.modelcontextprotocol/related-task",C0="2.0",Jb=JG((b)=>b!==null&&(typeof b==="object"||typeof b==="function")),AG=r([L(),p().int()]),OG=L(),TZ=Bb({ttl:r([p(),S4()]).optional(),pollInterval:p().optional()}),_7=V({ttl:p().optional()}),S7=V({taskId:L()}),C4=Bb({progressToken:AG.optional(),[Pw]:S7.optional()}),Eb=V({_meta:C4.optional()}),N1=Eb.extend({task:_7.optional()}),qG=(b)=>N1.safeParse(b).success,zb=V({method:L(),params:Eb.loose().optional()}),vb=V({_meta:C4.optional()}),kb=V({method:L(),params:vb.loose().optional()}),Ab=Bb({_meta:C4.optional()}),u0=r([L(),p().int()]),LG=V({jsonrpc:T(C0),id:u0,...zb.shape}).strict(),u4=(b)=>LG.safeParse(b).success,UG=V({jsonrpc:T(C0),...kb.shape}).strict(),BG=(b)=>UG.safeParse(b).success,x4=V({jsonrpc:T(C0),id:u0,result:Ab}).strict(),T1=(b)=>x4.safeParse(b).success;var c;(function(b){b[b.ConnectionClosed=-32000]="ConnectionClosed",b[b.RequestTimeout=-32001]="RequestTimeout",b[b.ParseError=-32700]="ParseError",b[b.InvalidRequest=-32600]="InvalidRequest",b[b.MethodNotFound=-32601]="MethodNotFound",b[b.InvalidParams=-32602]="InvalidParams",b[b.InternalError=-32603]="InternalError",b[b.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(c||(c={}));var y4=V({jsonrpc:T(C0),id:u0.optional(),error:V({code:p().int(),message:L(),data:wb().optional()})}).strict();var PG=(b)=>y4.safeParse(b).success;var EZ=r([LG,UG,x4,y4]),_Z=r([x4,y4]),x0=Ab.strict(),R7=vb.extend({requestId:u0.optional(),reason:L().optional()}),y0=kb.extend({method:T("notifications/cancelled"),params:R7}),v7=V({src:L(),mimeType:L().optional(),sizes:f(L()).optional(),theme:Mb(["light","dark"]).optional()}),E1=V({icons:f(v7).optional()}),mw=V({name:L(),title:L().optional()}),FG=mw.extend({...mw.shape,...E1.shape,version:L(),websiteUrl:L().optional(),description:L().optional()}),k7=v0(V({applyDefaults:Yb().optional()}),$b(L(),wb())),C7=v4((b)=>{if(b&&typeof b==="object"&&!Array.isArray(b)){if(Object.keys(b).length===0)return{form:{}}}return b},v0(V({form:k7.optional(),url:Jb.optional()}),$b(L(),wb()).optional())),u7=Bb({list:Jb.optional(),cancel:Jb.optional(),requests:Bb({sampling:Bb({createMessage:Jb.optional()}).optional(),elicitation:Bb({create:Jb.optional()}).optional()}).optional()}),x7=Bb({list:Jb.optional(),cancel:Jb.optional(),requests:Bb({tools:Bb({call:Jb.optional()}).optional()}).optional()}),y7=V({experimental:$b(L(),Jb).optional(),sampling:V({context:Jb.optional(),tools:Jb.optional()}).optional(),elicitation:C7.optional(),roots:V({listChanged:Yb().optional()}).optional(),tasks:u7.optional()}),h7=Eb.extend({protocolVersion:L(),capabilities:y7,clientInfo:FG}),h4=zb.extend({method:T("initialize"),params:h7});var f7=V({experimental:$b(L(),Jb).optional(),logging:Jb.optional(),completions:Jb.optional(),prompts:V({listChanged:Yb().optional()}).optional(),resources:V({subscribe:Yb().optional(),listChanged:Yb().optional()}).optional(),tools:V({listChanged:Yb().optional()}).optional(),tasks:x7.optional()}),c7=Ab.extend({protocolVersion:L(),capabilities:f7,serverInfo:FG,instructions:L().optional()}),f4=kb.extend({method:T("notifications/initialized"),params:vb.optional()});var h0=zb.extend({method:T("ping"),params:Eb.optional()}),n7=V({progress:p(),total:Wb(p()),message:Wb(L())}),g7=V({...vb.shape,...n7.shape,progressToken:AG}),f0=kb.extend({method:T("notifications/progress"),params:g7}),m7=Eb.extend({cursor:OG.optional()}),_1=zb.extend({params:m7.optional()}),S1=Ab.extend({nextCursor:OG.optional()}),i7=Mb(["working","input_required","completed","failed","cancelled"]),R1=V({taskId:L(),status:i7,ttl:r([p(),S4()]),createdAt:L(),lastUpdatedAt:L(),pollInterval:Wb(p()),statusMessage:Wb(L())}),iw=Ab.extend({task:R1}),l7=vb.merge(R1),v1=kb.extend({method:T("notifications/tasks/status"),params:l7}),c0=zb.extend({method:T("tasks/get"),params:Eb.extend({taskId:L()})}),n0=Ab.merge(R1),g0=zb.extend({method:T("tasks/result"),params:Eb.extend({taskId:L()})}),SZ=Ab.loose(),m0=_1.extend({method:T("tasks/list")}),i0=S1.extend({tasks:f(R1)}),l0=zb.extend({method:T("tasks/cancel"),params:Eb.extend({taskId:L()})}),KG=Ab.merge(R1),MG=V({uri:L(),mimeType:Wb(L()),_meta:$b(L(),wb()).optional()}),IG=MG.extend({text:L()}),c4=L().refine((b)=>{try{return atob(b),!0}catch{return!1}},{message:"Invalid Base64 string"}),ZG=MG.extend({blob:c4}),k1=Mb(["user","assistant"]),lw=V({audience:f(k1).optional(),priority:p().min(0).max(1).optional(),lastModified:V1.datetime({offset:!0}).optional()}),jG=V({...mw.shape,...E1.shape,uri:L(),description:Wb(L()),mimeType:Wb(L()),annotations:lw.optional(),_meta:Wb(Bb({}))}),p7=V({...mw.shape,...E1.shape,uriTemplate:L(),description:Wb(L()),mimeType:Wb(L()),annotations:lw.optional(),_meta:Wb(Bb({}))}),n4=_1.extend({method:T("resources/list")}),o7=S1.extend({resources:f(jG)}),d7=_1.extend({method:T("resources/templates/list")}),t7=S1.extend({resourceTemplates:f(p7)}),g4=Eb.extend({uri:L()}),r7=g4,m4=zb.extend({method:T("resources/read"),params:r7}),e7=Ab.extend({contents:f(r([IG,ZG]))}),s7=kb.extend({method:T("notifications/resources/list_changed"),params:vb.optional()}),a7=g4,b5=zb.extend({method:T("resources/subscribe"),params:a7}),w5=g4,$5=zb.extend({method:T("resources/unsubscribe"),params:w5}),W5=vb.extend({uri:L()}),Q5=kb.extend({method:T("notifications/resources/updated"),params:W5}),G5=V({name:L(),description:Wb(L()),required:Wb(Yb())}),D5=V({...mw.shape,...E1.shape,description:Wb(L()),arguments:Wb(f(G5)),_meta:Wb(Bb({}))}),X5=_1.extend({method:T("prompts/list")}),Y5=S1.extend({prompts:f(D5)}),H5=Eb.extend({name:L(),arguments:$b(L(),L()).optional()}),J5=zb.extend({method:T("prompts/get"),params:H5}),i4=V({type:T("text"),text:L(),annotations:lw.optional(),_meta:$b(L(),wb()).optional()}),l4=V({type:T("image"),data:c4,mimeType:L(),annotations:lw.optional(),_meta:$b(L(),wb()).optional()}),p4=V({type:T("audio"),data:c4,mimeType:L(),annotations:lw.optional(),_meta:$b(L(),wb()).optional()}),z5=V({type:T("tool_use"),name:L(),id:L(),input:$b(L(),wb()),_meta:$b(L(),wb()).optional()}),A5=V({type:T("resource"),resource:r([IG,ZG]),annotations:lw.optional(),_meta:$b(L(),wb()).optional()}),O5=jG.extend({type:T("resource_link")}),o4=r([i4,l4,p4,O5,A5]),q5=V({role:k1,content:o4}),L5=Ab.extend({description:L().optional(),messages:f(q5)}),U5=kb.extend({method:T("notifications/prompts/list_changed"),params:vb.optional()}),B5=V({title:L().optional(),readOnlyHint:Yb().optional(),destructiveHint:Yb().optional(),idempotentHint:Yb().optional(),openWorldHint:Yb().optional()}),P5=V({taskSupport:Mb(["required","optional","forbidden"]).optional()}),VG=V({...mw.shape,...E1.shape,description:L().optional(),inputSchema:V({type:T("object"),properties:$b(L(),Jb).optional(),required:f(L()).optional()}).catchall(wb()),outputSchema:V({type:T("object"),properties:$b(L(),Jb).optional(),required:f(L()).optional()}).catchall(wb()).optional(),annotations:B5.optional(),execution:P5.optional(),_meta:$b(L(),wb()).optional()}),d4=_1.extend({method:T("tools/list")}),F5=S1.extend({tools:f(VG)}),p0=Ab.extend({content:f(o4).default([]),structuredContent:$b(L(),wb()).optional(),isError:Yb().optional()}),RZ=p0.or(Ab.extend({toolResult:wb()})),K5=N1.extend({name:L(),arguments:$b(L(),wb()).optional()}),C1=zb.extend({method:T("tools/call"),params:K5}),M5=kb.extend({method:T("notifications/tools/list_changed"),params:vb.optional()}),vZ=V({autoRefresh:Yb().default(!0),debounceMs:p().int().nonnegative().default(300)}),u1=Mb(["debug","info","notice","warning","error","critical","alert","emergency"]),I5=Eb.extend({level:u1}),t4=zb.extend({method:T("logging/setLevel"),params:I5}),Z5=vb.extend({level:u1,logger:L().optional(),data:wb()}),j5=kb.extend({method:T("notifications/message"),params:Z5}),V5=V({name:L().optional()}),N5=V({hints:f(V5).optional(),costPriority:p().min(0).max(1).optional(),speedPriority:p().min(0).max(1).optional(),intelligencePriority:p().min(0).max(1).optional()}),T5=V({mode:Mb(["auto","required","none"]).optional()}),E5=V({type:T("tool_result"),toolUseId:L().describe("The unique identifier for the corresponding tool call."),content:f(o4).default([]),structuredContent:V({}).loose().optional(),isError:Yb().optional(),_meta:$b(L(),wb()).optional()}),_5=R4("type",[i4,l4,p4]),k0=R4("type",[i4,l4,p4,z5,E5]),S5=V({role:k1,content:r([k0,f(k0)]),_meta:$b(L(),wb()).optional()}),R5=N1.extend({messages:f(S5),modelPreferences:N5.optional(),systemPrompt:L().optional(),includeContext:Mb(["none","thisServer","allServers"]).optional(),temperature:p().optional(),maxTokens:p().int(),stopSequences:f(L()).optional(),metadata:Jb.optional(),tools:f(VG).optional(),toolChoice:T5.optional()}),v5=zb.extend({method:T("sampling/createMessage"),params:R5}),r4=Ab.extend({model:L(),stopReason:Wb(Mb(["endTurn","stopSequence","maxTokens"]).or(L())),role:k1,content:_5}),e4=Ab.extend({model:L(),stopReason:Wb(Mb(["endTurn","stopSequence","maxTokens","toolUse"]).or(L())),role:k1,content:r([k0,f(k0)])}),k5=V({type:T("boolean"),title:L().optional(),description:L().optional(),default:Yb().optional()}),C5=V({type:T("string"),title:L().optional(),description:L().optional(),minLength:p().optional(),maxLength:p().optional(),format:Mb(["email","uri","date","date-time"]).optional(),default:L().optional()}),u5=V({type:Mb(["number","integer"]),title:L().optional(),description:L().optional(),minimum:p().optional(),maximum:p().optional(),default:p().optional()}),x5=V({type:T("string"),title:L().optional(),description:L().optional(),enum:f(L()),default:L().optional()}),y5=V({type:T("string"),title:L().optional(),description:L().optional(),oneOf:f(V({const:L(),title:L()})),default:L().optional()}),h5=V({type:T("string"),title:L().optional(),description:L().optional(),enum:f(L()),enumNames:f(L()).optional(),default:L().optional()}),f5=r([x5,y5]),c5=V({type:T("array"),title:L().optional(),description:L().optional(),minItems:p().optional(),maxItems:p().optional(),items:V({type:T("string"),enum:f(L())}),default:f(L()).optional()}),n5=V({type:T("array"),title:L().optional(),description:L().optional(),minItems:p().optional(),maxItems:p().optional(),items:V({anyOf:f(V({const:L(),title:L()}))}),default:f(L()).optional()}),g5=r([c5,n5]),m5=r([h5,f5,g5]),i5=r([m5,k5,C5,u5]),l5=N1.extend({mode:T("form").optional(),message:L(),requestedSchema:V({type:T("object"),properties:$b(L(),i5),required:f(L()).optional()})}),p5=N1.extend({mode:T("url"),message:L(),elicitationId:L(),url:L().url()}),o5=r([l5,p5]),d5=zb.extend({method:T("elicitation/create"),params:o5}),t5=vb.extend({elicitationId:L()}),r5=kb.extend({method:T("notifications/elicitation/complete"),params:t5}),o0=Ab.extend({action:Mb(["accept","decline","cancel"]),content:v4((b)=>b===null?void 0:b,$b(L(),r([L(),p(),Yb(),f(L())])).optional())}),e5=V({type:T("ref/resource"),uri:L()});var s5=V({type:T("ref/prompt"),name:L()}),a5=Eb.extend({ref:r([s5,e5]),argument:V({name:L(),value:L()}),context:V({arguments:$b(L(),L()).optional()}).optional()}),bO=zb.extend({method:T("completion/complete"),params:a5});var wO=Ab.extend({completion:Bb({values:f(L()).max(100),total:Wb(p().int()),hasMore:Wb(Yb())})}),$O=V({uri:L().startsWith("file://"),name:L().optional(),_meta:$b(L(),wb()).optional()}),WO=zb.extend({method:T("roots/list"),params:Eb.optional()}),s4=Ab.extend({roots:f($O)}),QO=kb.extend({method:T("notifications/roots/list_changed"),params:vb.optional()}),kZ=r([h0,h4,bO,t4,J5,X5,n4,d7,m4,b5,$5,C1,d4,c0,g0,m0,l0]),CZ=r([y0,f0,f4,QO,v1]),uZ=r([x0,r4,e4,o0,s4,n0,i0,iw]),xZ=r([h0,v5,d5,WO,c0,g0,m0,l0]),yZ=r([y0,f0,j5,Q5,s7,M5,U5,v1,r5]),hZ=r([x0,c7,wO,L5,Y5,o7,t7,e7,p0,F5,n0,i0,iw]);class u extends Error{constructor(b,w,$){super(`MCP error ${b}: ${w}`);this.code=b,this.data=$,this.name="McpError"}static fromError(b,w,$){if(b===c.UrlElicitationRequired&&$){let W=$;if(W.elicitations)return new NG(W.elicitations,w)}return new u(b,w,$)}}class NG extends u{constructor(b,w=`URL elicitation${b.length>1?"s":""} required`){super(c.UrlElicitationRequired,w,{elicitations:b})}get elicitations(){return this.data?.elicitations??[]}}function Fw(b){return b==="completed"||b==="failed"||b==="cancelled"}var GO=Symbol("Let zodToJsonSchema decide on which parser to use");var Bj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function a4(b){let $=S0(b)?.method;if(!$)throw Error("Schema is missing a method literal");let W=u8($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function b6(b,w){let $=Bw(b,w);if(!$.success)throw $.error;return $.data}var zO=60000;class w6{constructor(b){if(this._options=b,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(y0,(w)=>{this._oncancel(w)}),this.setNotificationHandler(f0,(w)=>{this._onprogress(w)}),this.setRequestHandler(h0,(w)=>({})),this._taskStore=b?.taskStore,this._taskMessageQueue=b?.taskMessageQueue,this._taskStore)this.setRequestHandler(c0,async(w,$)=>{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new u(c.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(g0,async(w,$)=>{let W=async()=>{let Q=w.params.taskId;if(this._taskMessageQueue){let D;while(D=await this._taskMessageQueue.dequeue(Q,$.sessionId)){if(D.type==="response"||D.type==="error"){let X=D.message,Y=X.id,H=this._requestResolvers.get(Y);if(H)if(this._requestResolvers.delete(Y),D.type==="response")H(X);else{let J=X,z=new u(J.error.code,J.error.message,J.error.data);H(z)}else{let J=D.type==="response"?"Response":"Error";this._onerror(Error(`${J} handler missing for request ${Y}`))}continue}await this._transport?.send(D.message,{relatedRequestId:$.requestId})}}let G=await this._taskStore.getTask(Q,$.sessionId);if(!G)throw new u(c.InvalidParams,`Task not found: ${Q}`);if(!Fw(G.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(Fw(G.status)){let D=await this._taskStore.getTaskResult(Q,$.sessionId);return this._clearTaskQueue(Q),{...D,_meta:{...D._meta,[Pw]:{taskId:Q}}}}return await W()};return await W()}),this.setRequestHandler(m0,async(w,$)=>{try{let{tasks:W,nextCursor:Q}=await this._taskStore.listTasks(w.params?.cursor,$.sessionId);return{tasks:W,nextCursor:Q,_meta:{}}}catch(W){throw new u(c.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(l0,async(w,$)=>{try{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new u(c.InvalidParams,`Task not found: ${w.params.taskId}`);if(Fw(W.status))throw new u(c.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(w.params.taskId);let Q=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!Q)throw new u(c.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...Q}}catch(W){if(W instanceof u)throw W;throw new u(c.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(b){if(!b.params.requestId)return;this._requestHandlerAbortControllers.get(b.params.requestId)?.abort(b.params.reason)}_setupTimeout(b,w,$,W,Q=!1){this._timeoutInfo.set(b,{timeoutId:setTimeout(W,w),startTime:Date.now(),timeout:w,maxTotalTimeout:$,resetTimeoutOnProgress:Q,onTimeout:W})}_resetTimeout(b){let w=this._timeoutInfo.get(b);if(!w)return!1;let $=Date.now()-w.startTime;if(w.maxTotalTimeout&&$>=w.maxTotalTimeout)throw this._timeoutInfo.delete(b),u.fromError(c.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:$});return clearTimeout(w.timeoutId),w.timeoutId=setTimeout(w.onTimeout,w.timeout),!0}_cleanupTimeout(b){let w=this._timeoutInfo.get(b);if(w)clearTimeout(w.timeoutId),this._timeoutInfo.delete(b)}async connect(b){this._transport=b;let w=this.transport?.onclose;this._transport.onclose=()=>{w?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(Q)=>{$?.(Q),this._onerror(Q)};let W=this._transport?.onmessage;this._transport.onmessage=(Q,G)=>{if(W?.(Q,G),T1(Q)||PG(Q))this._onresponse(Q);else if(u4(Q))this._onrequest(Q,G);else if(BG(Q))this._onnotification(Q);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Q)}`))},await this._transport.start()}_onclose(){let b=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let w=u.fromError(c.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of b.values())$(w)}_onerror(b){this.onerror?.(b)}_onnotification(b){let w=this._notificationHandlers.get(b.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w(b)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(b,w){let $=this._requestHandlers.get(b.method)??this.fallbackRequestHandler,W=this._transport,Q=b.params?._meta?.[Pw]?.taskId;if($===void 0){let H={jsonrpc:"2.0",id:b.id,error:{code:c.MethodNotFound,message:"Method not found"}};if(Q&&this._taskMessageQueue)this._enqueueTaskMessage(Q,{type:"error",message:H,timestamp:Date.now()},W?.sessionId).catch((J)=>this._onerror(Error(`Failed to enqueue error response: ${J}`)));else W?.send(H).catch((J)=>this._onerror(Error(`Failed to send an error response: ${J}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set(b.id,G);let D=qG(b.params)?b.params.task:void 0,X=this._taskStore?this.requestTaskStore(b,W?.sessionId):void 0,Y={signal:G.signal,sessionId:W?.sessionId,_meta:b.params?._meta,sendNotification:async(H)=>{let J={relatedRequestId:b.id};if(Q)J.relatedTask={taskId:Q};await this.notification(H,J)},sendRequest:async(H,J,z)=>{let O={...z,relatedRequestId:b.id};if(Q&&!O.relatedTask)O.relatedTask={taskId:Q};let q=O.relatedTask?.taskId??Q;if(q&&X)await X.updateTaskStatus(q,"input_required");return await this.request(H,J,O)},authInfo:w?.authInfo,requestId:b.id,requestInfo:w?.requestInfo,taskId:Q,taskStore:X,taskRequestedTtl:D?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(D)this.assertTaskHandlerCapability(b.method)}).then(()=>$(b,Y)).then(async(H)=>{if(G.signal.aborted)return;let J={result:H,jsonrpc:"2.0",id:b.id};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"response",message:J,timestamp:Date.now()},W?.sessionId);else await W?.send(J)},async(H)=>{if(G.signal.aborted)return;let J={jsonrpc:"2.0",id:b.id,error:{code:Number.isSafeInteger(H.code)?H.code:c.InternalError,message:H.message??"Internal error",...H.data!==void 0&&{data:H.data}}};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"error",message:J,timestamp:Date.now()},W?.sessionId);else await W?.send(J)}).catch((H)=>this._onerror(Error(`Failed to send response: ${H}`))).finally(()=>{this._requestHandlerAbortControllers.delete(b.id)})}_onprogress(b){let{progressToken:w,...$}=b.params,W=Number(w),Q=this._progressHandlers.get(W);if(!Q){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(b)}`));return}let G=this._responseHandlers.get(W),D=this._timeoutInfo.get(W);if(D&&G&&D.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(X){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),G(X);return}Q($)}_onresponse(b){let w=Number(b.id),$=this._requestResolvers.get(w);if($){if(this._requestResolvers.delete(w),T1(b))$(b);else{let G=new u(b.error.code,b.error.message,b.error.data);$(G)}return}let W=this._responseHandlers.get(w);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(b)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let Q=!1;if(T1(b)&&b.result&&typeof b.result==="object"){let G=b.result;if(G.task&&typeof G.task==="object"){let D=G.task;if(typeof D.taskId==="string")Q=!0,this._taskProgressTokens.set(D.taskId,w)}}if(!Q)this._progressHandlers.delete(w);if(T1(b))W(b);else{let G=u.fromError(b.error.code,b.error.message,b.error.data);W(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(b,w,$){let{task:W}=$??{};if(!W){try{yield{type:"result",result:await this.request(b,w,$)}}catch(G){yield{type:"error",error:G instanceof u?G:new u(c.InternalError,String(G))}}return}let Q;try{let G=await this.request(b,iw,$);if(G.task)Q=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new u(c.InternalError,"Task creation did not return a task");while(!0){let D=await this.getTask({taskId:Q},$);if(yield{type:"taskStatus",task:D},Fw(D.status)){if(D.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};else if(D.status==="failed")yield{type:"error",error:new u(c.InternalError,`Task ${Q} failed`)};else if(D.status==="cancelled")yield{type:"error",error:new u(c.InternalError,`Task ${Q} was cancelled`)};return}if(D.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};return}let X=D.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((Y)=>setTimeout(Y,X)),$?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof u?G:new u(c.InternalError,String(G))}}}request(b,w,$){let{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G,task:D,relatedTask:X}=$??{};return new Promise((Y,H)=>{let J=(M)=>{H(M)};if(!this._transport){J(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(b.method),D)this.assertTaskCapability(b.method)}catch(M){J(M);return}$?.signal?.throwIfAborted();let z=this._requestMessageId++,O={...b,jsonrpc:"2.0",id:z};if($?.onprogress)this._progressHandlers.set(z,$.onprogress),O.params={...b.params,_meta:{...b.params?._meta||{},progressToken:z}};if(D)O.params={...O.params,task:D};if(X)O.params={...O.params,_meta:{...O.params?._meta||{},[Pw]:X}};let q=(M)=>{this._responseHandlers.delete(z),this._progressHandlers.delete(z),this._cleanupTimeout(z),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:z,reason:String(M)}},{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let v=M instanceof u?M:new u(c.RequestTimeout,String(M));H(v)};this._responseHandlers.set(z,(M)=>{if($?.signal?.aborted)return;if(M instanceof Error)return H(M);try{let v=Bw(w,M.result);if(!v.success)H(v.error);else Y(v.data)}catch(v){H(v)}}),$?.signal?.addEventListener("abort",()=>{q($?.signal?.reason)});let B=$?.timeout??zO,K=()=>q(u.fromError(c.RequestTimeout,"Request timed out",{timeout:B}));this._setupTimeout(z,B,$?.maxTotalTimeout,K,$?.resetTimeoutOnProgress??!1);let I=X?.taskId;if(I){let M=(v)=>{let S=this._responseHandlers.get(z);if(S)S(v);else this._onerror(Error(`Response handler missing for side-channeled request ${z}`))};this._requestResolvers.set(z,M),this._enqueueTaskMessage(I,{type:"request",message:O,timestamp:Date.now()}).catch((v)=>{this._cleanupTimeout(z),H(v)})}else this._transport.send(O,{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((M)=>{this._cleanupTimeout(z),H(M)})})}async getTask(b,w){return this.request({method:"tasks/get",params:b},n0,w)}async getTaskResult(b,w,$){return this.request({method:"tasks/result",params:b},w,$)}async listTasks(b,w){return this.request({method:"tasks/list",params:b},i0,w)}async cancelTask(b,w){return this.request({method:"tasks/cancel",params:b},KG,w)}async notification(b,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(b.method);let $=w?.relatedTask?.taskId;if($){let D={...b,jsonrpc:"2.0",params:{...b.params,_meta:{...b.params?._meta||{},[Pw]:w.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:D,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(b.method)&&!b.params&&!w?.relatedRequestId&&!w?.relatedTask){if(this._pendingDebouncedNotifications.has(b.method))return;this._pendingDebouncedNotifications.add(b.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(b.method),!this._transport)return;let D={...b,jsonrpc:"2.0"};if(w?.relatedTask)D={...D,params:{...D.params,_meta:{...D.params?._meta||{},[Pw]:w.relatedTask}}};this._transport?.send(D,w).catch((X)=>this._onerror(X))});return}let G={...b,jsonrpc:"2.0"};if(w?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[Pw]:w.relatedTask}}};await this._transport.send(G,w)}setRequestHandler(b,w){let $=a4(b);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let G=b6(b,W);return Promise.resolve(w(G,Q))})}removeRequestHandler(b){this._requestHandlers.delete(b)}assertCanSetRequestHandler(b){if(this._requestHandlers.has(b))throw Error(`A request handler for ${b} already exists, which would be overridden`)}setNotificationHandler(b,w){let $=a4(b);this._notificationHandlers.set($,(W)=>{let Q=b6(b,W);return Promise.resolve(w(Q))})}removeNotificationHandler(b){this._notificationHandlers.delete(b)}_cleanupTaskProgressHandler(b){let w=this._taskProgressTokens.get(b);if(w!==void 0)this._progressHandlers.delete(w),this._taskProgressTokens.delete(b)}async _enqueueTaskMessage(b,w,$){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(b,w,$,W)}async _clearTaskQueue(b,w){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(b,w);for(let W of $)if(W.type==="request"&&u4(W.message)){let Q=W.message.id,G=this._requestResolvers.get(Q);if(G)G(new u(c.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Q);else this._onerror(Error(`Resolver missing for request ${Q} during task ${b} cleanup`))}}}async _waitForTaskUpdate(b,w){let $=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(b);if(W?.pollInterval)$=W.pollInterval}catch{}return new Promise((W,Q)=>{if(w.aborted){Q(new u(c.InvalidRequest,"Request cancelled"));return}let G=setTimeout(W,$);w.addEventListener("abort",()=>{clearTimeout(G),Q(new u(c.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(b,w){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(W)=>{if(!b)throw Error("No request provided");return await $.createTask(W,b.id,{method:b.method,params:b.params},w)},getTask:async(W)=>{let Q=await $.getTask(W,w);if(!Q)throw new u(c.InvalidParams,"Failed to retrieve task: Task not found");return Q},storeTaskResult:async(W,Q,G)=>{await $.storeTaskResult(W,Q,G,w);let D=await $.getTask(W,w);if(D){let X=v1.parse({method:"notifications/tasks/status",params:D});if(await this.notification(X),Fw(D.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return $.getTaskResult(W,w)},updateTaskStatus:async(W,Q,G)=>{let D=await $.getTask(W,w);if(!D)throw new u(c.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(Fw(D.status))throw new u(c.InvalidParams,`Cannot update task "${W}" from terminal status "${D.status}" to "${Q}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(W,Q,G,w);let X=await $.getTask(W,w);if(X){let Y=v1.parse({method:"notifications/tasks/status",params:X});if(await this.notification(Y),Fw(X.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,w)}}}}function TG(b){return b!==null&&typeof b==="object"&&!Array.isArray(b)}function EG(b,w){let $={...b};for(let W in w){let Q=W,G=w[Q];if(G===void 0)continue;let D=$[Q];if(TG(D)&&TG(G))$[Q]={...D,...G};else $[Q]=G}return $}var GJ=RW(t6(),1),DJ=RW(QJ(),1);function KK(){let b=new GJ.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return DJ.default(b),b}class GW{constructor(b){this._ajv=b??KK()}getValidator(b){let w="$id"in b&&typeof b.$id==="string"?this._ajv.getSchema(b.$id)??this._ajv.compile(b):this._ajv.compile(b);return($)=>{if(w($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}class DW{constructor(b){this._server=b}requestStream(b,w,$){return this._server.requestStream(b,w,$)}async getTask(b,w){return this._server.getTask({taskId:b},w)}async getTaskResult(b,w,$){return this._server.getTaskResult({taskId:b},w,$)}async listTasks(b,w){return this._server.listTasks(b?{cursor:b}:void 0,w)}async cancelTask(b,w){return this._server.cancelTask({taskId:b},w)}}function XJ(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"tools/call":if(!b.tools?.call)throw Error(`${$} does not support task creation for tools/call (required for ${w})`);break;default:break}}function YJ(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!b.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!b.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}class XW extends w6{constructor(b,w){super(w);if(this._serverInfo=b,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(u1.options.map(($,W)=>[$,W])),this.isMessageIgnored=($,W)=>{let Q=this._loggingLevels.get(W);return Q?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(Q):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new GW,this.setRequestHandler(h4,($)=>this._oninitialize($)),this.setNotificationHandler(f4,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(t4,async($,W)=>{let Q=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=$.params,D=u1.safeParse(G);if(D.success)this._loggingLevels.set(Q,D.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new DW(this)};return this._experimental}registerCapabilities(b){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=EG(this._capabilities,b)}setRequestHandler(b,w){let W=S0(b)?.method;if(!W)throw Error("Schema is missing a method literal");let Q;if(gw(W)){let D=W;Q=D._zod?.def?.value??D.value}else{let D=W;Q=D._def?.value??D.value}if(typeof Q!=="string")throw Error("Schema method literal must be a string");if(Q==="tools/call"){let D=async(X,Y)=>{let H=Bw(C1,X);if(!H.success){let q=H.error instanceof Error?H.error.message:String(H.error);throw new u(c.InvalidParams,`Invalid tools/call request: ${q}`)}let{params:J}=H.data,z=await Promise.resolve(w(X,Y));if(J.task){let q=Bw(iw,z);if(!q.success){let B=q.error instanceof Error?q.error.message:String(q.error);throw new u(c.InvalidParams,`Invalid task creation result: ${B}`)}return q.data}let O=Bw(p0,z);if(!O.success){let q=O.error instanceof Error?O.error.message:String(O.error);throw new u(c.InvalidParams,`Invalid tools/call result: ${q}`)}return O.data};return super.setRequestHandler(b,D)}return super.setRequestHandler(b,w)}assertCapabilityForMethod(b){switch(b){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${b})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${b})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${b})`);break;case"ping":break}}assertNotificationCapability(b){switch(b){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${b})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${b})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${b})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${b})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(b){if(!this._capabilities)return;switch(b){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${b})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${b})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${b})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${b})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${b})`);break;case"ping":case"initialize":break}}assertTaskCapability(b){YJ(this._clientCapabilities?.tasks?.requests,b,"Client")}assertTaskHandlerCapability(b){if(!this._capabilities)return;XJ(this._capabilities.tasks?.requests,b,"Server")}async _oninitialize(b){let w=b.params.protocolVersion;return this._clientCapabilities=b.params.capabilities,this._clientVersion=b.params.clientInfo,{protocolVersion:zG.includes(w)?w:k4,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"},x0)}async createMessage(b,w){if(b.tools||b.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(b.messages.length>0){let $=b.messages[b.messages.length-1],W=Array.isArray($.content)?$.content:[$.content],Q=W.some((Y)=>Y.type==="tool_result"),G=b.messages.length>1?b.messages[b.messages.length-2]:void 0,D=G?Array.isArray(G.content)?G.content:[G.content]:[],X=D.some((Y)=>Y.type==="tool_use");if(Q){if(W.some((Y)=>Y.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!X)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(X){let Y=new Set(D.filter((J)=>J.type==="tool_use").map((J)=>J.id)),H=new Set(W.filter((J)=>J.type==="tool_result").map((J)=>J.toolUseId));if(Y.size!==H.size||![...Y].every((J)=>H.has(J)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(b.tools)return this.request({method:"sampling/createMessage",params:b},e4,w);return this.request({method:"sampling/createMessage",params:b},r4,w)}async elicitInput(b,w){switch(b.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=b;return this.request({method:"elicitation/create",params:W},o0,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=b.mode==="form"?b:{...b,mode:"form"},Q=await this.request({method:"elicitation/create",params:W},o0,w);if(Q.action==="accept"&&Q.content&&W.requestedSchema)try{let D=this._jsonSchemaValidator.getValidator(W.requestedSchema)(Q.content);if(!D.valid)throw new u(c.InvalidParams,`Elicitation response content does not match requested schema: ${D.errorMessage}`)}catch(G){if(G instanceof u)throw G;throw new u(c.InternalError,`Error validating elicitation response: ${G instanceof Error?G.message:String(G)}`)}return Q}}}createElicitationCompletionNotifier(b,w){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:b}},w)}async listRoots(b,w){return this.request({method:"roots/list",params:b},s4,w)}async sendLoggingMessage(b,w){if(this._capabilities.logging){if(!this.isMessageIgnored(b.level,w))return this.notification({method:"notifications/message",params:b})}}async sendResourceUpdated(b){return this.notification({method:"notifications/resources/updated",params:b})}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 HJ={name:"@sequenzy/mcp",version:"0.0.115",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"bunx --bun tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^7.0.2"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var YW=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],JJ={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function IK(b){let $=(b??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return $.length>0?$:"https://sequenzy.com"}function ib(b){let w=b?.trim();return w?w:void 0}function eb(b){return encodeURIComponent(b)}function Db(b,w){return`${b}${w}`}function Xb(b,w=""){return`/dashboard/company/${eb(b)}${w}`}function zJ(b,w,$){return Db(b,`${Xb(w,"/settings")}?tab=${encodeURIComponent($)}`)}function ZK(b,w){let $=YW.map((W)=>[W,w?zJ(b,w,W):""]);return Object.fromEntries($)}function Yw(b={},w){let $=IK(w),W=ib(b.companyId),Q={},G=ZK($,W);if(!W)return{appUrl:$,routeTemplates:JJ,settingsTabValues:YW,urls:Q,settingsUrls:G};Q.dashboard=Db($,Xb(W)),Q.campaigns=Db($,Xb(W,"/campaign")),Q.landingPages=Db($,Xb(W,"/landing-pages")),Q.sequences=Db($,Xb(W,"/sequences")),Q.settings=Db($,Xb(W,"/settings")),Q.emails=Db($,Xb(W,"/emails")),Q.subscribers=Db($,Xb(W,"/subscribers")),Q.sentEmails=Db($,Xb(W,"/sent-emails")),Q.segments=Db($,Xb(W,"/segments")),Q.metrics=Db($,Xb(W,"/metrics")),Q.transactional=Db($,Xb(W,"/transactional"));let D=ib(b.campaignId);if(D)Q.campaign=Db($,Xb(W,`/campaign/${eb(D)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let X=ib(b.landingPageId);if(X)Q.landingPage=Db($,Xb(W,`/landing-pages/${eb(X)}`));let Y=ib(b.sequenceId);if(Y)Q.sequence=Db($,Xb(W,`/sequences/${eb(Y)}`));let H=ib(b.emailId)??ib(b.templateId);if(H)Q.email=Db($,Xb(W,`/emails/${eb(H)}`)),Q.template=Q.email;let J=ib(b.transactionalId);if(J)Q.transactionalEmail=Db($,Xb(W,`/transactional/${eb(J)}`));let z=ib(b.emailSendId);if(z)Q.emailSend=Db($,Xb(W,`/sent-emails/${eb(z)}`));let O=ib(b.domainId);if(O)Q.domain=Db($,Xb(W,`/settings/domain/${eb(O)}`)),Q.domainVerify=`${Q.domain}/verify`;let q=ib(b.status);if(q)Q.campaignList=Db($,Xb(W,`/campaign/list/${eb(q)}`)),Q.sequenceList=Db($,Xb(W,`/sequences/list/${eb(q)}`));let B=ib(b.settingsTab);if(B)Q.settingsTab=zJ($,W,B);return{appUrl:$,routeTemplates:JJ,settingsTabValues:YW,urls:Q,settingsUrls:G}}var AJ=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function OJ(b){try{let w;switch(b){case"sequenzy://dashboard":w=await A("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await A("GET","/api/v1/account"),W=Ew()??$.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");w=await A("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":w=await A("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":w=await A("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":w=await A("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":w=await A("GET","/api/v1/sequences");break;case"sequenzy://templates":w=await A("GET","/api/v1/templates");break;case"sequenzy://segments":w=await A("GET","/api/v1/segments");break;case"sequenzy://tags":w=await A("GET","/api/v1/tags");break;case"sequenzy://health":w=await A("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":w=Yw();break;default:throw Error(`Unknown resource: ${b}`)}return{contents:[{uri:b,mimeType:"application/json",text:JSON.stringify(w,null,2)}]}}catch(w){return{contents:[{uri:b,mimeType:"text/plain",text:yw(w)}]}}}function y(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}function P(b,w){let $=b[w];if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function Z(b,w,$){let W=P(w,$);if(W===void 0)throw Error(`\`${$}\` is required when calling \`${b}\`.`);return W}var Tw='For exact historical Poll/NPS respondents, use field `pollResponse`, operator `is`, and a JSON value shaped like {"v":1,"campaignId":"camp_123","blockId":"poll_1","match":{"kind":"answer","value":"loved"}}. For NPS buckets, use match {"kind":"npsBucket","bucket":"promoters"}; bucket may be `promoters`, `passives`, or `detractors`.',Hw='Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the `html` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Repeat blocks use { type: \'repeat\', source: \'items\', itemAlias: \'item\', children: [...] }. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',Jw='Replacement Sequenzy email blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',W1='Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer `html`; Sequenzy stores it as one raw HTML block and does not recreate it as native blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Blocks can include repeat blocks over array variables such as items. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',D0="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",qJ="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",HW=500,JW=500,lb={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},v$=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],k$={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},jK={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},Q1={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:jK,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},G1={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date"],description:"Use duration for a fixed wait, or until_date to resolve a date from the trigger event."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},zW={type:"object",description:"Type-aware patch for the existing node. Start from get_sequence.sequence.nodes[].config. For logic_delay, set exactly one of delay ({ days, hours, minutes }), delayMs, or waitUntil; optional label is also accepted. For action_email, use name/label, subject, previewText, html/htmlContent or blocks, isTransactional, and sender/reply identity fields. For action_sms, use text, blocks, imageUrls, label, or ineligibleAction. Other node types accept their editable config keys. Managed IDs, nodeType conversion, and branch path IDs/count are not editable here; use edit_sequence_graph for topology. Webhook header patches are merged, and redacted values from get_sequence must be omitted or replaced with a real new value.",additionalProperties:!0},C$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:zW,expectedUpdatedAt:{type:"string",description:"Required optimistic-concurrency value from get_sequence.sequence.nodes[].updatedAt. The update is rejected if that node or its linked email content changed after it was read."}},required:["nodeId","changes","expectedUpdatedAt"],additionalProperties:!1},D1=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],X1=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var VK=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_websites","check_website","get_integration_guide","get_subscriber","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_forms","get_form_embed","get_recipient_suppression","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_subject_lines","generate_sms","get_sms_settings"]),NK=new Set(["select_company","create_company","update_company","update_sync_rules","update_shopify_automation_settings","create_api_key","add_sending_domain","add_website","verify_sending_domain","add_subscriber","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","upsert_products","delete_product","attach_product_file","remove_product_file","upload_image_asset","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","set_template_localization","sync_template_localizations","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_form","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback","remove_recipient_suppression"]),TK=new Set(["send_test_email","send_test_sms","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","add_sending_domain","add_website","verify_sending_domain","enable_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery","remove_recipient_suppression"]),EK=new Set(["remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook","remove_recipient_suppression"]);function _K(b){let w=VK.has(b),$=NK.has(b);if(w===$)throw Error(`MCP tool "${b}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:w,destructiveHint:w?!1:EK.has(b),openWorldHint:TK.has(b)}}function LJ(b){return{...b,annotations:{...b.annotations,..._K(b.name)}}}var AW={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],pollResponse:["is"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"]},SK=Object.entries(AW).map(([b,w])=>`${b}: ${w.join(", ")}`).join("; "),OW={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","pollResponse","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct"],description:`Filter field. Use \`phone\` with is_not_empty/is_empty to check whether a subscriber has a phone number, and \`smsStatus\` (is/is_not one of \`subscribed\`, \`unsubscribed\`, \`not_subscribed\`) for SMS marketing consent. Use \`event\` for custom subscriber events, \`segment\` for saved segment membership, \`stripeProduct\`/\`stripeCurrentProduct\`/\`stripeTrialProduct\` for Stripe product-based segments, and \`commerceProduct\` for products purchased through commerce orders - the value is \`provider:productId\` (provider one of \`shopify\`, \`woocommerce\`, \`api\`; product ids are provider-scoped), optionally with an order-count threshold (\`provider:productId:count\`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (\`emailSent\`, \`emailDelivered\`, \`emailOpened\`, \`emailClicked\`, \`emailBounced\`, \`emailComplained\`) accept a time range as the value, a specific campaign via \`campaign:<campaign_id>\`, or \`count:timeRange\` (e.g. \`10:30d\`, \`10:all\`) with at_least/less_than_count to segment by number of opens/clicks. ${Tw}`},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${SK}.`},value:{type:"string",description:`Filter value. For custom attribute empty checks, use \`attributeName:\` such as \`last_logged_in:\`. Event examples: \`saas.purchase:30d\`, \`saas.purchase:all\`, or \`saas.purchase:5:30d\` for thresholds. Segment values are segment IDs. Stripe product examples: \`prod_123\` for bought/didn't buy/current/trialing, \`prod_123:3\` for payment thresholds, \`prod_123:is_canceled\` for products set to cancel, \`prod_123:cancels_at:2026-05-26\`, \`prod_123:end_at:2026-05-26\`, or \`prod_123:start_at:7 days ago\` for product-scoped dates. Engagement examples: \`7d\`, \`30d\`, \`90d\`, \`180d\`, \`all\` for rolling time windows, \`campaign:<campaign_id>\` to scope to a specific sent campaign (use \`list_campaigns\` to find IDs), or \`count:timeRange\` like \`10:30d\` / \`10:all\` with at_least/less_than_count operators (e.g. emailClicked at_least \`10:all\` = clicked 10 or more times ever). ${Tw}`}},required:["field","operator","value"],additionalProperties:!1},qW={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function u$(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(typeof w!=="object"||w===null)return w;let $=w;if(typeof $.id==="string"&&$.id.trim()!=="")return $;return{...$,id:crypto.randomUUID()}})}function x$(b){if(typeof b!=="object"||b===null)return b;let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=u$([w]);return Array.isArray($)?$[0]:w}if(w.kind!=="group")return b;return{...w,id:typeof w.id==="string"&&w.id.trim()!==""?w.id:crypto.randomUUID(),children:Array.isArray(w.children)?w.children.map(x$):[]}}function RK(b){let w=b.indexOf(":");return w!==-1&&b.substring(0,w).trim().length>0}function vK(b){let w=b.indexOf(":");return w!==-1&&b.substring(w+1).trim().length>0}function UJ(b){if(b==="all")return!0;let w=b.match(/^(\d+)d$/);if(!w?.[1])return!1;let $=Number.parseInt(w[1],10);return Number.isInteger($)&&$>0}function kK(b,w){let $=w.split(":");if(b==="at_least"||b==="less_than_count"){if($.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let G=$.slice(0,-2).join(":").trim(),D=$.at(-2),X=$.at(-1),Y=D===void 0?Number.NaN:Number.parseInt(D,10);return G&&Number.isInteger(Y)&&Y>0&&X!==void 0&&UJ(X)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if($.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=$.slice(0,-1).join(":").trim(),Q=$.at(-1);return W&&Q!==void 0&&UJ(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function CK(b){let w=b.indexOf(":");if(w===-1)return{productId:b,subfilter:null,rawValue:null};let $=b.substring(0,w),W=b.substring(w+1),Q=W.indexOf(":");if(Q===-1)return{productId:$,subfilter:W,rawValue:null};return{productId:$,subfilter:W.substring(0,Q),rawValue:W.substring(Q+1)}}function uK(b){return b.trim().toLowerCase().replace(/[-\s]+/g,"_")}function xK(b){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(b)}function yK(b,w){if(w==="cancels_at"||w==="cancel_at"||w==="cancellation_at")return!0;if(b==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(w);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(w)}function hK(b){return["is","is_not","gte","lte","gt","lt"].includes(b)}function fK(b,w,$){if(b==="stripeProduct"){if(w!=="at_least"&&w!=="less_than_count")return null;let X=$.indexOf(":");if(X===-1)return null;let Y=$.substring(0,X).trim(),H=Number.parseInt($.substring(X+1).trim(),10);return Y&&Number.isInteger(H)&&H>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(b!=="stripeCurrentProduct"&&b!=="stripeTrialProduct")return null;let{productId:W,subfilter:Q,rawValue:G}=CK($);if(!W.trim())return"Stripe product filters must include a product ID.";if(!Q)return w==="is"||w==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let D=uK(Q);if(xK(D))return w==="is"||w==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!yK(b,D))return`Unsupported Stripe product subfilter "${Q}".`;if(!hK(w))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return G?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var cK=new Set(["shopify","woocommerce","api"]);function nK(b,w){let $=w.trim(),W=$.indexOf(":");if(W!==-1&&cK.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Product filters must include a product ID, like "shopify:42".';if(b!=="at_least"&&b!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let G=$.substring(0,Q).trim(),D=Number.parseInt($.substring(Q+1).trim(),10);return G&&Number.isInteger(D)&&D>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function gK(b){let w;try{w=JSON.parse(b)}catch{return`Poll response filters must use valid JSON. ${Tw}`}if(!y(w)||w.v!==1||typeof w.campaignId!=="string"||!w.campaignId.trim()||typeof w.blockId!=="string"||!w.blockId.trim()||!y(w.match))return`Poll response filter context is invalid. ${Tw}`;let $=w.match;if($.kind==="answer"&&typeof $.value==="string"&&$.value.length>0)return null;if($.kind==="npsBucket"&&($.bucket==="promoters"||$.bucket==="passives"||$.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${Tw}`}function y$(b){if(typeof b!=="object"||b===null)return"Segment filters must be objects.";let w=b,$=w.field,W=w.operator,Q=w.value;if(typeof $!=="string"||!($ in AW))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let G=AW[$];if(!G.includes(W))return`Operator "${W}" is not supported for ${$} filters. Use one of: ${G.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof Q!=="string"||Q.trim().length===0))return`Segment filter "${$}" must include a value.`;if($==="attribute"&&typeof Q==="string"){if(!RK(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!vK(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let D=kK(W,Q);if(D)return D}if($==="pollResponse"&&typeof Q==="string"){let D=gK(Q);if(D)return D}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof Q==="string"){let D=fK($,W,Q);if(D)return D}if($==="commerceProduct"&&typeof Q==="string"){let D=nK(W,Q);if(D)return D}if($==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof Q==="string"&&Q.split(",").map((X)=>X.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function h$(b){if(typeof b!=="object"||b===null)return[];let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=y$(w);return $?[$]:[]}if(Array.isArray(w.children))return w.children.flatMap(h$);return[]}function _b(b,w,$){if(w.html!==void 0&&w.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`, not both.`);if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error(`\`blocks\` must be an array when calling \`${b}\`.`);if($?.requireContent&&w.html===void 0&&w.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`.`)}function Y1(b,w){if(w.labels===void 0)return;if(!Array.isArray(w.labels))throw Error(`\`labels\` must be an array when calling \`${b}\`.`);if(w.labels.some(($)=>typeof $!=="string"||$.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${b}\`.`)}function FJ(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!w&&!$)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=y$(Q);return G?[G]:[]}):h$(b.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function KJ(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(b.name===void 0&&b.filterJoinOperator===void 0&&!w&&!$)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=y$(Q);return G?[G]:[]}):$?h$(b.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var LW=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"];function UW(b,w,$){if(w[$]!==void 0&&!y(w[$]))throw Error(`\`${$}\` must be an object when calling \`${b}\`.`)}function BJ(b,w,$){if(w[$]!==void 0&&!Array.isArray(w[$]))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`)}function MJ(b){let w=new Set(["companyId",...LW]),$=Object.keys(b).filter((Q)=>!w.has(Q));if($.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${$.length===1?"":"s"}: ${$.map((Q)=>`\`${Q}\``).join(", ")}.`);let W={};for(let Q of LW)if(b[Q]!==void 0)W[Q]=b[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${LW.map((Q)=>`\`${Q}\``).join(", ")} when calling \`update_company\`.`);for(let Q of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"])if(b[Q]!==void 0&&typeof b[Q]!=="string")throw Error(`\`${Q}\` must be a string when calling \`update_company\`.`);if(UW("update_company",b,"brandColors"),UW("update_company",b,"socialLinks"),UW("update_company",b,"pricing"),BJ("update_company",b,"valueProps"),BJ("update_company",b,"testimonials"),typeof b.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(b.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let Q of["fromEmail","replyTo"]){let G=b[Q];if(typeof G==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G.trim()))throw Error(`\`${Q}\` must be a valid email address when calling \`update_company\`.`)}if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_company`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_company`.");return W}var IJ=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function mK(b){return IJ.some((w)=>b[w]!==void 0)}function iK(b){if(typeof b.nodeType==="string")return b.nodeType==="action_email";return b.type===void 0||b.type==="email"}function f$(b,w,$){for(let W of IJ){let Q=$[W];if(Q!==void 0&&typeof Q!=="string")throw Error(`\`${W}\` must be a string for ${w} when calling \`${b}\`.`)}if($.senderProfileId!==void 0&&$.fromEmail!==void 0)throw Error(`Provide either \`senderProfileId\` or \`fromEmail\` for ${w} when calling \`${b}\`, not both.`);if($.replyProfileId!==void 0&&$.replyTo!==void 0)throw Error(`Provide either \`replyProfileId\` or \`replyTo\` for ${w} when calling \`${b}\`, not both.`);if($.replyToName!==void 0&&$.replyTo===void 0)throw Error(`\`replyToName\` requires \`replyTo\` for ${w} when calling \`${b}\`.`)}function PW(b,w,$){if(mK($)&&!iK($))throw Error(`Sender identity fields are only supported for email steps at ${w} when calling \`${b}\`.`);f$(b,w,$)}function PJ(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))f$(b,`${w}[${Q}]`,W)})}function BW(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))PW(b,`${w}[${Q}]`,W)})}function lK(b){if(PJ("update_sequence","emails",b.emails),PJ("update_sequence","steps",b.steps),y(b.insertSteps))BW("update_sequence","insertSteps.steps",b.insertSteps.steps);if(!y(b.branch))return;if(Array.isArray(b.branch.branches))b.branch.branches.forEach(($,W)=>{if(y($))BW("update_sequence",`branch.branches[${W}].steps`,$.steps)});BW("update_sequence","branch.elseSteps",b.branch.elseSteps)}function ZJ(b){if(b.fromEmail!==void 0&&b.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(b.replyTo!==void 0&&b.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(b.clearEnrollmentFieldPath===!0&&b.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(b.clearSendingWindow===!0&&b.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(b.clearBccEmails===!0&&b.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(b.branch!==void 0&&b.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");lK(b);let w={...b};if(delete w.clearEnrollmentFieldPath,delete w.clearSendingWindow,delete w.clearBccEmails,b.clearEnrollmentFieldPath===!0)w.enrollmentFieldPath=null;if(b.clearSendingWindow===!0)w.sendingWindow=null;if(b.clearBccEmails===!0)w.bccEmails=null;return w}function jJ(b,w,$){let W=Z(b,w,"nodeId");if(!y(w.changes)||Object.keys(w.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${b}\`.`);let Q=Z(b,w,"expectedUpdatedAt");return{nodeId:W,changes:w.changes,expectedUpdatedAt:Q}}function VJ(b){let w=jJ("update_sequence_node",b,"the node update");return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:[w]}}function NJ(b){if(!Array.isArray(b.updates)||b.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let w=new Set,$=b.updates.map((W,Q)=>{if(!y(W))throw Error(`\`updates[${Q}]\` must be an object when calling \`update_sequence_nodes\`.`);let G=jJ("update_sequence_nodes",W,`updates[${Q}]`),D=String(G.nodeId);if(w.has(D))throw Error(`\`updates[${Q}]\` targets duplicate nodeId '${D}' when calling \`update_sequence_nodes\`.`);return w.add(D),G});return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:$}}function TJ(b){let w=Z("edit_sequence_graph",b,"action"),$=Z("edit_sequence_graph",b,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(w))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let Q=P(b,"nodeId"),G=P(b,"afterNodeId"),D=P(b,"beforeNodeId"),X=b.edges;if(w!=="replace_edges"&&!Q)throw Error(`\`nodeId\` is required for ${w} when calling \`edit_sequence_graph\`.`);if(w==="replace_edges"&&Q)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let Y=w==="move_node"||w==="duplicate_node";if(Y&&(G?1:0)+(D?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${w} when calling \`edit_sequence_graph\`.`);if(!Y&&(G||D))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${w} when calling \`edit_sequence_graph\`.`);if((w==="replace_edges"||w==="delete_node"&&X!==void 0)&&(!Array.isArray(X)||X.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${w} when calling \`edit_sequence_graph\`.`);if((w==="move_node"||w==="duplicate_node")&&X!==void 0)throw Error(`\`edges\` is not used with ${w} when calling \`edit_sequence_graph\`.`);let H=Array.isArray(X)?X.map((J,z)=>{if(!y(J))throw Error(`\`edges\` item ${z+1} must be an object when calling \`edit_sequence_graph\`.`);let O=Z("edit_sequence_graph",J,"sourceNodeId"),q=Z("edit_sequence_graph",J,"targetNodeId");if(J.condition!==void 0&&J.condition!==null&&!y(J.condition))throw Error(`\`edges\` item ${z+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:O,targetNodeId:q,...y(J.condition)?{condition:J.condition}:{}}}):void 0;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},graphEdit:{action:w,expectedRevision:$,...Q?{nodeId:Q}:{},...G?{afterNodeId:G}:{},...D?{beforeNodeId:D}:{},...H?{edges:H}:{}}}}function EJ(b){let w=b.type==="sms",$;if(w){PW("insert_sequence_step","SMS step",b);let Q=P(b,"text"),G=Array.isArray(b.blocks)&&b.blocks.length>0;if(Q===void 0&&!G)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");$={type:"sms"};for(let D of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(b[D]!==void 0)$[D]=b[D]}else{_b("insert_sequence_step",b,{requireContent:!0}),f$("insert_sequence_step","email step",b),$={subject:Z("insert_sequence_step",b,"subject")};for(let Q of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"])if(b[Q]!==void 0)$[Q]=b[Q]}let W={steps:[$]};if(b.afterNodeId!==void 0)W.afterNodeId=b.afterNodeId;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},insertSteps:W}}function _J(b){let w=P(b,"subscriberId"),$=b.fieldValues,W=$===void 0?void 0:Array.isArray($)?$:void 0;if($!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let Q=W?.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0)??[];if(W?.some((X)=>typeof X!=="string")||W!==void 0&&Q.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(w!==void 0===Q.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let G=P(b,"fieldPath"),D=P(b,"reason");return{...w!==void 0&&{subscriberId:w},...G!==void 0&&{fieldPath:G},...Q.length>0&&{fieldValues:Q},...typeof b.dryRun==="boolean"&&{dryRun:b.dryRun},...D!==void 0&&{reason:D}}}function SJ(b){_b("create_campaign",b),Y1("create_campaign",b);let w=P(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0,Q=b.templateId!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(w&&($||W||Q))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!w&&P(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function RJ(b){_b("create_template",b),Y1("create_template",b);let w=P(b,"prompt")!==void 0,$=[w,b.html!==void 0,b.blocks!==void 0].filter(Boolean).length;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_template`.");if($!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!w&&P(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function vJ(b){if(P(b,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(b.targetLists!==void 0&&!y(b.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(b.sendTimeOptimization!==void 0){if(typeof b.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(b.spreadOverHours!==void 0){if(typeof b.spreadOverHours!=="number"||!Number.isInteger(b.spreadOverHours)||b.spreadOverHours<1||b.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(b.recurringInterval!==void 0&&b.recurringInterval!=="weekly"&&b.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function c$(b,w,$){let W=new Set(["companyId","landingPageId","name","slug","content"]),Q=Object.keys(w).filter((G)=>!W.has(G));if(Q.length>0)throw Error(`\`${b}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${Q.length===1?"":"s"}: ${Q.map((G)=>`\`${G}\``).join(", ")}.`);if($.requireUpdate&&w.name===void 0&&w.slug===void 0&&w.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${b}\`.`);return{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.content!==void 0&&{content:w.content}}}function kJ(b){let w=new Set(["companyId","domain","verify"]),$=Object.keys(b).filter((W)=>!w.has(W));if($.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}.`);if(b.domain===void 0&&b.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...b.domain!==void 0&&{domain:b.domain},...typeof b.verify==="boolean"&&{verify:b.verify}}}function CJ(b){_b("create_transactional_email",b);let w=P(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(w&&($||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!w&&!$&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!w&&P(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var X0={type:"object",description:"Update Subscriber config. firstName, lastName, and customAttributeUpdates values may use trigger-event merge tags such as {{event.plan}}. Number and boolean values must be a literal or one standalone merge tag and are coerced after resolution.",properties:{label:{type:"string"},firstName:{type:["string","null"],description:"First name literal or merge tag; null clears the field."},lastName:{type:["string","null"],description:"Last name literal or merge tag; null clears the field."},status:{type:"string",enum:["active","unsubscribed","bounced"]},customAttributeUpdates:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:["string","number","boolean","null"],description:"Literal scalar, null to delete, or a standalone merge tag such as {{event.plan}}, {{event.amount}}, or {{event.active}}."},valueType:{type:"string",enum:["text","number","boolean"]}},required:["name","value"]}}},additionalProperties:!0},FW={senderProfileId:{type:"string",description:"Sender profile for this step's From identity. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"From address for this step. Its domain must be configured and verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this step. Alone it only changes the visible name; with fromEmail it also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this step's Reply-To. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Reply-To address for this step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."}},n$={type:"object",description:"A step to create inside a sequence path. Use type:'delay' for a standalone delay, type:'email' for an email, type:'create_discount' for a discount action, or type:'condition' for a condition gate.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","update_subscriber","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for standalone waits or update_subscriber for action_update_attributes."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","logic_condition","action_webhook"],description:"Advanced sequence path node type. Prefer type unless creating a non-email action."},config:{...X0,description:"Config for advanced nodeType steps. For action_update_attributes, use the documented Update Subscriber fields and trigger-event merge tags; other node types accept their normal config fields.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:W1,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},delay:G1,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:Q1,name:{type:"string",description:"Email template name for email steps."},senderProfileId:{type:"string",description:"Sender profile for this email step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"From address for this email step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this email step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this email step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},replyTo:{type:"string",description:"Reply-To address for this email step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1};function uJ(b){if(!b||typeof b!=="object")return null;let w=b;if(w.success!==!1)return null;if(typeof w.error==="string")return Error(w.error);if(w.error&&typeof w.error==="object"&&typeof w.error.message==="string")return Error(w.error.message);if(typeof w.message==="string")return Error(w.message);return Error("The tool returned an unsuccessful response.")}function KW(b){return b.trim().toLowerCase().replace(/\s+/g,"-")}function pK(b){let w=new URLSearchParams;if(typeof b.query==="string"&&b.query.trim()!=="")w.set("query",b.query.trim());if(Array.isArray(b.tags)&&b.tags.length>0)w.set("tags",b.tags.filter(($)=>typeof $==="string"&&$.trim()!=="").join(","));if(typeof b.list==="string"&&b.list.trim()!=="")w.set("list",b.list.trim());if(typeof b.listId==="string"&&b.listId.trim()!=="")w.set("listId",b.listId.trim());if(typeof b.listName==="string"&&b.listName.trim()!=="")w.set("listName",b.listName.trim());if(typeof b.segmentId==="string"&&b.segmentId.trim()!=="")w.set("segmentId",b.segmentId);if(typeof b.status==="string"&&b.status.trim()!=="")w.set("status",b.status.trim());return w.set("page",String(b.page)),w.set("limit",String(b.pageSize)),w}async function yJ(b,w){let $=typeof b.limit==="number"&&Number.isFinite(b.limit)?Math.max(1,Math.trunc(b.limit)):void 0,W=Math.min(100,Math.max(1,$??100)),Q=[],G=1,D=0,X=0,Y=0;while(!0){let J=pK({query:b.query,tags:b.tags,list:b.list,listId:b.listId,listName:b.listName,segmentId:b.segmentId,status:b.status,page:G,pageSize:W}),z=await A("GET",`/api/v1/subscribers?${J.toString()}`,void 0,w);D=z.pagination?.total??z.subscribers.length,X=z.pagination?.totalPages??1,Y+=1,Q.push(...z.subscribers??[]);let O=$!==void 0&&Q.length>=$,q=z.pagination?G>=z.pagination.totalPages:(z.subscribers??[]).length<W;if(O||q)break;G+=1}let H=$!==void 0?Q.slice(0,$):Q;return{success:!0,subscribers:H,pagination:{page:1,limit:W,total:D,totalPages:X,fetchedPages:Y},returned:H.length,truncated:$!==void 0&&D>0&&H.length<D}}function oK(b){let w=typeof b.email==="string"&&b.email.trim()!==""?b.email.trim():void 0,$=typeof b.externalId==="string"&&b.externalId.trim()!==""?b.externalId.trim():void 0;return{...w?{email:w}:{},...$?{externalId:$}:{}}}function Aw(b,w){let $=oK(w);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${b}\`.`);return $}function g$(b,w){let $=new URLSearchParams;if(w?.includeMachineEngagement)$.set("includeMachineEngagement","true");let W=$.toString(),Q=W?`?${W}`:"";if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}${Q}`;return $.set("externalId",String(b.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function MW(b){if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}/notes`;let w=new URLSearchParams;return w.set("externalId",String(b.externalId)),`/api/v1/subscribers/external/notes?${w.toString()}`}async function Y0(b,w,$){return A("GET",g$(b,$),void 0,w)}function Ub(b,w,$,W){let Q=P(w,$);if(Q===void 0)return;if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function H0(b,w,$,W){let Q=Z(b,w,$);if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function zw(b,w,$,W,Q){let G=w[$];if(G===void 0)return;if(typeof G!=="number"||!Number.isInteger(G)||G<W||G>Q)throw Error(`\`${$}\` must be an integer between ${W} and ${Q} when calling \`${b}\`.`);return G}function dK(b,w){let $=[],W=Ub(b,w,"eventType",v$);if(W)$.push(W);if(w.eventTypes!==void 0){if(!Array.isArray(w.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${b}\`.`);w.eventTypes.forEach((Q,G)=>{if(typeof Q!=="string")throw Error(`\`eventTypes\` item ${G+1} must be a string when calling \`${b}\`.`);let D=Q.trim();if(!v$.includes(D))throw Error(`\`eventTypes\` item ${G+1} must be one of ${v$.join(", ")} when calling \`${b}\`.`);$.push(D)})}return[...new Set($)]}function IW(b,w){let $=new URLSearchParams,W=dK(b,w);if(W.length>0)$.set("eventTypes",W.join(","));let Q=Ub(b,w,"period",["1h","24h","7d","30d","90d"]);if(Q)$.set("period",Q);let G=P(w,"start");if(G)$.set("start",G);let D=P(w,"end");if(D)$.set("end",D);let X=zw(b,w,"page",1,1e6);if(X!==void 0)$.set("page",String(X));let Y=zw(b,w,"limit",1,500);if(Y!==void 0)$.set("limit",String(Y));if(w.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function ZW(b,w){if(w.events===void 0)return;if(!Array.isArray(w.events))throw Error(`\`events\` must be an array when calling \`${b}\`.`);let $=w.events.map((W,Q)=>{if(typeof W!=="string"||!X1.includes(W))throw Error(`\`events\` item ${Q+1} must be one of ${X1.join(", ")} when calling \`${b}\`.`);return W});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${b}\`.`);return $}function jW(b,w){if(!Array.isArray(w.emails))throw Error(`\`emails\` must be an array when calling \`${b}\`.`);let $=[];if(w.emails.forEach((W,Q)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${Q+1} must be a string when calling \`${b}\`.`);let G=W.trim();if(G.length>0)$.push(G)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${b}\`.`);if($.length>HW)throw Error(`\`emails\` must include no more than ${HW} email addresses when calling \`${b}\`. Split larger batches into multiple calls.`);return $}function xJ(b,w,$,W){let Q=w[$];if(Q===void 0)return;if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`);let G=[];if(Q.forEach((D,X)=>{if(typeof D!=="string")throw Error(`\`${$}\` item ${X+1} must be a string when calling \`${b}\`.`);let Y=D.trim();if(Y.length>0)G.push(Y)}),G.length===0)throw Error(`\`${$}\` must include at least one ${W} when calling \`${b}\`.`);return G}function hJ(b){let $=xJ("enroll_subscribers_in_sequence",b,"emails","email address"),W=xJ("enroll_subscribers_in_sequence",b,"subscriberIds","subscriber ID"),Q=($?.length??0)+(W?.length??0);if(Q===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(Q>JW)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${JW} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let G=P(b,"targetNodeId");return{...$!==void 0&&{emails:$},...W!==void 0&&{subscriberIds:W},...G!==void 0&&{targetNodeId:G}}}import{readFileSync as tK,statSync as rK}from"node:fs";import{basename as eK}from"node:path";var sK={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function aK(b){let w=b.split(".").pop()?.toLowerCase()??"";return sK[w]??null}var bM=104857600;async function fJ(b,w){if(!z0())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let $=aK(b);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=rK(b).size;if(W>bM)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=tK(b),G=await A("POST","/api/v1/products/delivery/upload-url",{filename:eK(b),contentType:$,fileSizeBytes:W},w),D=await fetch(G.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:Q});if(!D.ok)throw Error(`File upload failed (${D.status})`);return{url:G.publicUrl,fileName:G.fileName,fileSizeBytes:W,mimeType:$}}async function m$(b){let w=P(b,"companyId");if(w)return w;let $=Ew();if($)return $;try{return(await A("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function cJ(b,w){let $=await m$(w);if(!$)throw Error(`A company is required when calling \`${b}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function H1(b,w){if(!y(b)||!w)return b;return{...b,url:w}}function nJ(b,w){if(!y(b))return b;return{...b,...w.campaign!==void 0&&{url:w.campaign},...w.campaignPreview!==void 0&&{previewUrl:w.campaignPreview}}}function J0(b,w,$){if(!Array.isArray(b)||!w)return b;return b.map((W)=>{if(!y(W))return W;let Q=P(W,"id");if(!Q)return W;let G=Yw({companyId:w,...$==="campaign"&&{campaignId:Q},...$==="landingPage"&&{landingPageId:Q},...$==="sequence"&&{sequenceId:Q},...$==="template"&&{emailId:Q},...$==="transactional"&&{transactionalId:Q}});if($==="campaign")return nJ(W,G.urls);let D=$==="sequence"?G.urls.sequence:$==="landingPage"?G.urls.landingPage:$==="template"?G.urls.email:G.urls.transactionalEmail;return H1(W,D)})}function wM(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(!y(w))return w;let $=P(w,"id");if(!$)return w;let W=Yw({companyId:$});return{...w,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var VW=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","set_template_localization","sync_template_localizations","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function gJ(b,w,$){if(!y($)||!VW.has(b))return $;let W=y($.company)?$.company:void 0,G=P($,"selectedCompanyId")??P($,"currentCompanyId")??P($,"companyId")??(W?P(W,"id"):void 0)??(W?P(W,"companyId"):void 0)??await m$(w);if(!G)return $;let D=y($.campaign)?$.campaign:void 0,X=y($.sequence)?$.sequence:void 0,Y=y($.landingPage)?$.landingPage:void 0,H=y($.template)?$.template:void 0,J=y($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,z={companyId:G,campaignId:P(w,"campaignId")??P($,"campaignId")??(D?P(D,"id"):void 0),landingPageId:P(w,"landingPageId")??P($,"landingPageId")??(Y?P(Y,"id"):void 0),sequenceId:P(w,"sequenceId")??P($,"sequenceId")??(X?P(X,"id"):void 0),emailId:P($,"templateId")??(H?P(H,"id"):void 0)??(J?P(J,"emailId"):void 0)??P(w,"templateId"),transactionalId:P(w,"transactionalId")??(J?P(J,"id"):void 0)??P(w,"idOrSlug"),emailSendId:P(w,"emailSendId")??P($,"emailSendId")??(y($.emailSend)?P($.emailSend,"id"):void 0),status:P(w,"status")},O=Yw(z),q=W?Yw({companyId:G}):void 0;return{...$,...Array.isArray($.companies)&&{companies:wM($.companies)},...Array.isArray($.campaigns)&&{campaigns:J0($.campaigns,G,"campaign")},...Array.isArray($.landingPages)&&{landingPages:J0($.landingPages,G,"landingPage")},...Array.isArray($.sequences)&&{sequences:J0($.sequences,G,"sequence")},...Array.isArray($.templates)&&{templates:J0($.templates,G,"template")},...Array.isArray($.transactional)&&{transactional:J0($.transactional,G,"transactional")},...W&&q!==void 0&&{company:{...W,url:q.urls.dashboard,settingsUrl:q.urls.settings}},...D&&O.urls.campaign!==void 0&&{campaign:nJ(D,O.urls)},...X&&O.urls.sequence!==void 0&&{sequence:H1(X,O.urls.sequence)},...Y&&O.urls.landingPage!==void 0&&{landingPage:H1(Y,O.urls.landingPage)},...H&&O.urls.email!==void 0&&{template:H1(H,O.urls.email)},...J&&O.urls.transactionalEmail!==void 0&&{transactional:H1(J,O.urls.transactionalEmail)},...y($.emailSend)&&O.urls.emailSend!==void 0&&{emailSend:H1($.emailSend,O.urls.emailSend)},appUrls:O.urls}}import{readFileSync as $M,statSync as WM}from"node:fs";import{basename as QM,extname as iJ}from"node:path";var TW=5242880,GM=Math.ceil(TW/3)*4,DM=Math.ceil(GM*1.05)+256,lJ={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},XM=new Set(Object.values(lJ));function NW(b){return b?.split(";")[0]?.trim().toLowerCase()||void 0}function YM(b){return lJ[iJ(b).toLowerCase()]}function HM(b){let w=iJ(b);return(w?b.slice(0,-w.length):b).replace(/[-_]+/g," ").trim()||"Image"}function JM(b){if(b.length>DM)throw Error("Image assets must be 5MB or smaller.")}function zM(b){let w=0,$=0;for(let Q=0;Q<b.length;Q+=1){let G=b.charCodeAt(Q);if(G===9||G===10||G===11||G===12||G===13||G===32)continue;w+=1,$=G===61?$+1:0}if(Math.floor(w*3/4)-Math.min($,2)>TW)throw Error("Image assets must be 5MB or smaller.")}function AM(b){JM(b);let w=b.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(w),W=$?.[2]??w;zM(W);let Q=W.replace(/\s+/g,"");if(Q.length===0||Q.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(Q))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(Q,"base64"),...$?.[1]?{dataUrlContentType:NW($[1])}:{}}}function mJ(b){if(b<=0)throw Error("The image file is empty.");if(b>TW)throw Error("Image assets must be 5MB or smaller.")}function OM(b){let w=YM(b.filename)??NW(b.explicitContentType)??NW(b.dataUrlContentType);if(!w||!XM.has(w))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return w}function qM(b){let w,$,W;if(b.filePath!==void 0){if(!z0())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. For a remote MCP connection, pass `imageBase64` and `filename` instead.");let G=WM(b.filePath).size;mJ(G),w=$M(b.filePath),$=b.filename??QM(b.filePath)}else{if(!b.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!b.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let G=AM(b.imageBase64);w=G.bytes,W=G.dataUrlContentType,$=b.filename,mJ(w.byteLength)}let Q=OM({filename:$,explicitContentType:b.contentType,dataUrlContentType:W});return{bytes:w,filename:$,contentType:Q,altText:b.altText??HM($)}}async function pJ(b){let w=qM(b),$=w.bytes.byteLength,W=await A("POST","/api/v1/media/upload-url",{filename:w.filename,contentType:w.contentType,fileSizeBytes:$},b.companyId);return await cW(W.uploadUrl,w.bytes,w.contentType,b.companyId),(await A("POST","/api/v1/media/complete-upload",{key:W.key,filename:W.fileName,contentType:w.contentType,fileSizeBytes:$,...b.sourceWidth!==void 0&&{width:b.sourceWidth},...b.sourceHeight!==void 0&&{height:b.sourceHeight},altText:w.altText},b.companyId)).asset}var LM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},UM={type:"string",description:"Human-readable status, confirmation, or next-step message."},BM={type:"string",description:"Additional context about the result."};function o(b){return{type:"object",description:b,additionalProperties:!0}}function PM(b){return{type:"array",description:b,items:o("One item in the returned collection.")}}function N(b){return{type:"string",description:b}}function Kb(b){return{type:"number",description:b}}function Sb(b){return{type:"boolean",description:b}}function F(b){return o(`The ${b} record returned by Sequenzy.`)}function l(b){return PM(`List of ${b} records returned by Sequenzy.`)}var FM={appUrls:o("Dashboard URLs for relevant Sequenzy resources."),url:N("Primary dashboard URL for this result."),settingsUrl:N("Company settings URL when available.")},KM={success:LM,message:UM,note:BM,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:o("One returned item.")},value:o("Fallback object wrapper used only when a tool returns a non-object value.")},MM={get_account:{account:F("account"),companies:l("company"),apiKeyPermissions:o("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:N("Company ID selected by the authenticated API key, when available."),selectedCompanyId:N("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:N("Selected company ID."),companyName:N("Selected company name.")},get_app_urls:{dashboard:N("Company dashboard URL."),settings:N("Company settings URL."),campaign:N("Campaign editor URL."),landingPage:N("Landing page editor URL."),sequence:N("Sequence editor URL."),email:N("Email editor URL."),transactionalEmail:N("Transactional email URL."),emailSend:N("Sent email detail URL."),domain:N("Sending domain settings URL."),urls:o("All generated URLs keyed by resource type.")},create_company:{company:F("company"),autoSelected:Sb("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:F("company")},get_company:{company:F("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:o("One sync rule.")},isDefault:Sb("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:o("One sync rule.")},isDefault:Sb("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:o("Effective browse-abandonment settings (defaults applied)."),priceDrop:o("Effective price-drop settings (defaults applied)."),shopDomain:N("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:o("Effective browse-abandonment settings after the update."),priceDrop:o("Effective price-drop settings after the update."),shopDomain:N("Connected Shopify store domain.")},create_api_key:{apiKey:o("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:N("Newly created API key if the API response uses the short key field.")},list_websites:{websites:l("sender website")},add_website:{website:F("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:F("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:F("sender website"),ready:Sb("Whether the sender website is ready."),status:N("Current processing or verification status.")},verify_sending_domain:{website:F("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:Sb("Whether the sending domain passed the fresh verification check."),message:N("Verification result summary.")},get_integration_guide:{guide:F("integration guide"),code:N("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:o("One setup step.")}},add_subscriber:{subscriber:F("subscriber")},update_subscriber:{subscriber:F("subscriber")},remove_subscriber:{subscriber:F("subscriber"),hardDeleted:Sb("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:F("subscriber")},list_subscriber_notes:{notes:l("subscriber note")},add_subscriber_note:{note:F("subscriber note")},delete_subscriber_note:{id:N("Deleted subscriber note ID."),deleted:Sb("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:l("subscriber"),pagination:o("Pagination metadata."),returned:Kb("Number of subscribers returned."),truncated:Sb("Whether the result was truncated by the requested limit.")},list_products:{products:l("product")},upsert_products:{products:l("product"),created:Kb("Number of products created."),updated:Kb("Number of products updated.")},delete_product:{productId:N("Deleted product ID.")},attach_product_file:{product:F("product"),delivery:F("digital delivery file")},remove_product_file:{product:F("product")},upload_image_asset:{asset:F("hosted image asset"),imageBlock:o("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:F("product sync job"),jobId:N("Queued product sync job ID.")},list_tags:{tags:l("tag")},create_tag:{tag:F("tag")},update_tag:{tag:F("tag")},delete_tag:{tagId:N("Deleted tag ID.")},list_lists:{lists:l("list")},create_list:{list:F("list")},update_list:{list:F("list")},delete_list:{listId:N("Deleted list ID.")},add_subscribers_to_list:{list:F("list"),added:Kb("Number of subscribers added to the list."),skipped:Kb("Number of subscribers skipped.")},remove_subscribers_from_list:{list:F("list"),removed:Kb("Number of subscribers removed from the list."),skipped:Kb("Number of subscribers skipped.")},list_segments:{segments:l("segment")},create_segment:{segment:F("segment")},update_segment:{segment:F("segment")},delete_segment:{segmentId:N("Deleted segment ID.")},get_segment_count:{count:Kb("Number of subscribers matching the segment."),segmentId:N("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:l("audience sync")},list_ad_accounts:{adAccounts:l("ad account")},create_audience_sync:{audienceSync:F("audience sync")},update_audience_sync:{audienceSync:F("audience sync")},delete_audience_sync:{audienceSyncId:N("Deleted audience sync ID.")},sync_audience_now:{audienceSync:F("audience sync"),job:F("audience sync job"),jobId:N("Queued audience sync job ID.")},list_templates:{templates:l("email template")},get_template:{template:F("email template")},create_template:{template:F("email template")},update_template:{template:F("email template")},set_template_localization:{templateId:N("Localized template ID."),localization:F("template localization")},sync_template_localizations:{templateId:N("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:N("One queued locale code.")},queuedVariantCount:Kb("Number of localized variants queued for translation.")},delete_template:{templateId:N("Deleted template ID.")},list_ab_tests:{abTests:l("A/B test")},get_ab_test:{abTest:F("A/B test")},get_ab_test_stats:{abTest:F("A/B test"),stats:F("A/B test statistics")},restart_ab_test:{abTest:F("A/B test")},update_ab_test_variant:{abTest:F("A/B test"),variant:F("A/B test variant")},create_ab_test:{abTest:F("A/B test")},add_ab_test_variant:{abTest:F("A/B test"),variant:F("A/B test variant")},delete_ab_test_variant:{abTest:F("A/B test"),variantId:N("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:N("Deleted A/B test ID.")},list_campaigns:{campaigns:l("campaign")},get_campaign:{campaign:F("campaign")},get_email_send:{emailSend:F("email send"),events:l("email delivery event")},get_recipient_suppression:{suppression:F("recipient suppression status")},remove_recipient_suppression:{removed:Sb("Whether stale bounce suppression was removed."),removedLocalBounce:Sb("Whether the platform-local bounce block was removed."),removedSesRegions:{type:"array",description:"AWS SES regions where a bounce suppression was removed.",items:N("One AWS SES region.")},remainingSuppression:F("recipient suppression status after cleanup")},create_campaign:{campaign:F("campaign")},update_campaign:{campaign:F("campaign")},schedule_campaign:{campaign:F("campaign"),scheduledAt:N("Scheduled send timestamp.")},send_test_email:{emailSendId:N("Durable test email delivery ID."),recipientEmail:N("Test email recipient.")},send_test_sms:{smsSendId:N("Created test SMS send ID."),toPhone:N("Normalized E.164 destination phone.")},cancel_campaign:{campaign:F("campaign")},pause_campaign:{campaign:F("campaign")},resume_campaign:{campaign:F("campaign")},delete_campaign:{campaignId:N("Deleted campaign ID.")},duplicate_campaign:{campaign:F("duplicated campaign")},resend_campaign_to_non_openers:{campaign:F("non-opener resend draft campaign"),estimatedNonOpenerCount:Kb("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:l("saved form")},create_form:{form:F("saved form"),embed:o("Public action URL plus JavaScript, native form, and fetch snippets.")},get_form_embed:{form:F("saved form"),embed:o("Public action URL plus JavaScript, native form, and fetch snippets.")},list_landing_pages:{landingPages:l("landing page")},get_landing_page:{landingPage:F("landing page")},create_landing_page:{landingPage:F("landing page")},update_landing_page:{landingPage:F("landing page")},delete_landing_page:{landingPageId:N("Deleted landing page ID.")},publish_landing_page:{landingPage:F("landing page")},unpublish_landing_page:{landingPage:F("landing page")},connect_landing_page_domain:{landingPage:F("landing page"),domain:N("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:F("landing page"),domain:N("Landing page domain.")},list_sequences:{sequences:l("sequence")},get_sequence:{sequence:F("sequence")},create_sequence:{sequence:F("sequence"),eventTrackingCode:N("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:o("Custom-event endpoint, payload contract, example payload, documentation URL, and get_integration_guide arguments."),requiredEvents:{type:"array",description:"Event names the application or an integration must send.",items:N("One required event name.")}},update_sequence:{sequence:F("sequence")},update_sequence_node:{sequence:F("sequence")},update_sequence_nodes:{sequence:F("sequence")},edit_sequence_graph:{sequence:F("sequence")},insert_sequence_step:{sequence:F("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:N("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:N("Inserted email template ID.")},insertedEmailCount:Kb("Number of email steps inserted.")},enable_sequence:{sequence:F("sequence")},disable_sequence:{sequence:F("sequence")},pause_sequence_enrollments:{sequenceId:N("Sequence ID."),enrollmentPaused:Sb("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:N("Sequence ID."),enrollmentPaused:Sb("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:F("sequence"),enrollments:l("sequence enrollment"),enrolled:Kb("Number of subscribers enrolled."),skipped:Kb("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:F("sequence"),cancelled:Kb("Number of enrollments cancelled."),skipped:Kb("Number of enrollments skipped.")},delete_sequence:{sequenceId:N("Deleted sequence ID.")},list_transactional_emails:{transactional:l("transactional email")},get_transactional_email:{transactional:F("transactional email")},create_transactional_email:{transactional:F("transactional email")},update_transactional_email:{transactional:F("transactional email")},send_email:{emailSendId:N("Durable transactional delivery ID."),transactional:F("transactional email")},get_stats:{stats:F("account or company statistics")},get_campaign_stats:{campaign:F("campaign"),stats:F("campaign statistics"),clickedLinks:{type:"array",description:"Per-link click breakdown, most clicked first (top 20). Each entry has url, clicks, and percentage (that link's share of every recorded link click). Present only when the campaign has tracked link clicks.",items:o("One clicked link with url/clicks/share.")},polls:{type:"array",description:`Poll and NPS summaries. Each subscriber counts once per campaign poll block using their latest answer to that block; NPS entries include score, average, and promoter/passive/detractor counts. To list the exact historical respondents behind a count, use the summary blockId and the get_campaign_stats campaignId with create_segment. ${Tw} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response and may be overwritten by a later poll that reuses the key.`,items:o("One poll or NPS results summary.")}},get_sequence_stats:{sequence:F("sequence"),stats:F("sequence statistics")},list_campaign_events:{events:l("campaign email event"),pagination:o("Pagination metadata.")},list_sequence_events:{events:l("sequence email event"),pagination:o("Pagination metadata.")},get_subscriber_activity:{activity:l("subscriber activity event"),subscribers:l("subscriber"),pagination:o("Pagination metadata.")},list_team_members:{members:l("team member"),invitations:l("team invitation")},invite_team_member:{invitation:F("team invitation")},cancel_team_invitation:{invitationId:N("Cancelled invitation ID.")},list_conversations:{conversations:l("inbox conversation"),pagination:o("Pagination metadata.")},get_conversation:{conversation:F("inbox conversation"),messages:l("conversation message")},reply_to_conversation:{conversation:F("inbox conversation"),message:F("conversation message")},update_conversation_status:{conversation:F("inbox conversation")},mark_conversation_read:{conversation:F("inbox conversation")},list_webhooks:{webhooks:l("outbound webhook")},create_webhook:{webhook:F("outbound webhook")},update_webhook:{webhook:F("outbound webhook")},delete_webhook:{webhookId:N("Deleted outbound webhook ID.")},test_webhook:{webhook:F("outbound webhook"),delivery:F("test webhook delivery")},list_webhook_deliveries:{deliveries:l("webhook delivery")},replay_webhook_delivery:{delivery:F("webhook delivery"),job:F("webhook replay job")},generate_email:{email:F("generated email"),html:N("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:o("One generated email block.")},subject:N("Generated subject line."),previewText:N("Generated inbox preview text.")},generate_sequence:{sequence:F("persisted AI-generated sequence draft"),deprecated:Sb("Always true for this deprecated alias."),deprecationMessage:N("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:N("One generated subject line.")},variants:l("generated subject line variant")},generate_sms:{prompt:N("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:o("One generated SMS message.")}},get_sms_settings:{sms:o("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function IM(b){let w=MM[b];if(w===void 0)throw Error(`MCP tool "${b}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${b}\` MCP tool.`,properties:{...KM,...w,...VW.has(b)?FM:{}},additionalProperties:!0}}function oJ(b){return{...b,outputSchema:IM(b.name)}}function dJ(b){if(y(b))return b;if(Array.isArray(b))return{items:b};return{value:b}}var tJ=[{name:"list_ab_tests",description:"List A/B tests and their variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Optional sequence ID to filter automation A/B tests."}}}},{name:"get_ab_test",description:"Get A/B test details, variants, and per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"}},required:["abTestId"]}},{name:"get_ab_test_stats",description:"Get A/B test aggregate stats and per-variant stats. Supports period or custom start/end ranges.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},period:{type:"string",description:"Optional period: 1h, 24h, 7d, 30d, or 90d."},start:{type:"string",description:"Custom range start as ISO 8601. Requires end."},end:{type:"string",description:"Custom range end as ISO 8601. Requires start."},includeMachineEngagement:lb},required:["abTestId"]}},{name:"restart_ab_test",description:"Run another sequence A/B test after a winner is selected. By default the winner becomes the new control; pass sourceVariantId to use another variant as the control email.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to restart"},sourceVariantId:{type:"string",description:"Optional variant ID to use as the new control email. Defaults to the selected winner."},testType:{type:"string",description:"Optional test type: subject or content."},winnerThreshold:{type:"number",description:"Optional number of subscribers before selecting a winner. Must be from 10 to 1000."},variantCount:{type:"number",description:"Optional total variants including the control. Must be from 2 to 4."}},required:["abTestId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update a draft A/B test variant. Provide at least one of subject, previewText, html, or blocks. Use either html or blocks, not both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID"},subject:{type:"string",description:"Variant subject line"},previewText:{type:"string",description:"Variant preview text. Pass an empty string to clear it."},html:{type:"string",description:"Replacement HTML body. Mutually exclusive with blocks."},blocks:{type:"array",description:`${Jw} Mutually exclusive with html.`,items:{type:"object"}}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test. Control variant A is created automatically from the campaign's current email; optionally provide extra variants. The campaign must be in draft or rejected status, and each campaign can only have one A/B test.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Draft campaign ID to create the A/B test for."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Percentage of the audience used for the test phase, from 5 to 50. Defaults to 20."},testDurationMinutes:{type:"number",description:"Test phase duration in minutes before the winner is selected, from 15 to 1440. Defaults to 240."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Defaults to open_rate."},variants:{type:"array",description:"Optional extra variants to create in addition to control variant A.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Jw,items:{type:"object"}}},required:["subject"]}}},required:["campaignId"]}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign A/B test. Variants cannot be added after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Jw,items:{type:"object"}}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign A/B test. This cannot be undone. Variant A is the control and cannot be deleted, and the test must keep at least the minimum number of variants. Variants cannot be removed after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID to delete."}},required:["abTestId","variantId"]}},{name:"delete_ab_test",description:"Permanently delete a campaign A/B test and all of its variants. This cannot be undone. Running tests (testing or winner_selected) cannot be deleted, and the linked campaign must be in draft or rejected status.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to delete."}},required:["abTestId"]}}];var rJ=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. IMPORTANT: If you have access to multiple companies, you MUST either:
29
29
  1. Call select_company first to choose which company to work with, OR
30
30
  2. Pass companyId explicitly in each tool call
31
31
 
@@ -47,5 +47,5 @@ Use cases:
47
47
  - 'event_tracking': Tracking CUSTOM events only (not payment events - those come from the integration)
48
48
  - 'ecommerce': Connecting a custom e-commerce platform via the Commerce API (sync products, push orders/checkouts, power abandoned cart + back-in-stock automations)
49
49
 
50
- Before implementing, use create_api_key to generate an API key and save it to .env as SEQUENZY_API_KEY.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration), 'ecommerce' (connecting a custom e-commerce platform via the Commerce API)"}}}}];var eD=[{name:"generate_email",description:"Generate email blocks from a prompt. Generated blocks include the company's branding chrome (logo, footer with company name/address/unsubscribe) by default, matching emails created in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"},applyBranding:{type:"boolean",description:"Wrap the generated content with company branding (logo + footer). Defaults to true; set false to get raw content blocks only."},emailType:{type:"string",enum:["marketing","transactional"],description:"Email type. Transactional emails get a footer without the unsubscribe link. Defaults to marketing."}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED compatibility alias - use create_sequence] Create and persist a disabled AI-generated email sequence draft from a goal. The saved draft appears in list_sequences. The name defaults to the goal and the trigger defaults to contact_added; optionally pass listId to scope it. Review before enabling.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},name:{type:"string",description:"Optional sequence name. Defaults to the goal."},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"},listId:{type:"string",description:"Optional list ID. When provided, only contacts added to this list trigger the sequence."}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}},{name:"generate_sms",description:"Generate SMS marketing message variants from a prompt. Returns plain-text messages with per-message encoding and segment counts. Use the results as the 'text' of an SMS sequence step (insert_sequence_step with type 'sms' or a create_sequence sms step). Messages exclude opt-out footers and brand prefixes - the platform adds those automatically at send time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the SMS to generate (e.g., 'cart reminder with a free-shipping hook')"},count:{type:"number",description:"Number of message variants to generate (default: 3, max: 10)"}},required:["prompt"]}},{name:"get_sms_settings",description:"Get the company's SMS add-on status: whether SMS is enabled, plan eligibility, credit balance, brand prefix, phone numbers, and whether SMS steps will actually send. Check this before adding SMS steps to sequences so you can warn the user when SMS is not ready.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"send_test_sms",description:"Send a test SMS to a phone number. IMPORTANT: sends a real text message and charges SMS credits - only call when the user explicitly asks for a test send. Requires the SMS add-on with a verified number (check get_sms_settings). Limited to 5 test sends per hour; bypasses quiet hours; excluded from step stats.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Destination phone number in international E.164 format, e.g. +15550100123."},text:{type:"string",description:"Plain-text message body. Merge tags are not resolved for test sends to arbitrary numbers. Provide text or blocks."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable image URLs sent as MMS media (US/CA only)."},blocks:{type:"array",items:{type:"object"},description:"SMS content blocks (text + image subset). Provide text or blocks, not both."}},required:["to"]}}];var sD=[{name:"get_stats",description:"Get overview statistics for a time period",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"},includeMachineEngagement:lb}}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including attributed conversions, revenue (revenueCents), a per-link click breakdown in the top-level clickedLinks array, and any Poll or NPS survey summaries in the top-level polls array",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},includeMachineEngagement:lb},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence, including attributed conversions and revenue (revenueCents) plus per-step failed subscribers and failure reasons",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},includeMachineEngagement:lb},required:["sequenceId"]}},{name:"list_campaign_events",description:"List paginated raw email events for a campaign. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:lb},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:lb},required:["sequenceId"]}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:lb},required:[]}}];var aD=[{name:"list_audience_syncs",description:"List Meta custom audience syncs (segment -> ad audience mappings) with their schedule and last sync status. Requires the Meta Ads integration to be connected in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_ad_accounts",description:"List the Meta ad accounts available through the connected Meta Ads integration. Use the returned account id as `adAccountId` when creating an audience sync.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_audience_sync",description:'Push a segment to a Meta custom audience and keep it synced on a schedule. Provide `segmentId` for an existing segment OR `predefinedSegmentId` for a ready-made template (for example "zero-ltv", "no-purchase-1y", "recent-buyers", "high-spenders-ecom", "non-buyers", "engaged") - the template segment is created automatically on first use. The first upload runs immediately. Note: audiences are add-only; subscribers who later leave the segment stay in the Meta audience.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Existing segment ID to sync. Mutually exclusive with `predefinedSegmentId`."},predefinedSegmentId:{type:"string",description:'Predefined segment template ID (for example "zero-ltv", "no-purchase-1y", "recent-buyers"). The segment is created automatically if it does not exist. Mutually exclusive with `segmentId`.'},adAccountId:{type:"string",description:"Meta ad account ID (act_...) from `list_ad_accounts`."},audienceName:{type:"string",description:"Name for the custom audience in Meta Ads Manager."},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"How often to re-upload the segment. Default: daily."}},required:["adAccountId","audienceName"]}},{name:"update_audience_sync",description:"Update an audience sync's frequency or pause/resume it (`isActive`).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID"},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"New sync frequency."},isActive:{type:"boolean",description:"Set false to pause the sync, true to resume it."}},required:["syncId"]}},{name:"delete_audience_sync",description:"Remove an audience sync mapping. The Meta audience itself is kept (running ads are not disrupted) - only future syncs stop.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to remove."}},required:["syncId"]}},{name:"sync_audience_now",description:"Trigger an immediate upload of the segment's subscribers to its Meta custom audience, outside the regular schedule.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to run."}},required:["syncId"]}}];var bz=[{name:"list_campaigns",description:"List all campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent)"},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."}}}},{name:"get_campaign",description:"Get campaign details and stats",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_email_send",description:"Get a sent email by emailSendId, including the stored HTML body when available and the ClickHouse event timeline. If the short-lived email send row has been cleaned up, returns the retained ClickHouse events and a sparse summary.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Email send ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider campaigns; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Jw,items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Generated blocks include the company's logo and footer, and the created campaign inherits the company brand font. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Target segment ID"},fromEmail:{type:"string",description:"From address for this campaign. Its domain must be configured and verified; a sender profile is created when needed."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for this campaign. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},campaignData:{type:"object",description:"Optional campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Optional computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested. Send an empty string to clear it."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider campaigns; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Jw,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Send a test email to a single address",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"resend_campaign_to_non_openers",description:"Create a draft that resends a sent campaign to everyone in the same audience who didn't open it. Copies the campaign email and reuses the original audience with a 'didn't open this campaign' rule added. Only available 6 hours after the campaign finishes sending. The draft must be scheduled or sent separately. Returns the new draft and an estimate of how many subscribers haven't opened the original.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"ID of the sent campaign to resend to non-openers."}},required:["campaignId"]}}];var wz=[{name:"submit_feedback",description:"Send product feedback about Sequenzy itself to the Sequenzy team. IMPORTANT: call this tool whenever the user wanted to accomplish something and Sequenzy did not expose functionality for it - a missing tool or argument, an unsupported workflow, a confusing behavior, or a bug. Briefly tell the user you reported the gap. This feedback goes straight to the team and shapes what gets built next. Do not use it for questions about the user's own account or data, and never include secrets or API keys. Submitting feedback never changes account data.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},message:{type:"string",description:"The feedback itself. Be specific: what was needed, what was missing or wrong, and what you did instead (workaround, gave up, used the dashboard)."},category:{type:"string",enum:["missing_capability","bug","docs","ux","praise","other"],description:"Feedback category. Use missing_capability when the user wanted something these tools do not support (default: other)."},context:{type:"string",description:"Optional: what the user was trying to accomplish, in their words, plus any relevant tool names or arguments you tried."}},required:["message"]}}];var $z=[{name:"upload_image_asset",description:"Upload an image to the selected company's shared media library and return a hosted URL plus a ready-to-insert Sequenzy image block. Call this before create/update campaign, sequence, template, or transactional tools, then place the returned imageBlock in the target blocks array. Provide either filePath (local stdio MCP only) or imageBase64 (works with remote MCP when the client can supply attachment bytes), not both. PNG, JPEG, GIF, and WebP are supported up to 5MB. cropHeight with objectFit:'cover' provides a precise centered screenshot crop while displayWidthPercent keeps the image responsive.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},filePath:{type:"string",description:"Local path to a PNG, JPEG, GIF, or WebP image. Available only when the MCP server runs locally. Provide filePath or imageBase64, not both."},imageBase64:{type:"string",description:"Raw base64 image bytes or a base64 data URL. Use this for remote MCP clients that can access attachment bytes. Provide imageBase64 or filePath, not both."},filename:{type:"string",description:"File name including extension. Required with imageBase64; optional override with filePath."},contentType:{type:"string",description:"Image MIME type when it cannot be inferred from filename, such as image/png."},altText:{type:"string",description:"Accessible description stored with the asset and returned as imageBlock.alt. Use an empty string only for a decorative image."},sourceWidth:{type:"integer",minimum:1,maximum:20000,description:"Optional intrinsic source width in pixels. Provide sourceWidth and sourceHeight together when known."},sourceHeight:{type:"integer",minimum:1,maximum:20000,description:"Optional intrinsic source height in pixels. Provide sourceWidth and sourceHeight together when known."},displayWidthPercent:{type:"number",minimum:1,maximum:100,description:"Responsive image width as a percentage of the email content area. Defaults to 100."},cropHeight:{type:"integer",minimum:1,maximum:2000,description:"Optional fixed display height in pixels. With objectFit:'cover', the image is centered and cropped to this height."},objectFit:{type:"string",enum:["cover","contain"],description:"How the image fits cropHeight. Defaults to cover when cropHeight is provided. Only valid with cropHeight."},align:{type:"string",enum:["left","center","right"],description:"Image alignment. Defaults to center."}},additionalProperties:!1}}];var Wz=[{name:"list_conversations",description:"List inbox conversations (email replies from subscribers). Filter by status, free-text search, or unread state, with pagination.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},status:{type:"string",enum:["open","closed","all"],description:"Filter by conversation status. Defaults to all."},search:{type:"string",description:"Free-text search across conversation subjects and participants."},unread:{type:"boolean",description:"Set true to only return conversations with unread messages."},page:{type:"number",description:"Page number. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."}}}},{name:"get_conversation",description:"Get a conversation with its full message history, subscriber details, and context.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}},{name:"reply_to_conversation",description:"Send a reply in a conversation, or add an internal note. type 'outbound' (default) emails the subscriber and requires bodyText or bodyHtml; type 'note' adds a private team-only note. Replying to a closed conversation reopens it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID to reply in."},type:{type:"string",enum:["outbound","note"],description:"Message type: outbound emails the subscriber, note is internal-only. Defaults to outbound."},subject:{type:"string",description:"Optional subject override. Defaults to the conversation subject."},bodyText:{type:"string",description:"Plain-text message body."},bodyHtml:{type:"string",description:"HTML message body."}},required:["conversationId"]}},{name:"update_conversation_status",description:"Open or close a conversation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."},status:{type:"string",enum:["open","closed"],description:"New conversation status."}},required:["conversationId","status"]}},{name:"mark_conversation_read",description:"Mark all unread inbound messages in a conversation as read.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}}];var Qz=[{name:"list_landing_pages",description:"List all landing pages for a company",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list landing pages for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"get_landing_page",description:"Get landing page details, content, metrics, and URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"create_landing_page",description:"Create a draft landing page. Provide content for an exact page, or a template for generated starter content.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the landing page in. If not provided, uses the currently selected company."},name:{type:"string",description:"Landing page name. Optional; defaults to a template-specific name."},slug:{type:"string",description:"Optional URL slug. It will be normalized and made unique within the company."},template:{type:"string",description:qD},content:{type:"object",description:X0,additionalProperties:!0}},additionalProperties:!1}},{name:"update_landing_page",description:"Edit a landing page's name, slug, or full content. Provide at least one update field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Landing page name."},slug:{type:"string",description:"Landing page URL slug. It will be normalized and made unique within the company."},content:{type:"object",description:X0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"delete_landing_page",description:"Delete a landing page",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"publish_landing_page",description:"Publish a landing page. Optional name, slug, or content updates are saved before publishing.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before publishing."},content:{type:"object",description:X0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"unpublish_landing_page",description:"Unpublish a landing page and return it to draft status. Optional name, slug, or content updates are saved first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before unpublishing."},content:{type:"object",description:X0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"connect_landing_page_domain",description:"Connect a custom domain for published landing pages. Returns the DNS target and verification records.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Custom domain, for example pages.example.com."}},required:["domain"],additionalProperties:!1}},{name:"update_landing_page_domain_settings",description:"Update landing page domain settings. Provide domain to replace the custom domain, verify true to refresh verification, or both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Replacement custom domain."},verify:{type:"boolean",description:"Refresh domain verification after any domain update."}},additionalProperties:!1}}];var Gz=[{name:"list_products",description:"List synced products (Stripe, Shopify, WooCommerce) including any attached digital delivery file. Useful before attaching a file or building a purchase sequence for a specific product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list products for. If not provided, uses the currently selected company."},provider:{type:"string",description:"Filter by provider: stripe, shopify, woocommerce, or manual."},search:{type:"string",description:"Filter products by title."}}}},{name:"upsert_products",description:"Create or update products in the catalog (Commerce API, keyed by your productId, stored under the api provider). Use this to add products that are not synced from Stripe/Shopify/WooCommerce, then attach a deliverable file with attach_product_file and build a purchase sequence for them.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},products:{type:"array",description:"Products to create or update (max 100).",items:{type:"object",properties:{productId:{type:"string",description:"Your stable product identifier (used for upserts and order line items)."},title:{type:"string",description:"Product title."},description:{type:"string",description:"Product description."},imageUrl:{type:"string",description:"Product image URL."},url:{type:"string",description:"Product page URL."},priceCents:{type:"number",description:"Price in the smallest currency unit."},currency:{type:"string",description:"ISO currency code, e.g. USD."},inStock:{type:"boolean",description:"Whether the product is in stock."}},required:["productId","title"]}}},required:["products"]}},{name:"delete_product",description:"Delete a product previously pushed via upsert_products (Commerce API products only), identified by your productId.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Your productId used when upserting the product."}},required:["productId"]}},{name:"attach_product_file",description:"Attach a distributable file to a product, either by public URL or by uploading a local file (filePath, local MCP server only). After a purchase of the product, sequence emails can link to it with {{event.download.url}} and {{event.download.name}}.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."},url:{type:"string",description:"Public http(s) URL of the file to deliver. Provide url or filePath, not both."},filePath:{type:"string",description:"Local path of a file to upload and attach (PDF, ePub, ZIP, image, audio, video, or text, up to 100MB). Only available when the MCP server runs locally on this machine."},fileName:{type:"string",description:"Display name for the file (e.g. guide.pdf). Used as {{event.download.name}}."}},required:["productId"]}},{name:"remove_product_file",description:"Remove the attached distributable file from a product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."}},required:["productId"]}},{name:"sync_products",description:"Queue a sync of the Stripe product catalog into the products list. Requires an active Stripe integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}}];var Xz=[{name:"list_sequences",description:"List all email sequences (automations)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."}}}},{name:"get_sequence",description:"Get sequence details, editable step content, and graph topology. Each sequence.nodes item includes id, nodeType, current config, updatedAt, and updateHints with its editable/managed fields and ready-to-return expectedUpdatedAt token for update_sequence_node/update_sequence_nodes. The response also includes sequence.edges and graphRevision for safe edit_sequence_graph calls, plus sequence.emails with each email step's nodeId, linked emailId, subject, previewText, and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence",description:"Create and persist a disabled draft email sequence, follow-up series, drip campaign, nurture flow, or automation workflow. For natural-language content, provide goal and emailCount. Use explicit steps for finished caller-supplied content, exact workflows, or migrations. Configure trigger plus its relevant field, such as listId, tagName, segmentId, or eventName. Supports email and SMS steps, delays and date waits, actions that dynamically create a provider discount/code, subscriber updates, event filters, enrollment rules, sending windows, and stop conditions. The saved draft appears in list_sequences. Never call enable_sequence unless the user explicitly asks to activate it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inactivity","frequency"],description:"Trigger type: 'contact_added' (when added to a list), 'tag_added' (when tag is applied), 'segment_entered' (when a contact newly enters a saved segment), 'event_received' (when custom event fires), 'inactivity' (when subscriber hasn't performed an event for X days), 'frequency' (when subscriber performs event X times in Y days)"},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inactivity, and frequency triggers)"},propertyFilters:{type:"array",description:"Optional event property filters for event_received triggers. The sequence only starts when the triggering event's properties match ALL filters. Use a dot-path into the event properties; use [] to match inside arrays. Examples: scope a purchase sequence to one product with { path: 'lineItems[].providerProductId', operator: 'equals', value: 'prod_123' } (ecommerce.order_placed) or { path: 'productIds', operator: 'equals', value: 'prod_123' } (saas.purchase); to match any of several products use { path: 'lineItems[].providerProductId', operator: 'one_of', value: ['prod_123', 'prod_456'] }. Max 10 filters.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:v$,stopCondition:{type:"object",description:"Optional explicit auto-stop condition. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'does_not_have_tag', value: 'trial' } when a tag is removed, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } when they leave a list, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. Use null or omit for type 'none'."}},required:["type"]},steps:{type:"array",description:"Explicit sequence steps. Omit type for email steps, use type: 'sms' for SMS, type: 'create_discount' for a dynamic discount, or type: 'update_subscriber' with nodeType: 'action_update_attributes' and config to copy trigger-event values such as {{event.plan}} into subscriber data.",items:{type:"object",properties:{type:{type:"string",enum:["email","sms","create_discount","discount","update_subscriber"],description:"Step type. Omit or use 'email' for email content. Use 'sms' to send a text message, 'create_discount' to generate a code, or 'update_subscriber' to copy trigger data into the subscriber."},nodeType:{type:"string",enum:["action_email","action_sms","action_create_discount","action_update_attributes"],description:"Internal step type. Use action_update_attributes with config for Update Subscriber steps."},config:Y0,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:W1,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:G1,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:Q1,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.",properties:{label:{type:"string",description:"Builder label for the discount step."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use 'stripe' to dynamically create a Stripe coupon plus promotion code, or 'shopify' to dynamically create a Shopify Admin discount code. Defaults to 'stripe' when omitted."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional display name for each dynamically generated provider discount."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe","shopify"],description:"Legacy top-level discount provider. Prefer discount.provider. Supports 'stripe' and 'shopify'."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name","trigger"]}}];var Yz=[{name:"update_sequence",description:"Update an existing sequence. To target a specific existing step, use IDs returned by get_sequence. The emails/steps arrays edit email steps, smsSteps edits SMS steps, and subscriberUpdateSteps replaces the config of action_update_attributes steps. To insert new linear steps, use insertSteps with an afterNodeId from get_sequence; omit afterNodeId only to append to an unambiguous linear tail. For active sequences, structural changes such as insertSteps or branch require confirmStructuralChange:true after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},fromEmail:{type:"string",description:"Set the From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Set an existing reply profile. Mutually exclusive with replyTo."},enrollmentPaused:{type:"boolean",description:"Set true to stop new enrollments for an active sequence while current recipients continue. Set false to resume new enrollments. The sequence must already be active."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence. Required for insertSteps or branch when the sequence is active; not needed for content-only email edits."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. 'matching_field' is only valid for event-based sequence triggers."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},sendingWindow:v$,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses that receive a blind copy of every email this sequence sends, such as a customer support inbox (max 10). Omit to leave unchanged. Use clearBccEmails to remove them."},clearBccEmails:{type:"boolean",description:"Set true to remove the sequence BCC addresses. Do not provide this together with bccEmails."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'entered_segment', value: 'segment_123' } to stop when they enter a segment, { type: 'field_changed', value: 'plan' } to stop when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } to stop when they leave a list, or { type: 'none', value: null } to clear it.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"]},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition."}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. The branch is inserted after afterNodeId and creates an if path plus an else fallback path. Use get_sequence first to choose afterNodeId. Each branch condition should include steps, and elseSteps is required unless allowEmptyPaths is true. Conditions support tag presence/absence, lists, saved segments, events, clicked links, and field comparisons. Use activityScope for event_received and link_clicked checks.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert the branch after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails."},label:{type:"string",description:"Optional branch node label."},branches:{type:"array",description:"Conditional branches evaluated in order. An else fallback is created automatically.",items:{type:"object",properties:{id:{type:"string",description:"Optional stable branch ID. Defaults to branch-0, branch-1, etc."},label:{type:"string",description:"Display label, e.g. 'If has customer tag'."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"Condition type for this branch. has_phone (contact has a phone number) and sms_subscribed (contact opted in to SMS marketing) need no extra fields."},tagName:{type:"string",description:"Tag name for has_tag and does_not_have_tag conditions. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag and does_not_have_tag conditions."},listId:{type:"string",description:"List ID for in_list conditions."},segmentId:{type:"string",description:"Segment ID for in_segment conditions."},segmentName:{type:"string",description:"Optional display name for in_segment conditions."},eventName:{type:"string",description:"Event name for event_received conditions, such as project.invite.accepted."},linkUrl:{type:"string",description:"Optional URL substring for link_clicked conditions. Omit to match any clicked link."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"Scope for event_received and link_clicked conditions. Omit to check ever."},fieldName:{type:"string",description:"Subscriber attribute name for field conditions."},fieldValue:{type:"string",description:"Comparison value for field conditions."},steps:{type:"array",description:"Steps to create inside this branch path. Required by default so the branch is not an empty placeholder.",items:g$}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:g$},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating empty UI placeholders. Normal API/MCP use should omit this and provide branch steps plus elseSteps."}},required:["afterNodeId","branches"]},insertSteps:{type:"object",description:"Insert one or more new linear steps into an existing sequence. Use get_sequence first, then pass afterNodeId to insert after a specific node. If afterNodeId is omitted, the steps are appended only when the sequence has exactly one linear tail. Inserted email steps require subject plus blocks or html.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},steps:{type:"array",description:"New steps to insert. Supports emails, delays, create_discount actions, webhooks, and other supported sequence path node types.",items:g$}},required:["steps"]},emails:{type:"array",description:"Updated existing sequence emails. If you omit emailId/nodeId, items are matched by existing step order. This field does not create new steps; use insertSteps for insertion and include delay on inserted email steps when a timer is needed.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating imported provider HTML for a step."},blocks:{type:"array",description:Dw,items:{type:"object"}},...KW}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules, and only edits existing email steps. Use insertSteps to create new steps.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating HTML content for a step."},blocks:{type:"array",description:Dw,items:{type:"object"}},...KW}}},smsSteps:{type:"array",description:"Content updates for existing SMS steps, targeted by nodeId (an action_sms node from get_sequence.sequence.nodes). Content-only edits - use insertSteps to create new SMS steps.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_sms node ID. Required."},text:{type:"string",description:"Replacement plain-text message body. Merge tags like {{FIRST_NAME}} work. Provide text or blocks, not both."},blocks:{type:"array",items:{type:"object"},description:"Replacement SMS content blocks (text + image subset)."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable MMS image URLs. Only valid together with text."},label:{type:"string",description:"Updated display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"Updated behavior when the contact can't receive SMS."}},required:["nodeId"]}},subscriberUpdateSteps:{type:"array",description:"Full config replacements for existing Update Subscriber steps, targeted by action_update_attributes nodeId.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_update_attributes node ID."},config:Y0},required:["nodeId","config"]}}},required:["sequenceId"]}},{name:"update_sequence_node",description:"Patch one existing sequence node in place. Call get_sequence first, select sequence.nodes[].id, inspect nodeType/config, and pass that node's updatedAt as expectedUpdatedAt. This supports every stored sequence node type, including delays, email/SMS content, actions, conditions, branches without topology changes, webhooks, and trigger settings. Delay example: changes:{ delay:{ days:7 } }. The update is type-aware and preserves fields you omit. It cannot change nodeType, managed linked-resource IDs, or graph topology; use edit_sequence_graph for structural work. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamp; the new delay applies when recipients reach the node in the future.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},nodeId:C$.properties.nodeId,changes:zW,expectedUpdatedAt:C$.properties.expectedUpdatedAt,confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing a node in an active sequence."}},required:["sequenceId","nodeId","changes","expectedUpdatedAt"],additionalProperties:!1}},{name:"update_sequence_nodes",description:"Atomically patch multiple existing sequence nodes. Call get_sequence first and include each node's id plus its updatedAt as expectedUpdatedAt. Every patch follows update_sequence_node's type-aware rules. Either every node update commits or none do, making this the preferred tool for changes such as replacing all 5-minute delays with 7-day delays. A node may appear only once. It cannot change node types or graph topology. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamps.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},updates:{type:"array",description:"Non-empty node patches. Each nodeId may appear only once.",items:C$},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing nodes in an active sequence."}},required:["sequenceId","updates"],additionalProperties:!1}},{name:"edit_sequence_graph",description:"Restructure an existing sequence graph using node IDs, edges, and graphRevision from get_sequence. move_node repositions one non-split step; beforeNodeId can place an A/B test or other step at the shared continuation below a branch. duplicate_node creates an independent copy and deep-copies linked email or A/B test content. delete_node safely splices a linear step; deleting a split node requires the complete replacement edges. replace_edges atomically replaces the complete topology for advanced reconnect or multi-node reorder work. Always call get_sequence immediately before this tool and pass its graphRevision. Active sequences require confirmStructuralChange:true after the user confirms live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},action:{type:"string",enum:["move_node","delete_node","duplicate_node","replace_edges"],description:"Graph operation. Use move_node for a single step reorder, duplicate_node for an independent copy, delete_node to remove a step/node, or replace_edges for an atomic reconnect/reorder of the whole topology."},graphRevision:{type:"string",description:"Exact graphRevision returned by the latest get_sequence call. The edit is rejected if the graph changed since then."},nodeId:{type:"string",description:"Existing node to move, duplicate, or delete. Required for those actions and unused by replace_edges."},afterNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately after this node. The target must have at most one outgoing path. Provide exactly one of afterNodeId or beforeNodeId."},beforeNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately before this node. All incoming paths converge through the moved/copied node, which is useful for placing a step below a branch. Provide exactly one of beforeNodeId or afterNodeId."},edges:{type:"array",description:"Complete replacement topology from get_sequence.sequence.edges. The returned edge array is already normalized for this input and can be reused directly. Required for replace_edges and when deleting a split node. Preserve each branch edge's condition.branchId. Do not include edges that reference a deleted node.",items:{type:"object",properties:{sourceNodeId:{type:"string"},targetNodeId:{type:"string"},condition:{type:"object",description:"Optional edge routing condition. Preserve condition.branchId on edges leaving logic_branch nodes."}},required:["sourceNodeId","targetNodeId"],additionalProperties:!1}},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."}},required:["sequenceId","action","graphRevision"],additionalProperties:!1}},{name:"insert_sequence_step",description:"Insert one new email or SMS step into an existing sequence. Prefer this over update_sequence.steps/emails when adding a step: it creates the step node (plus an email template for email steps) and, when delay or delayMs is provided, a logic_delay node immediately before it. For SMS steps set type:'sms' and provide 'text' (generate copy with generate_sms; check get_sms_settings first and warn the user if SMS is not enabled). Use get_sequence first, then pass afterNodeId from sequence.nodes or sequence.emails to choose the insertion point. If afterNodeId is omitted, the step is appended only when the sequence has exactly one linear tail. For active sequences, set confirmStructuralChange:true only after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},type:{type:"string",enum:["email","sms"],description:"Step type. Defaults to 'email'. Use 'sms' to insert an SMS step (requires 'text')."},afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."},name:{type:"string",description:"Optional email template and step name."},subject:{type:"string",description:"Email subject for the new step. Required for email steps; not used for SMS steps."},previewText:{type:"string",description:"Optional email preview text for the new step."},blocks:{type:"array",description:W1,items:{type:"object"}},html:{type:"string",description:"HTML content for the new step. Stored as one raw HTML block. Use this for imported provider HTML. Provide either html or blocks, not both."},senderProfileId:{type:"string",description:"Email steps only: sender profile for the new step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"Email steps only: From address for the new step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Email steps only: display name override for the new step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Email steps only: reply profile for the new step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Email steps only: Reply-To address for the new step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Email steps only: display name for a newly created reply profile. Requires replyTo."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},label:{type:"string",description:"SMS steps only: display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:G1,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:Q1},required:["sequenceId"],additionalProperties:!1}},{name:"enable_sequence",description:"Enable/activate a sequence. IMPORTANT: Only call this when the user EXPLICITLY asks to enable or activate a sequence. Never enable sequences automatically after creation - the user must review the content first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"disable_sequence",description:"Disable/freeze a sequence. This blocks new enrollments and holds current recipients until the sequence is enabled again. To only stop new enrollments while current recipients continue, use pause_sequence_enrollments.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"pause_sequence_enrollments",description:"Stop new enrollments for an active sequence while current recipients continue through the sequence. This matches the dashboard 'Stop new enrollments' control and does not freeze current recipients.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"resume_sequence_enrollments",description:"Resume new enrollments for an active sequence whose enrollment gate was paused. Use enable_sequence instead for a fully disabled/frozen sequence.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"enroll_subscribers_in_sequence",description:"Manually enroll subscribers in a sequence by email address or subscriber ID. Maximum 500 total targets per call across emails and subscriberIds. Only active subscribers are enrolled: unknown emails are returned in `notFound`, while inactive, unavailable, and already actively enrolled subscribers are counted in `skipped`. By default enrollment starts at the first step after the trigger; pass targetNodeId to start at a specific step.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to enroll subscribers in."},emails:{type:"array",items:{type:"string"},description:"Email addresses of subscribers to enroll. Combined with subscriberIds, maximum 500 total targets per call."},subscriberIds:{type:"array",items:{type:"string"},description:"Subscriber IDs to enroll. Combined with emails, maximum 500 total targets per call."},targetNodeId:{type:"string",description:"Optional node ID to start enrollment at. Use a non-trigger nodeId from get_sequence. Defaults to the first step after the trigger."}},required:["sequenceId"]}},{name:"cancel_sequence_enrollments",description:"Cancel active/waiting enrollments in one sequence. Provide sequenceId and exactly one target: subscriberId for one subscriber, or fieldValues to match stored entry event properties. For fieldValues, fieldPath is optional when the sequence has enrollmentFieldPath configured; otherwise provide a dot path such as order.id.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be cancelled."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide subscriberId or fieldValues, not both."},fieldPath:{type:"string",description:"Dot-path inside the token's stored entry event properties, such as order.id or event.id. Optional when the sequence has enrollmentFieldPath configured."},fieldValues:{type:"array",items:{type:"string"},description:"Entry field values to match. Cancels all active/waiting enrollments in the sequence whose entry field value is in this list. Provide fieldValues or subscriberId, not both."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. Field-value cancellation defaults to dryRun on the API unless explicitly false."},reason:{type:"string",description:"Optional cancellation reason stored on matched enrollment tokens."}},required:["sequenceId"],additionalProperties:!1}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}}];var Hz=[{name:"add_subscriber",description:"Add a new subscriber to your list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},attributes:{type:"object",description:"Custom attributes (name, plan, etc.)"},tags:{type:"array",items:{type:"string"},description:"Tags to apply to the subscriber"},listIds:{type:"array",items:{type:"string"},description:"List IDs to add subscriber to"},status:{type:"string",description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active."},optInMode:{type:"string",description:"Consent mode: confirmed creates active immediately when consent is verified, double_opt_in sends a confirmation email before activation, and default obeys company double opt-in settings."}},required:[]}},{name:"update_subscriber",description:"Update an existing subscriber's attributes or tags",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},attributes:{type:"object",description:"Attributes to update"},addTags:{type:"array",items:{type:"string"},description:"Tags to add"},removeTags:{type:"array",items:{type:"string"},description:"Tags to remove"}},required:[]}},{name:"remove_subscriber",description:"Unsubscribe or delete a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},hardDelete:{type:"boolean",description:"If true, permanently deletes. If false, just unsubscribes."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, notes, list memberships, sequence enrollments, email stats, and recent activity",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:lb},required:[]}},{name:"list_subscriber_notes",description:"List internal notes for a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"add_subscriber_note",description:"Add an internal note to a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},body:{type:"string",description:"Internal note body, up to 5000 characters."}},required:["body"]}},{name:"delete_subscriber_note",description:"Delete one internal subscriber note by note ID.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},noteId:{type:"string",description:"Subscriber note ID to delete."}},required:["noteId"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, or segment. If you omit limit, the tool fetches all pages and returns every match.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query (email or name)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},list:{type:"string",description:"Filter by subscriber list ID or exact list name. Prefer listId when known."},listId:{type:"string",description:"Filter by subscriber list ID."},listName:{type:"string",description:"Filter by exact subscriber list name when the list ID is not known."},segmentId:{type:"string",description:"Filter by segment ID"},status:{type:"string",description:"Filter by subscriber status: active, unsubscribed, or bounced."},limit:{type:"number",description:"Maximum results to return. If omitted, the tool returns all matches across pages."}}}}];var Jz=[{name:"list_tags",description:"List all tags in the account",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list tags for. If not provided, uses the currently selected company."}}}},{name:"create_tag",description:"Create a new tag definition. The name is normalized to lowercase with hyphens (e.g. 'VIP Customer' becomes 'vip-customer'). Color defaults to gray.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Tag name. Normalized to lowercase with hyphens."},color:{type:"string",enum:[...X1],description:"Tag color. Defaults to gray."}},required:["name"]}},{name:"update_tag",description:"Update a tag's color. System tags cannot be updated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."},color:{type:"string",enum:[...X1],description:"New tag color."}},required:["tagId","color"]}},{name:"delete_tag",description:"Permanently delete a tag and remove it from all subscribers. This cannot be undone. System tags and tags used by sequences cannot be deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."}},required:["tagId"]}},{name:"list_lists",description:"List all subscriber lists",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list lists for. If not provided, uses the currently selected company."}}}},{name:"create_list",description:"Create a new subscriber list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the list in. If not provided, uses the currently selected company."},name:{type:"string",description:"List name"},description:{type:"string",description:"List description"}},required:["name"]}},{name:"update_list",description:"Update a subscriber list's name, description, or privacy. Only the provided fields are changed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to update."},name:{type:"string",description:"New list name."},description:{type:["string","null"],description:"New list description. Pass null to clear it."},isPrivate:{type:"boolean",description:"Whether the list is private."}},required:["listId"]}},{name:"delete_list",description:"Permanently delete a subscriber list and remove all of its memberships. Subscribers themselves are kept. This cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to delete."}},required:["listId"]}},{name:"add_subscribers_to_list",description:"Bulk add existing or new subscribers to a subscriber list from an email array. Existing subscribers are added to the list without requiring a per-subscriber update call.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to add subscribers to."},emails:{type:"array",items:{type:"string"},description:"Email addresses to add to the list. Maximum 500 per call."},duplicateStrategy:{type:"string",description:"Duplicate strategy for existing subscribers: skip, merge, or overwrite. Defaults to skip."},enrollInSequences:{type:"boolean",description:"Whether newly created subscribers should enroll in matching sequences. Defaults to false."},optInMode:{type:"string",description:"Consent mode for newly created subscribers: default, confirmed, or double_opt_in. Defaults to default."}},required:["listId","emails"]}},{name:"remove_subscribers_from_list",description:"Remove subscribers from a list by email address. Maximum 500 emails per call. Subscribers stay in the account; only the list membership is removed. Returns the removed count plus a notFound array of emails that did not match a subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to remove subscribers from."},emails:{type:"array",items:{type:"string"},description:"Email addresses to remove from the list. Maximum 500 per call."}},required:["listId","emails"]}},{name:"list_segments",description:"List all segments",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list segments for. If not provided, uses the currently selected company."}}}},{name:"create_segment",description:'Create a new segment from explicit filter rules. Use `filters` plus `filterJoinOperator` for flat legacy rules, or `root` for nested AND/OR groups such as `{ "kind": "group", "joinOperator": "and", "children": [{ "kind": "filter", "field": "attribute", "operator": "gte", "value": "mrr:50" }, { "kind": "group", "joinOperator": "or", "children": [{ "kind": "filter", "field": "tag", "operator": "contains", "value": "vip" }, { "kind": "filter", "field": "event", "operator": "is_not", "value": "saas.purchase:30d" }] }] }`. Supports `event` and `segment` fields, Stripe product purchase/current/trial/date filters, and campaign-specific engagement filters.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the segment in. If not provided, uses the currently selected company."},name:{type:"string",description:"Segment name"},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:OW,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example commerce product purchase filter (value is provider:productId since product ids are provider-scoped): [{"id":"filter-1","field":"commerceProduct","operator":"is","value":"api:prod-starter-kit"}]. Example repeat-buyer filter: [{"id":"filter-1","field":"commerceProduct","operator":"at_least","value":"shopify:42:2"}]. Example trial cancellation filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:is_canceled"}]. Example trial end filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:end_at:2026-05-26"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{...qW,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"update_segment",description:"Update a segment's name and/or filter rules. Use the same `filters` plus `filterJoinOperator` or nested `root` shapes as create_segment; providing `filters` or `root` replaces the segment's existing rules.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to update."},name:{type:"string",description:"New segment name."},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:OW,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...qW,description:"Replacement nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["segmentId"]}},{name:"delete_segment",description:"Permanently delete a segment. This cannot be undone. Subscribers are not affected.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to delete."}},required:["segmentId"]}},{name:"get_segment_count",description:"Get the number of subscribers in a segment",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID"}},required:["segmentId"]}}];var Dz=[{name:"list_team_members",description:"List team members for the company, including the owner, members with their roles, and pending or expired invitations.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"invite_team_member",description:"Invite a team member by email with role admin, viewer, or restricted. Existing Sequenzy users are added to the team immediately; others receive an email invitation. Billing access (canManageBilling) can only be granted by the company owner and is not available for restricted members.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Email address of the person to invite."},role:{type:"string",enum:["admin","viewer","restricted"],description:"Team role. Admins can manage the workspace; viewers have read-only access; restricted members can open direct campaign links only."},canManageBilling:{type:"boolean",description:"Whether the member can manage billing. Only the company owner can grant billing access. Defaults to false."}},required:["email","role"]}},{name:"cancel_team_invitation",description:"Cancel a pending team invitation. Invitations that have already been accepted cannot be cancelled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},invitationId:{type:"string",description:"Invitation ID to cancel. Use list_team_members to find pending invitations."}},required:["invitationId"]}}];var zz=[{name:"list_templates",description:"List all email templates, including per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template. For net-new email content requested in natural language, use `prompt`; do not write HTML or construct blocks yourself. Use `blocks` only for finished caller-supplied Sequenzy content and `html` only for supplied or explicitly requested preserved HTML.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line. Optional with `prompt`."},previewText:{type:["string","null"],description:"Optional preview text override."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider templates; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Jw,items:{type:"object"}},prompt:{type:"string",description:"Natural-language request for Sequenzy to generate branded native template blocks."},style:{type:"string",description:"Generation style; valid only with `prompt`."},tone:{type:"string",description:"Generation tone; valid only with `prompt`."},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `html`, `blocks`, or `labels` is required, and only those update fields are accepted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider templates; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Jw,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"set_template_localization",description:"Create or replace one caller-supplied localized variant of a template. The locale must be enabled for the company and cannot be its primary locale. Provide exactly one of `html` or `blocks`.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locale:{type:"string",description:"Enabled non-primary locale code such as es, fr, or pt-BR."},subject:{type:"string",description:"Localized email subject line."},previewText:{type:["string","null"],description:"Optional localized inbox preview text."},html:{type:"string",description:"Localized email HTML. Mutually exclusive with `blocks`."},blocks:{type:"array",description:Jw,items:{type:"object"}}},required:["templateId","locale","subject"],additionalProperties:!1}},{name:"sync_template_localizations",description:"Queue AI translation for selected template locales. Omit `locales` to sync every enabled non-primary locale. This works even when automatic on-save localization is disabled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locales:{type:"array",description:"Optional enabled non-primary locale codes to sync. Omit to sync all enabled non-primary locales.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}}];var Az=[{name:"list_transactional_emails",description:"List transactional email templates, including their API slugs and linked email IDs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Sequenzy stores it as one raw HTML block."},blocks:{type:"array",description:`${Jw} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Generated blocks include the company's branding (logo and a footer without an unsubscribe link). Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Prompt-created templates default to false; explicit HTML/blocks retain the compatibility default of true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Sequenzy stores it as one raw HTML block."},blocks:{type:"array",description:`${Dw} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Send one transactional email using either a saved transactional email API slug (`templateId`) or direct `subject` and `html` content.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line. Required with `html` when `templateId` is omitted."},html:{type:"string",description:"Direct-send HTML body. Required with `subject` when `templateId` is omitted; the MCP server maps this to the transactional API `body` field."},templateId:{type:"string",description:"Saved transactional email API slug, for example `welcome-email`. The field name is retained for MCP compatibility and is mapped to the transactional API `slug` field."},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics/localization on single-recipient sends. Maximum length: 255 characters."}},required:["to"],additionalProperties:!1}}];var Oz=[{name:"list_webhooks",description:"List outbound webhook endpoints and their subscribed event types.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_webhook",description:"Create an outbound webhook endpoint. IMPORTANT: the response includes a signingSecret that is returned only once - show it to the user immediately so they can store it and verify webhook signatures. If events is omitted, a default set of event types is subscribed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Webhook endpoint name."},url:{type:"string",description:"HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...Y1]},description:"Event types to subscribe to. If omitted, a default set is used."}},required:["name","url"]}},{name:"update_webhook",description:"Update an outbound webhook endpoint's name, URL, subscribed events, or status (enabled/disabled). Providing events replaces the existing event list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},name:{type:"string",description:"New webhook endpoint name."},url:{type:"string",description:"New HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...Y1]},description:"Replacement event type subscriptions."},status:{type:"string",enum:["enabled","disabled"],description:"Enable or disable deliveries to this endpoint."}},required:["webhookId"]}},{name:"delete_webhook",description:"Permanently delete an outbound webhook endpoint along with its delivery history. This cannot be undone. To keep the endpoint but stop deliveries, use update_webhook with status disabled instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to delete."}},required:["webhookId"]}},{name:"test_webhook",description:"Send a test event to an outbound webhook endpoint to verify it is reachable and signatures can be validated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to test."}},required:["webhookId"]}},{name:"list_webhook_deliveries",description:"List recent delivery attempts for an outbound webhook endpoint, including status and response codes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},limit:{type:"number",description:"Maximum number of deliveries to return, from 1 to 100. Defaults to 20."}},required:["webhookId"]}},{name:"replay_webhook_delivery",description:"Replay a previous webhook delivery, re-sending the same event payload to the endpoint.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},deliveryId:{type:"string",description:"Delivery ID to replay. Use list_webhook_deliveries to find delivery IDs."}},required:["webhookId","deliveryId"]}}];var qz=[...rD,...Hz,...Gz,...Jz,...aD,...zz,...tD,...bz,...Qz,...$z,...Xz,...Yz,...Az,...sD,...Dz,...Wz,...Oz,...eD,...wz];async function Lz(b,w){let $;switch(b){case"get_account":{let W=await A("GET","/api/v1/account"),Q=Ew();$={...W,selectedCompanyId:Q??W.currentCompanyId};break}case"select_company":{let W=w.companyId,Q=await A("GET","/api/v1/account"),G=Q.companies?.find((X)=>X.id===W);if(!G)throw Error(`Company not found. Available companies: ${Q.companies?.map((X)=>`${X.name} (${X.id})`).join(", ")??"none"}`);t$(W),$={success:!0,message:`Switched to company: ${G.name}`,companyId:G.id,companyName:G.name};break}case"get_app_urls":{let W=await n$(w);$={...Hw({companyId:W,campaignId:F(w,"campaignId"),landingPageId:F(w,"landingPageId"),sequenceId:F(w,"sequenceId"),emailId:F(w,"emailId")??F(w,"templateId"),transactionalId:F(w,"transactionalId"),emailSendId:F(w,"emailSendId"),domainId:F(w,"domainId"),status:F(w,"status"),settingsTab:F(w,"settingsTab")}),...W===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let W=await A("POST","/api/v1/companies",{name:w.name,domain:w.domain});if(!W.success)throw Error("Failed to create company");let Q=W.company.id,G=6,X=0,Y=W.company.status;while(Y==="processing"&&X<G){await new Promise((D)=>setTimeout(D,20000)),X++;let J=await A("GET",`/api/v1/companies/${Q}`);if(J.success)Y=J.company.status}t$(Q);let H=await A("GET",`/api/v1/companies/${Q}`);$={success:!0,company:H.company,message:Y==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${H.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let W=w.companyId;$=await A("GET",`/api/v1/companies/${W}`);break}case"update_company":{let W=await cD("update_company",w),Q=MD(w);$=await A("PATCH",`/api/v1/companies/${W}`,Q);break}case"get_sync_rules":{let W=w.companyId;$=await A("GET","/api/v1/sync-rules",void 0,W);break}case"update_sync_rules":{let W=w.companyId;if(w.syncRules!==null&&!Array.isArray(w.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");$=await A("PUT","/api/v1/sync-rules",{syncRules:w.syncRules},W);break}case"get_shopify_automation_settings":{let W=w.companyId;$=await A("GET","/api/v1/shopify/automation-settings",void 0,W);break}case"update_shopify_automation_settings":{let W=w.companyId,Q={};if(w.browseAbandonment!==void 0)Q.browseAbandonment=w.browseAbandonment;if(w.priceDrop!==void 0)Q.priceDrop=w.priceDrop;if(Object.keys(Q).length===0)throw Error("Provide `browseAbandonment` and/or `priceDrop` when calling `update_shopify_automation_settings`.");$=await A("PUT","/api/v1/shopify/automation-settings",Q,W);break}case"create_api_key":{let W=w.companyId,Q={};if(typeof w.name==="string")Q.name=w.name;if(typeof w.preset==="string")Q.preset=w.preset;if(Array.isArray(w.scopes))Q.scopes=w.scopes;$=await A("POST","/api/v1/api-keys",Q,W);break}case"list_websites":{let W=w.companyId;$=await A("GET","/api/v1/websites",void 0,W);break}case"add_sending_domain":case"add_website":{let W=w.companyId;$=await A("POST","/api/v1/websites",{domain:w.domain},W);break}case"check_website":{let W=w.companyId;$=await A("GET",`/api/v1/websites/${encodeURIComponent(String(w.domain))}`,void 0,W);break}case"verify_sending_domain":{let W=w.companyId;$=await A("POST",`/api/v1/websites/${encodeURIComponent(String(w.domain))}/verify`,void 0,W);break}case"get_integration_guide":$=await A("POST","/api/v1/integration-guide",w);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Uz(b,w){let $;switch(b){case"generate_email":{let W=w.companyId;$=await A("POST","/api/v1/generate/email",w,W);break}case"generate_subject_lines":{let W=w.companyId;$=await A("POST","/api/v1/generate/subjects",w,W);break}case"generate_sms":{let W=w.companyId;$=await A("POST","/api/v1/generate/sms",w,W);break}case"get_sms_settings":{let W=w.companyId;$=await A("GET","/api/v1/sms/settings",void 0,W);break}case"send_test_sms":{let W=w.companyId,Q={to:j("send_test_sms",w,"to")};for(let G of["text","imageUrls","blocks"])if(w[G]!==void 0)Q[G]=w[G];$=await A("POST","/api/v1/sms/test",Q,W);break}case"submit_feedback":{let W=w.companyId,Q={message:j("submit_feedback",w,"message"),source:"mcp"};for(let G of["category","context"])if(w[G]!==void 0)Q[G]=w[G];$=await A("POST","/api/v1/feedback",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Bz(b,w){let $;switch(b){case"list_transactional_emails":{let W=w.companyId;$=await A("GET","/api/v1/transactional",void 0,W);break}case"get_transactional_email":{let W=w.companyId;$=await A("GET",`/api/v1/transactional/${w.idOrSlug}`,void 0,W);break}case"create_transactional_email":{let W=w.companyId,Q=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),G=Object.keys(w).filter((Y)=>!Q.has(Y));if(G.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((Y)=>`\`${Y}\``).join(", ")}.`);CD(w);let X=Object.fromEntries(Object.entries(w).filter(([Y])=>Y!=="companyId"));$=await A("POST","/api/v1/transactional",X,W);break}case"update_transactional_email":{let W=w.companyId,Q=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),G=Object.keys(w).filter((Y)=>!Q.has(Y));if(G.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((Y)=>`\`${Y}\``).join(", ")}.`);if(_b("update_transactional_email",w),w.name===void 0&&w.enabled===void 0&&w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let X=Object.fromEntries(Object.entries(w).filter(([Y])=>Y!=="companyId"&&Y!=="idOrSlug"));$=await A("PATCH",`/api/v1/transactional/${w.idOrSlug}`,X,W);break}case"send_email":{let W=w.companyId,Q=j("send_email",w,"to"),G=w.templateId===void 0?void 0:j("send_email",w,"templateId"),X=w.subject===void 0?void 0:j("send_email",w,"subject"),Y=w.html===void 0?void 0:j("send_email",w,"html");if(G!==void 0&&(X!==void 0||Y!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(G===void 0&&(X===void 0||Y===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");let H=Object.fromEntries(Object.entries({to:Q,slug:G,subject:X,body:Y,variables:w.variables,subscriberExternalId:w.subscriberExternalId}).filter(([,J])=>J!==void 0));$=await A("POST","/api/v1/transactional/send",H,W);break}case"get_stats":{let W=w.companyId,Q=w.period??"7d",G=new URLSearchParams({period:String(Q)});if(w.includeMachineEngagement===!0)G.set("includeMachineEngagement","true");$=await A("GET",`/api/v1/metrics?${G.toString()}`,void 0,W);break}case"get_campaign_stats":{let W=w.companyId,Q=new URLSearchParams;if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let G=Q.toString();$=await A("GET",`/api/v1/metrics/campaigns/${w.campaignId}${G?`?${G}`:""}`,void 0,W);break}case"get_sequence_stats":{let W=w.companyId,Q=new URLSearchParams;if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let G=Q.toString();$=await A("GET",`/api/v1/metrics/sequences/${w.sequenceId}${G?`?${G}`:""}`,void 0,W);break}case"list_campaign_events":{let W=w.companyId,Q=j("list_campaign_events",w,"campaignId"),X=ZW("list_campaign_events",w).toString();$=await A("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(Q)}/events${X?`?${X}`:""}`,void 0,W);break}case"list_sequence_events":{let W=w.companyId,Q=j("list_sequence_events",w,"sequenceId"),X=ZW("list_sequence_events",w).toString();$=await A("GET",`/api/v1/metrics/sequences/${encodeURIComponent(Q)}/events${X?`?${X}`:""}`,void 0,W);break}case"get_subscriber_activity":{let W=w.companyId,Q=Aw("get_subscriber_activity",w),G=await H0(Q,W,{includeMachineEngagement:w.includeMachineEngagement===!0});$={success:G.success,email:G.subscriber.email,emailStats:G.subscriber.emailStats??null,activity:G.subscriber.activity??[],sequenceEnrollments:G.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Fz(b,w){let $;switch(b){case"list_tags":{let W=w.companyId;$=await A("GET","/api/v1/tags",void 0,W);break}case"create_tag":{let W=w.companyId,Q=j("create_tag",w,"name"),G=Vb("create_tag",w,"color",X1);$=await A("POST","/api/v1/tags",{name:Q,...G!==void 0&&{color:G}},W);break}case"update_tag":{let W=w.companyId,Q=j("update_tag",w,"tagId"),G=J0("update_tag",w,"color",X1);$=await A("PATCH",`/api/v1/tags/${encodeURIComponent(Q)}`,{color:G},W);break}case"delete_tag":{let W=w.companyId,Q=j("delete_tag",w,"tagId");$=await A("DELETE",`/api/v1/tags/${encodeURIComponent(Q)}`,void 0,W);break}case"list_lists":{let W=w.companyId;$=await A("GET","/api/v1/lists",void 0,W);break}case"create_list":{let W=w.companyId;$=await A("POST","/api/v1/lists",w,W);break}case"update_list":{let W=w.companyId,Q=j("update_list",w,"listId");if(w.name===void 0&&w.description===void 0&&w.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(w.name!==void 0&&F(w,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(w.description!==void 0&&w.description!==null&&typeof w.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(w.isPrivate!==void 0&&typeof w.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");$=await A("PATCH",`/api/v1/lists/${encodeURIComponent(Q)}`,{...w.name!==void 0&&{name:F(w,"name")},...w.description!==void 0&&{description:w.description},...w.isPrivate!==void 0&&{isPrivate:w.isPrivate}},W);break}case"delete_list":{let W=w.companyId,Q=j("delete_list",w,"listId");$=await A("DELETE",`/api/v1/lists/${encodeURIComponent(Q)}`,void 0,W);break}case"add_subscribers_to_list":{let W=w.companyId,Q=j("add_subscribers_to_list",w,"listId"),G=IW("add_subscribers_to_list",w),X=Vb("add_subscribers_to_list",w,"duplicateStrategy",["skip","merge","overwrite"])??"skip",Y=Vb("add_subscribers_to_list",w,"optInMode",["default","confirmed","double_opt_in"])??"default";$=await A("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers`,{emails:G,duplicateStrategy:X,enrollInSequences:w.enrollInSequences===!0,optInMode:Y},W);break}case"remove_subscribers_from_list":{let W=w.companyId,Q=j("remove_subscribers_from_list",w,"listId"),G=IW("remove_subscribers_from_list",w);$=await A("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers/remove`,{emails:G},W);break}case"list_segments":{let W=w.companyId;$=await A("GET","/api/v1/segments",void 0,W);break}case"create_segment":{KD(w);let W=w.companyId;$=await A("POST","/api/v1/segments",{...w,...w.filters!==void 0?{filters:x$(w.filters)}:{},...w.root!==void 0?{root:u$(w.root)}:{}},W);break}case"update_segment":{PD(w);let W=w.companyId,Q=j("update_segment",w,"segmentId"),G=F(w,"name"),X=Vb("update_segment",w,"filterJoinOperator",["and","or"]);$=await A("PATCH",`/api/v1/segments/${encodeURIComponent(Q)}`,{...G!==void 0&&{name:G},...X!==void 0&&{filterJoinOperator:X},...w.filters!==void 0?{filters:x$(w.filters)}:{},...w.root!==void 0?{root:u$(w.root)}:{}},W);break}case"delete_segment":{let W=w.companyId,Q=j("delete_segment",w,"segmentId");$=await A("DELETE",`/api/v1/segments/${encodeURIComponent(Q)}`,void 0,W);break}case"get_segment_count":{let W=w.companyId;$=await A("GET",`/api/v1/segments/${w.segmentId}/count`,void 0,W);break}case"list_audience_syncs":{let W=w.companyId;$=await A("GET","/api/v1/audience-syncs",void 0,W);break}case"list_ad_accounts":{let W=w.companyId;$=await A("GET","/api/v1/ad-accounts",void 0,W);break}case"create_audience_sync":{let W=w.companyId,Q=F(w,"segmentId"),G=F(w,"predefinedSegmentId");if(Q&&G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!Q&&!G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");$=await A("POST","/api/v1/audience-syncs",{segmentId:Q,predefinedSegmentId:G,adAccountId:j("create_audience_sync",w,"adAccountId"),audienceName:j("create_audience_sync",w,"audienceName"),...w.frequency!==void 0?{frequency:w.frequency}:{}},W);break}case"update_audience_sync":{let W=w.companyId,Q=j("update_audience_sync",w,"syncId");$=await A("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,{...w.frequency!==void 0?{frequency:w.frequency}:{},...w.isActive!==void 0?{isActive:w.isActive}:{}},W);break}case"delete_audience_sync":{let W=w.companyId,Q=j("delete_audience_sync",w,"syncId");$=await A("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,void 0,W);break}case"sync_audience_now":{let W=w.companyId,Q=j("sync_audience_now",w,"syncId");$=await A("POST",`/api/v1/audience-syncs/${encodeURIComponent(Q)}/sync`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Kz(b,w){let $;switch(b){case"list_templates":{let W=w.companyId,Q=new URLSearchParams,G=F(w,"label");if(G)Q.set("label",G);$=await A("GET",`/api/v1/templates${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_template":{let W=w.companyId;$=await A("GET",`/api/v1/templates/${w.templateId}`,void 0,W);break}case"create_template":{let W=w.companyId;RD(w);let Q=Object.fromEntries(Object.entries(w).filter(([G])=>G!=="companyId"));$=await A("POST","/api/v1/templates",Q,W);break}case"update_template":{let W=w.companyId,Q=new Set(["companyId","templateId","name","subject","html","blocks","labels"]),G=Object.keys(w).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);if(_b("update_template",w),H1("update_template",w),w.name===void 0&&w.subject===void 0&&w.html===void 0&&w.blocks===void 0&&w.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, `blocks`, or `labels` when calling `update_template`.");$=await A("PUT",`/api/v1/templates/${w.templateId}`,w,W);break}case"set_template_localization":{let W=w.companyId,Q=j("set_template_localization",w,"templateId"),G=j("set_template_localization",w,"locale"),X=j("set_template_localization",w,"subject"),Y=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),H=Object.keys(w).filter((D)=>!Y.has(D));if(H.length>0)throw Error(`\`set_template_localization\` received unsupported field${H.length===1?"":"s"}: ${H.map((D)=>`\`${D}\``).join(", ")}.`);_b("set_template_localization",w,{requireContent:!0});let J={subject:X};if(w.previewText!==void 0)J.previewText=w.previewText;if(w.html!==void 0)J.html=w.html;if(w.blocks!==void 0)J.blocks=w.blocks;$=await A("PUT",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/${encodeURIComponent(G)}`,J,W);break}case"sync_template_localizations":{let W=w.companyId,Q=j("sync_template_localizations",w,"templateId"),G=new Set(["companyId","templateId","locales"]),X=Object.keys(w).filter((H)=>!G.has(H));if(X.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${X.length===1?"":"s"}: ${X.map((H)=>`\`${H}\``).join(", ")}.`);let Y;if(w.locales!==void 0){if(!Array.isArray(w.locales)||w.locales.length===0||w.locales.some((H)=>typeof H!=="string"||H.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");Y=w.locales.map((H)=>H.trim())}$=await A("POST",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/sync`,Y===void 0?{}:{locales:Y},W);break}case"delete_template":{let W=w.companyId;$=await A("DELETE",`/api/v1/templates/${w.templateId}`,void 0,W);break}case"list_ab_tests":{let W=w.companyId,Q=new URLSearchParams,G=F(w,"sequenceId");if(G)Q.set("sequenceId",G);$=await A("GET",`/api/v1/ab-tests${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_ab_test":{let W=w.companyId;$=await A("GET",`/api/v1/ab-tests/${w.abTestId}`,void 0,W);break}case"get_ab_test_stats":{let W=w.companyId,Q=new URLSearchParams,G=F(w,"period"),X=F(w,"start"),Y=F(w,"end");if(G)Q.set("period",G);if(X)Q.set("start",X);if(Y)Q.set("end",Y);if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");$=await A("GET",`/api/v1/ab-tests/${w.abTestId}/stats${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"restart_ab_test":{let W=w.companyId,Q=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),G=Object.keys(w).filter((J)=>!Q.has(J));if(G.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${G.length===1?"":"s"}: ${G.map((J)=>`\`${J}\``).join(", ")}.`);let X=F(w,"testType");if(X!==void 0&&X!=="subject"&&X!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let Y=w.winnerThreshold===void 0?void 0:Number(w.winnerThreshold);if(Y!==void 0&&(!Number.isInteger(Y)||Y<10||Y>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let H=w.variantCount===void 0?void 0:Number(w.variantCount);if(H!==void 0&&(!Number.isInteger(H)||H<2||H>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");$=await A("POST",`/api/v1/ab-tests/${w.abTestId}/restart`,{sourceVariantId:F(w,"sourceVariantId"),testType:X,winnerThreshold:Y,variantCount:H},W);break}case"update_ab_test_variant":{let W=w.companyId,Q=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks"]),G=Object.keys(w).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);if(_b("update_ab_test_variant",w),w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");$=await A("PATCH",`/api/v1/ab-tests/${w.abTestId}/variants/${w.variantId}`,w,W);break}case"create_ab_test":{let W=w.companyId,Q=j("create_ab_test",w,"campaignId"),G=F(w,"name"),X=zw("create_ab_test",w,"testPercentage",5,50),Y=zw("create_ab_test",w,"testDurationMinutes",15,1440),H=Vb("create_ab_test",w,"winnerCriteria",["open_rate","click_rate"]);if(w.variants!==void 0){if(!Array.isArray(w.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");w.variants.forEach((J,D)=>{if(!y(J)||typeof J.subject!=="string"||J.subject.trim()==="")throw Error(`\`variants\` item ${D+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(J.blocks!==void 0&&!Array.isArray(J.blocks))throw Error(`\`variants\` item ${D+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}$=await A("POST","/api/v1/ab-tests",{campaignId:Q,...G!==void 0&&{name:G},...X!==void 0&&{testPercentage:X},...Y!==void 0&&{testDurationMinutes:Y},...H!==void 0&&{winnerCriteria:H},...w.variants!==void 0&&{variants:w.variants}},W);break}case"add_ab_test_variant":{let W=w.companyId,Q=j("add_ab_test_variant",w,"abTestId"),G=j("add_ab_test_variant",w,"subject"),X=F(w,"previewText");if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");$=await A("POST",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants`,{subject:G,...X!==void 0&&{previewText:X},...w.blocks!==void 0&&{blocks:w.blocks}},W);break}case"delete_ab_test_variant":{let W=w.companyId,Q=j("delete_ab_test_variant",w,"abTestId"),G=j("delete_ab_test_variant",w,"variantId");$=await A("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants/${encodeURIComponent(G)}`,void 0,W);break}case"delete_ab_test":{let W=w.companyId,Q=j("delete_ab_test",w,"abTestId");$=await A("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}`,void 0,W);break}case"list_campaigns":{let W=w.companyId,Q=new URLSearchParams;if(w.status)Q.set("status",String(w.status));let G=F(w,"label");if(G)Q.set("label",G);$=await A("GET",`/api/v1/campaigns?${Q}`,void 0,W);break}case"get_campaign":{let W=w.companyId;$=await A("GET",`/api/v1/campaigns/${w.campaignId}`,void 0,W);break}case"get_email_send":{let W=w.companyId;$=await A("GET",`/api/v1/email-sends/${encodeURIComponent(String(w.emailSendId))}`,void 0,W);break}case"create_campaign":{let W=w.companyId;if(SD(w),w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_campaign`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_campaign`.");let Q=Object.fromEntries(Object.entries(w).filter(([G])=>G!=="companyId"));$=await A("POST","/api/v1/campaigns",Q,W);break}case"update_campaign":{let W=w.companyId,Q=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","campaignData","computedLists","labels"]),G=Object.keys(w).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, and label update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);if(_b("update_campaign",w),H1("update_campaign",w),w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_campaign`.");if(w.name===void 0&&w.subject===void 0&&w.trackingCode===void 0&&w.html===void 0&&w.blocks===void 0&&w.fromEmail===void 0&&w.senderProfileId===void 0&&w.replyTo===void 0&&w.replyProfileId===void 0&&w.campaignData===void 0&&w.computedLists===void 0&&w.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, or label field when calling `update_campaign`.");$=await A("PUT",`/api/v1/campaigns/${w.campaignId}`,w,W);break}case"schedule_campaign":{let W=w.companyId,Q=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),G=Object.keys(w).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);kD(w),$=await A("POST",`/api/v1/campaigns/${w.campaignId}/schedule`,{scheduledAt:w.scheduledAt,...w.targetLists!==void 0&&{targetLists:w.targetLists},...w.sendTimeOptimization!==void 0&&{sendTimeOptimization:w.sendTimeOptimization},...w.spreadOverHours!==void 0&&{spreadOverHours:w.spreadOverHours},...w.recurringInterval!==void 0&&{recurringInterval:w.recurringInterval}},W);break}case"send_test_email":{let W=w.companyId;$=await A("POST",`/api/v1/campaigns/${w.campaignId}/test`,{to:w.to},W);break}case"cancel_campaign":{let W=w.companyId,Q=j("cancel_campaign",w,"campaignId");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/cancel`,void 0,W);break}case"pause_campaign":{let W=w.companyId,Q=j("pause_campaign",w,"campaignId");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/pause`,void 0,W);break}case"resume_campaign":{let W=w.companyId,Q=j("resume_campaign",w,"campaignId"),G=zw("resume_campaign",w,"spreadOverHours",1,72);$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resume`,{...G!==void 0&&{spreadOverHours:G}},W);break}case"delete_campaign":{let W=w.companyId,Q=j("delete_campaign",w,"campaignId");$=await A("DELETE",`/api/v1/campaigns/${encodeURIComponent(Q)}`,void 0,W);break}case"duplicate_campaign":{let W=w.companyId,Q=j("duplicate_campaign",w,"campaignId"),G=Vb("duplicate_campaign",w,"mode",["campaign","ab_test","variant"]),X=F(w,"variantId");if(G==="variant"&&X===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/duplicate`,{...G!==void 0&&{mode:G},...X!==void 0&&{variantId:X}},W);break}case"resend_campaign_to_non_openers":{let W=w.companyId,Q=j("resend_campaign_to_non_openers",w,"campaignId");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resend-to-non-openers`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function l$(b,w,$,W,Q){let G=b[w];if(G===void 0)return;if(typeof G!=="number"||!Number.isFinite(G)||G<$||G>W||Q&&!Number.isInteger(G))throw Error(`\`${w}\` must be a ${Q?"integer":"number"} between ${$} and ${W} when calling \`upload_image_asset\`.`);return G}async function Pz(b,w){if(b!=="upload_image_asset")return{handled:!1,result:void 0};let $=F(w,"filePath"),W=F(w,"imageBase64");if($===void 0===(W===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let Q=F(w,"filename");if(W!==void 0&&Q===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let G=l$(w,"sourceWidth",1,20000,!0),X=l$(w,"sourceHeight",1,20000,!0);if(G===void 0!==(X===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let Y=l$(w,"displayWidthPercent",1,100,!1)??100,H=l$(w,"cropHeight",1,2000,!0),J=F(w,"objectFit");if(J!==void 0&&J!=="cover"&&J!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(J!==void 0&&H===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let D=F(w,"align");if(D!==void 0&&!["left","center","right"].includes(D))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let z=typeof w.altText==="string"?w.altText.trim():void 0;if(z!==void 0&&z.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let O=await pD({companyId:F(w,"companyId"),filePath:$,imageBase64:W,filename:Q,contentType:F(w,"contentType"),altText:z,sourceWidth:G,sourceHeight:X}),q={type:"image",src:O.url,alt:O.altText??"",width:Y,widthType:"percent",...H!==void 0&&{height:H,objectFit:J??"cover"},...D!==void 0&&{align:D}};return{handled:!0,result:{success:!0,asset:O,imageBlock:q,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function Mz(b,w){let $;switch(b){case"list_landing_pages":{let W=w.companyId;$=await A("GET","/api/v1/landing-pages",void 0,W);break}case"get_landing_page":{let W=w.companyId;$=await A("GET",`/api/v1/landing-pages/${w.landingPageId}`,void 0,W);break}case"create_landing_page":{let W=w.companyId,Q=new Set(["companyId","name","slug","template","content"]),G=Object.keys(w).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);$=await A("POST","/api/v1/landing-pages",{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.template!==void 0&&{template:w.template},...w.content!==void 0&&{content:w.content}},W);break}case"update_landing_page":{let W=w.companyId,Q=c$("update_landing_page",w,{requireUpdate:!0});$=await A("PUT",`/api/v1/landing-pages/${w.landingPageId}`,Q,W);break}case"publish_landing_page":{let W=w.companyId,Q=c$("publish_landing_page",w,{requireUpdate:!1});$=await A("POST",`/api/v1/landing-pages/${w.landingPageId}/publish`,Q,W);break}case"unpublish_landing_page":{let W=w.companyId,Q=c$("unpublish_landing_page",w,{requireUpdate:!1});$=await A("POST",`/api/v1/landing-pages/${w.landingPageId}/unpublish`,Q,W);break}case"delete_landing_page":{let W=w.companyId;$=await A("DELETE",`/api/v1/landing-pages/${w.landingPageId}`,void 0,W);break}case"connect_landing_page_domain":{let W=w.companyId;$=await A("POST","/api/v1/landing-pages/domain",{domain:w.domain},W);break}case"update_landing_page_domain_settings":{let W=w.companyId,Q=vD(w);$=await A("PUT","/api/v1/landing-pages/domain",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Zz(b,w){let $;switch(b){case"list_products":{let W=w.companyId,Q=new URLSearchParams;if(typeof w.provider==="string"&&w.provider.trim())Q.set("provider",w.provider.trim());if(typeof w.search==="string"&&w.search.trim())Q.set("search",w.search.trim());let G=Q.size>0?`?${Q.toString()}`:"";$=await A("GET",`/api/v1/products${G}`,void 0,W);break}case"upsert_products":{let W=w.companyId;if(!Array.isArray(w.products)||w.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");$=await A("POST","/api/v1/products",{products:w.products},W);break}case"delete_product":{let W=w.companyId,Q=j("delete_product",w,"productId");$=await A("DELETE",`/api/v1/products/${encodeURIComponent(Q)}`,void 0,W);break}case"attach_product_file":{let W=w.companyId,Q=j("attach_product_file",w,"productId"),G=F(w,"url"),X=F(w,"filePath");if(G===void 0===(X===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let Y;if(X!==void 0){let H=await fD(X,W);Y={url:H.url,source:"upload",fileName:F(w,"fileName")??H.fileName,fileSizeBytes:H.fileSizeBytes,mimeType:H.mimeType}}else{Y={url:G};let H=F(w,"fileName");if(H)Y.fileName=H}$=await A("PUT",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,Y,W);break}case"remove_product_file":{let W=w.companyId,Q=j("remove_product_file",w,"productId");$=await A("DELETE",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,void 0,W);break}case"sync_products":{let W=w.companyId;$=await A("POST","/api/v1/products/sync",void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var jz=80;function FM(b){let w=b.trim().replace(/\s+/g," ");if(w.length<=jz)return w;return`${w.slice(0,jz-3).trimEnd()}...`}async function EW(b,w){let $;switch(b){case"generate_sequence":{let W=j("generate_sequence",w,"goal"),Q=typeof w.name==="string"&&w.name.trim().length>0?w.name.trim():void 0,X=(await EW("create_sequence",{...w,goal:W,name:Q??FM(W),trigger:"contact_added",durationDays:w.durationDays??14})).result;return{handled:!0,result:typeof X==="object"&&X!==null?{...X,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:X}}case"list_sequences":{let W=w.companyId;$=await A("GET","/api/v1/sequences",void 0,W);break}case"get_sequence":{let W=w.companyId;$=await A("GET",`/api/v1/sequences/${w.sequenceId}`,void 0,W);break}case"create_sequence":{let W=w.companyId;if(w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_sequence`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_sequence`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_sequence`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_sequence`.");let Q=Array.isArray(w.steps)&&w.steps.length>0,G=await A("POST","/api/v1/sequences",w,W);if(!G.success){$=G;break}let X=G.sequence.id;if(Q){let z=await A("GET",`/api/v1/sequences/${X}`,void 0,W);if(z.success)$={...G,success:!0,sequence:z.sequence,message:`Sequence "${z.sequence.name}" created with explicit steps. Review it before enabling.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=z;break}let Y=7,H=0,J="pending";while(J!=="complete"&&H<Y){let z=await A("GET",`/api/v1/sequences/${X}`,void 0,W);if(z.success)J=z.sequence.enrichmentStatus;if(H++,J!=="complete"&&H<Y)await new Promise((O)=>setTimeout(O,20000))}let D=await A("GET",`/api/v1/sequences/${X}`,void 0,W);if(D.success)$={...G,success:!0,sequence:D.sequence,message:D.sequence.enrichmentStatus==="complete"?`Sequence "${D.sequence.name}" created with ${D.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${D.sequence.name}" created. Email enrichment is still in progress (${D.sequence.enrichedCount}/${D.sequence.emailCount} emails generated). You can check status with get_sequence.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=D;break}case"update_sequence":{let W=w.companyId,Q=jD(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"update_sequence_node":{let W=w.companyId,Q=j("update_sequence_node",w,"sequenceId"),G=VD(w);$=await A("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"update_sequence_nodes":{let W=w.companyId,Q=j("update_sequence_nodes",w,"sequenceId"),G=ND(w);$=await A("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"edit_sequence_graph":{let W=w.companyId,Q=TD(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"insert_sequence_step":{let W=w.companyId,Q=ED(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"enable_sequence":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/enable`,void 0,W);break}case"disable_sequence":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/disable`,void 0,W);break}case"pause_sequence_enrollments":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/pause-enrollments`,void 0,W);break}case"resume_sequence_enrollments":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/resume-enrollments`,void 0,W);break}case"enroll_subscribers_in_sequence":{let W=w.companyId,Q=j("enroll_subscribers_in_sequence",w,"sequenceId"),G=hD(w);$=await A("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/enroll`,G,W);break}case"cancel_sequence_enrollments":{let W=w.companyId,Q=_D(w);$=await A("POST",`/api/v1/sequences/${w.sequenceId}/enrollments/cancel`,Q,W);break}case"delete_sequence":{let W=w.companyId;$=await A("DELETE",`/api/v1/sequences/${w.sequenceId}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Iz(b,w){let $;switch(b){case"add_subscriber":{let W=w.companyId,Q=Aw("add_subscriber",w);$=await A("POST","/api/v1/subscribers",{...Q,customAttributes:w.attributes,tags:w.tags,lists:w.listIds,...w.status!==void 0&&{status:w.status},...w.optInMode!==void 0&&{optInMode:w.optInMode}},W);break}case"update_subscriber":{let W=w.companyId,Q=Aw("update_subscriber",w),G=await H0(Q,W),X=Array.isArray(G.subscriber.tags)?G.subscriber.tags.filter((z)=>typeof z==="string"):[],Y=Array.isArray(w.addTags)?w.addTags.filter((z)=>typeof z==="string"&&z.trim()!=="").map(PW):[],H=new Set(Array.isArray(w.removeTags)?w.removeTags.filter((z)=>typeof z==="string"&&z.trim()!=="").map(PW):[]),J=X.filter((z)=>!H.has(z));for(let z of Y)if(!J.includes(z))J.push(z);let D={};if(Q.email&&Q.externalId)D.externalId=Q.externalId;if(y(w.attributes))D.customAttributes={...y(G.subscriber.customAttributes)?G.subscriber.customAttributes:{},...w.attributes};if(w.addTags||w.removeTags)D.tags=J;$=await A("PATCH",m$(Q),D,W);break}case"remove_subscriber":{let W=w.companyId,Q=Aw("remove_subscriber",w),G=m$(Q);if(w.hardDelete===!0)$=await A("DELETE",G,void 0,W);else $=await A("PATCH",G,{status:"unsubscribed"},W);break}case"get_subscriber":{let W=w.companyId,Q=Aw("get_subscriber",w);$=await H0(Q,W,{includeMachineEngagement:w.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let W=w.companyId,Q=Aw("list_subscriber_notes",w);$=await A("GET",MW(Q),void 0,W);break}case"add_subscriber_note":{let W=w.companyId,Q=Aw("add_subscriber_note",w),G=typeof w.body==="string"?w.body.trim():void 0;if(!G)throw Error("`body` is required when calling `add_subscriber_note`.");if(G.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");$=await A("POST",MW(Q),{body:G},W);break}case"delete_subscriber_note":{let W=w.companyId,Q=typeof w.noteId==="string"?w.noteId.trim():"";if(!Q)throw Error("`noteId` is required when calling `delete_subscriber_note`.");$=await A("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(Q)}`,void 0,W);break}case"search_subscribers":{let W=w.companyId;$=await yD(w,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Vz(b,w){let $;switch(b){case"list_team_members":{let W=w.companyId;$=await A("GET","/api/v1/team",void 0,W);break}case"invite_team_member":{let W=w.companyId,Q=j("invite_team_member",w,"email"),G=J0("invite_team_member",w,"role",["admin","viewer","restricted"]);if(w.canManageBilling!==void 0&&typeof w.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");$=await A("POST","/api/v1/team/invitations",{email:Q,role:G,...w.canManageBilling!==void 0&&{canManageBilling:w.canManageBilling}},W);break}case"cancel_team_invitation":{let W=w.companyId,Q=j("cancel_team_invitation",w,"invitationId");$=await A("DELETE",`/api/v1/team/invitations/${encodeURIComponent(Q)}`,void 0,W);break}case"list_conversations":{let W=w.companyId,Q=new URLSearchParams,G=Vb("list_conversations",w,"status",["open","closed","all"]);if(G)Q.set("status",G);let X=F(w,"search");if(X)Q.set("search",X);if(w.unread!==void 0){if(typeof w.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(w.unread)Q.set("unread","true")}if(w.page!==void 0){if(typeof w.page!=="number"||!Number.isInteger(w.page)||w.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");Q.set("page",String(w.page))}let Y=zw("list_conversations",w,"limit",1,100);if(Y!==void 0)Q.set("limit",String(Y));$=await A("GET",`/api/v1/conversations${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_conversation":{let W=w.companyId,Q=j("get_conversation",w,"conversationId");$=await A("GET",`/api/v1/conversations/${encodeURIComponent(Q)}`,void 0,W);break}case"reply_to_conversation":{let W=w.companyId,Q=j("reply_to_conversation",w,"conversationId"),G=Vb("reply_to_conversation",w,"type",["outbound","note"])??"outbound",X=F(w,"subject"),Y=F(w,"bodyText"),H=F(w,"bodyHtml");if(G==="outbound"&&Y===void 0&&H===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");$=await A("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/messages`,{type:G,...X!==void 0&&{subject:X},...Y!==void 0&&{bodyText:Y},...H!==void 0&&{bodyHtml:H}},W);break}case"update_conversation_status":{let W=w.companyId,Q=j("update_conversation_status",w,"conversationId"),G=J0("update_conversation_status",w,"status",["open","closed"]);$=await A("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/status`,{status:G},W);break}case"mark_conversation_read":{let W=w.companyId,Q=j("mark_conversation_read",w,"conversationId");$=await A("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/read`,void 0,W);break}case"list_webhooks":{let W=w.companyId;$=await A("GET","/api/v1/webhooks",void 0,W);break}case"create_webhook":{let W=w.companyId,Q=j("create_webhook",w,"name"),G=j("create_webhook",w,"url"),X=jW("create_webhook",w);$=await A("POST","/api/v1/webhooks",{name:Q,url:G,...X!==void 0&&{events:X}},W);break}case"update_webhook":{let W=w.companyId,Q=j("update_webhook",w,"webhookId"),G=F(w,"name"),X=F(w,"url"),Y=jW("update_webhook",w),H=Vb("update_webhook",w,"status",["enabled","disabled"]);if(G===void 0&&X===void 0&&Y===void 0&&H===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");$=await A("PATCH",`/api/v1/webhooks/${encodeURIComponent(Q)}`,{...G!==void 0&&{name:G},...X!==void 0&&{url:X},...Y!==void 0&&{events:Y},...H!==void 0&&{status:H}},W);break}case"delete_webhook":{let W=w.companyId,Q=j("delete_webhook",w,"webhookId");$=await A("DELETE",`/api/v1/webhooks/${encodeURIComponent(Q)}`,void 0,W);break}case"test_webhook":{let W=w.companyId,Q=j("test_webhook",w,"webhookId");$=await A("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/test`,void 0,W);break}case"list_webhook_deliveries":{let W=w.companyId,Q=j("list_webhook_deliveries",w,"webhookId"),G=zw("list_webhook_deliveries",w,"limit",1,100),X=new URLSearchParams;if(G!==void 0)X.set("limit",String(G));$=await A("GET",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries${X.size>0?`?${X}`:""}`,void 0,W);break}case"replay_webhook_delivery":{let W=w.companyId,Q=j("replay_webhook_delivery",w,"webhookId"),G=j("replay_webhook_delivery",w,"deliveryId");$=await A("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries/${encodeURIComponent(G)}/replay`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var Nz=[Lz,Iz,Zz,Fz,Kz,Mz,Pz,EW,Bz,Vz,Uz];var Tz=qz.map(oD).map(LD);async function Ez(b,w){try{let $,W=!1;for(let G of Nz){let X=await G(b,w);if(X.handled){$=X.result,W=!0;break}}if(!W)throw Error(`Unknown tool: ${b}`);let Q=xD($);if(Q)throw Q;return $=await mD(b,w,$),{structuredContent:dD($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:yw($)}]}}}async function _z(b,w,$){let W=w.getRequestContext?.(b)??{};try{return await xW(W,$)}finally{await w.onRequestContextUpdated?.(W,b)}}function Qk(b={}){let w=new YW({name:"sequenzy",version:JD.version},{capabilities:{tools:{},resources:{}},instructions:["Sequenzy email marketing MCP server: manage subscribers, campaigns, sequences, templates, and delivery stats.","If you have access to multiple companies, call get_account and then select_company (or pass companyId per call) before other tools.","IMPORTANT: whenever the user wanted to accomplish something and these tools did not expose functionality for it (missing tool, missing argument, unsupported workflow, or broken behavior), call submit_feedback describing the gap before finishing the task. The Sequenzy team reads every submission and uses it to decide what to build next."].join(`
51
- `)});return w.setRequestHandler(d4,async()=>{return{tools:Tz}}),w.setRequestHandler(C1,async($,W)=>{let{name:Q,arguments:G}=$.params;return _z(W,b,()=>Ez(Q,G??{}))}),w.setRequestHandler(g4,async()=>{return{resources:AD}}),w.setRequestHandler(n4,async($,W)=>{let{uri:Q}=$.params;return _z(W,b,()=>OD(Q))}),w}export{Qk as createSequenzyMcpServer};
50
+ Before protected server-side API work, use create_api_key and save the key to .env as SEQUENZY_API_KEY. Static-site saved forms are the exception: use list_forms/create_form/get_form_embed and never place a secret key in browser code.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration), 'ecommerce' (connecting a custom e-commerce platform via the Commerce API)"}}}}];var eJ=[{name:"generate_email",description:"Generate email blocks from a prompt. Generated blocks include the company's branding chrome (logo, footer with company name/address/unsubscribe) by default, matching emails created in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"},applyBranding:{type:"boolean",description:"Wrap the generated content with company branding (logo + footer). Defaults to true; set false to get raw content blocks only."},emailType:{type:"string",enum:["marketing","transactional"],description:"Email type. Transactional emails get a footer without the unsubscribe link. Defaults to marketing."}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED compatibility alias - use create_sequence] Create and persist a disabled AI-generated email sequence draft from a goal. The saved draft appears in list_sequences. The name defaults to the goal and the trigger defaults to contact_added; optionally pass listId to scope it. Review before enabling.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},name:{type:"string",description:"Optional sequence name. Defaults to the goal."},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"},listId:{type:"string",description:"Optional list ID. When provided, only contacts added to this list trigger the sequence."}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}},{name:"generate_sms",description:"Generate SMS marketing message variants from a prompt. Returns plain-text messages with per-message encoding and segment counts. Use the results as the 'text' of an SMS sequence step (insert_sequence_step with type 'sms' or a create_sequence sms step). Messages exclude opt-out footers and brand prefixes - the platform adds those automatically at send time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the SMS to generate (e.g., 'cart reminder with a free-shipping hook')"},count:{type:"number",description:"Number of message variants to generate (default: 3, max: 10)"}},required:["prompt"]}},{name:"get_sms_settings",description:"Get the company's SMS add-on status: whether SMS is enabled, plan eligibility, credit balance, brand prefix, phone numbers, and whether SMS steps will actually send. Check this before adding SMS steps to sequences so you can warn the user when SMS is not ready.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"send_test_sms",description:"Send a test SMS to a phone number. IMPORTANT: sends a real text message and charges SMS credits - only call when the user explicitly asks for a test send. Requires the SMS add-on with a verified number (check get_sms_settings). Limited to 5 test sends per hour; bypasses quiet hours; excluded from step stats.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Destination phone number in international E.164 format, e.g. +15550100123."},text:{type:"string",description:"Plain-text message body. Merge tags are not resolved for test sends to arbitrary numbers. Provide text or blocks."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable image URLs sent as MMS media (US/CA only)."},blocks:{type:"array",items:{type:"object"},description:"SMS content blocks (text + image subset). Provide text or blocks, not both."}},required:["to"]}}];var sJ=[{name:"get_stats",description:"Get overview statistics for a time period",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"},includeMachineEngagement:lb}}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including attributed conversions, revenue (revenueCents), a per-link click breakdown in the top-level clickedLinks array, and any Poll or NPS survey summaries in the top-level polls array",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},includeMachineEngagement:lb},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence, including attributed conversions and revenue (revenueCents) plus per-step failed subscribers and failure reasons",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},includeMachineEngagement:lb},required:["sequenceId"]}},{name:"list_campaign_events",description:"List paginated raw email events for a campaign. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:lb},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:lb},required:["sequenceId"]}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:lb},required:[]}}];var aJ=[{name:"list_audience_syncs",description:"List Meta custom audience syncs (segment -> ad audience mappings) with their schedule and last sync status. Requires the Meta Ads integration to be connected in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_ad_accounts",description:"List the Meta ad accounts available through the connected Meta Ads integration. Use the returned account id as `adAccountId` when creating an audience sync.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_audience_sync",description:'Push a segment to a Meta custom audience and keep it synced on a schedule. Provide `segmentId` for an existing segment OR `predefinedSegmentId` for a ready-made template (for example "zero-ltv", "no-purchase-1y", "recent-buyers", "high-spenders-ecom", "non-buyers", "engaged") - the template segment is created automatically on first use. The first upload runs immediately. Note: audiences are add-only; subscribers who later leave the segment stay in the Meta audience.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Existing segment ID to sync. Mutually exclusive with `predefinedSegmentId`."},predefinedSegmentId:{type:"string",description:'Predefined segment template ID (for example "zero-ltv", "no-purchase-1y", "recent-buyers"). The segment is created automatically if it does not exist. Mutually exclusive with `segmentId`.'},adAccountId:{type:"string",description:"Meta ad account ID (act_...) from `list_ad_accounts`."},audienceName:{type:"string",description:"Name for the custom audience in Meta Ads Manager."},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"How often to re-upload the segment. Default: daily."}},required:["adAccountId","audienceName"]}},{name:"update_audience_sync",description:"Update an audience sync's frequency or pause/resume it (`isActive`).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID"},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"New sync frequency."},isActive:{type:"boolean",description:"Set false to pause the sync, true to resume it."}},required:["syncId"]}},{name:"delete_audience_sync",description:"Remove an audience sync mapping. The Meta audience itself is kept (running ads are not disrupted) - only future syncs stop.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to remove."}},required:["syncId"]}},{name:"sync_audience_now",description:"Trigger an immediate upload of the segment's subscribers to its Meta custom audience, outside the regular schedule.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to run."}},required:["syncId"]}}];var bz=[{name:"list_campaigns",description:"List all campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent)"},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."}}}},{name:"get_campaign",description:"Get campaign details and stats",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_email_send",description:"Get an email delivery by emailSendId, including queued and test sends, delivery status, provider failure reason, stored HTML, and the ClickHouse event timeline. Queue jobs are internal execution details and are not exposed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Durable email delivery ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider campaigns; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Hw,items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Generated blocks include the company's logo and footer, and the created campaign inherits the company brand font. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Target segment ID"},fromEmail:{type:"string",description:"From address for this campaign. Its domain must be configured and verified; a sender profile is created when needed."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for this campaign. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},campaignData:{type:"object",description:"Optional campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Optional computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested. Send an empty string to clear it."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider campaigns; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Hw,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},ccEmails:{type:["array","null"],description:"Addresses CC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},bccEmails:{type:["array","null"],description:"Addresses BCC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Queue a campaign test email to a single address. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"resend_campaign_to_non_openers",description:"Create a draft that resends a sent campaign to everyone in the same audience who didn't open it. Copies the campaign email and reuses the original audience with a 'didn't open this campaign' rule added. Only available 6 hours after the campaign finishes sending. The draft must be scheduled or sent separately. Returns the new draft and an estimate of how many subscribers haven't opened the original.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"ID of the sent campaign to resend to non-openers."}},required:["campaignId"]}}];var wz=[{name:"submit_feedback",description:"Send product feedback about Sequenzy itself to the Sequenzy team. IMPORTANT: call this tool whenever the user wanted to accomplish something and Sequenzy did not expose functionality for it - a missing tool or argument, an unsupported workflow, a confusing behavior, or a bug. Briefly tell the user you reported the gap. This feedback goes straight to the team and shapes what gets built next. Do not use it for questions about the user's own account or data, and never include secrets or API keys. Submitting feedback never changes account data.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},message:{type:"string",description:"The feedback itself. Be specific: what was needed, what was missing or wrong, and what you did instead (workaround, gave up, used the dashboard)."},category:{type:"string",enum:["missing_capability","bug","docs","ux","praise","other"],description:"Feedback category. Use missing_capability when the user wanted something these tools do not support (default: other)."},context:{type:"string",description:"Optional: what the user was trying to accomplish, in their words, plus any relevant tool names or arguments you tried."}},required:["message"]}}];var $z=[{name:"list_forms",description:"List saved signup forms for a company, including their server-managed audience settings and public action URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list forms for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"create_form",description:"Create and publish a saved signup form whose opaque formId is a client-safe public capability. The selected lists, tags, duplicate behavior, and success action stay server-side; no API key is needed in the deployed form.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the form in. If not provided, uses the currently selected company."},name:{type:"string",description:"Internal saved-form name."},listIds:{type:"array",description:"One or more list IDs that every public submission will be added to. Use list_lists to resolve IDs.",items:{type:"string"}},tagIds:{type:"array",description:"Optional existing tag IDs applied by the saved form. Use list_tags to resolve IDs.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber. Defaults to skip."},buttonText:{type:"string",description:"Optional submit button label."},headline:{type:"string",description:"Optional form headline."},description:{type:"string",description:"Optional supporting form copy."},successMessage:{type:"string",description:"Confirmation shown after a successful submission when redirectUrl is omitted."},redirectUrl:{type:"string",description:"Optional HTTP or HTTPS URL for successful submissions. Omit it to show the saved confirmation message."},showFirstName:{type:"boolean",description:"Whether the generated form also collects first name."},showLastName:{type:"boolean",description:"Whether the generated form also collects last name."}},required:["name","listIds"],additionalProperties:!1}},{name:"get_form_embed",description:"Get a published saved form's action URL, one-line JavaScript embed, minimal native form action, and fetch example. Use this for Astro, Hugo, Jekyll, Cloudflare Pages, Netlify, GitHub Pages, or any browser integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."}},required:["formId"],additionalProperties:!1}}];var Wz=[{name:"upload_image_asset",description:"Upload an image to the selected company's shared media library and return a hosted URL plus a ready-to-insert Sequenzy image block. Call this before create/update campaign, sequence, template, or transactional tools, then place the returned imageBlock in the target blocks array. Provide either filePath (local stdio MCP only) or imageBase64 (works with remote MCP when the client can supply attachment bytes), not both. PNG, JPEG, GIF, and WebP are supported up to 5MB. cropHeight with objectFit:'cover' provides a precise centered screenshot crop while displayWidthPercent keeps the image responsive.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},filePath:{type:"string",description:"Local path to a PNG, JPEG, GIF, or WebP image. Available only when the MCP server runs locally. Provide filePath or imageBase64, not both."},imageBase64:{type:"string",description:"Raw base64 image bytes or a base64 data URL. Use this for remote MCP clients that can access attachment bytes. Provide imageBase64 or filePath, not both."},filename:{type:"string",description:"File name including extension. Required with imageBase64; optional override with filePath."},contentType:{type:"string",description:"Image MIME type when it cannot be inferred from filename, such as image/png."},altText:{type:"string",description:"Accessible description stored with the asset and returned as imageBlock.alt. Use an empty string only for a decorative image."},sourceWidth:{type:"integer",minimum:1,maximum:20000,description:"Optional intrinsic source width in pixels. Provide sourceWidth and sourceHeight together when known."},sourceHeight:{type:"integer",minimum:1,maximum:20000,description:"Optional intrinsic source height in pixels. Provide sourceWidth and sourceHeight together when known."},displayWidthPercent:{type:"number",minimum:1,maximum:100,description:"Responsive image width as a percentage of the email content area. Defaults to 100."},cropHeight:{type:"integer",minimum:1,maximum:2000,description:"Optional fixed display height in pixels. With objectFit:'cover', the image is centered and cropped to this height."},objectFit:{type:"string",enum:["cover","contain"],description:"How the image fits cropHeight. Defaults to cover when cropHeight is provided. Only valid with cropHeight."},align:{type:"string",enum:["left","center","right"],description:"Image alignment. Defaults to center."}},additionalProperties:!1}}];var Qz=[{name:"list_conversations",description:"List inbox conversations (email replies from subscribers). Filter by status, free-text search, or unread state, with pagination.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},status:{type:"string",enum:["open","closed","all"],description:"Filter by conversation status. Defaults to all."},search:{type:"string",description:"Free-text search across conversation subjects and participants."},unread:{type:"boolean",description:"Set true to only return conversations with unread messages."},page:{type:"number",description:"Page number. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."}}}},{name:"get_conversation",description:"Get a conversation with its full message history, subscriber details, and context.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}},{name:"reply_to_conversation",description:"Send a reply in a conversation, or add an internal note. type 'outbound' (default) emails the subscriber and requires bodyText or bodyHtml; type 'note' adds a private team-only note. Replying to a closed conversation reopens it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID to reply in."},type:{type:"string",enum:["outbound","note"],description:"Message type: outbound emails the subscriber, note is internal-only. Defaults to outbound."},subject:{type:"string",description:"Optional subject override. Defaults to the conversation subject."},bodyText:{type:"string",description:"Plain-text message body."},bodyHtml:{type:"string",description:"HTML message body."}},required:["conversationId"]}},{name:"update_conversation_status",description:"Open or close a conversation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."},status:{type:"string",enum:["open","closed"],description:"New conversation status."}},required:["conversationId","status"]}},{name:"mark_conversation_read",description:"Mark all unread inbound messages in a conversation as read.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}}];var Gz=[{name:"list_landing_pages",description:"List all landing pages for a company",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list landing pages for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"get_landing_page",description:"Get landing page details, content, metrics, and URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"create_landing_page",description:"Create a draft landing page. Provide content for an exact page, or a template for generated starter content.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the landing page in. If not provided, uses the currently selected company."},name:{type:"string",description:"Landing page name. Optional; defaults to a template-specific name."},slug:{type:"string",description:"Optional URL slug. It will be normalized and made unique within the company."},template:{type:"string",description:qJ},content:{type:"object",description:D0,additionalProperties:!0}},additionalProperties:!1}},{name:"update_landing_page",description:"Edit a landing page's name, slug, or full content. Provide at least one update field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Landing page name."},slug:{type:"string",description:"Landing page URL slug. It will be normalized and made unique within the company."},content:{type:"object",description:D0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"delete_landing_page",description:"Delete a landing page",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"publish_landing_page",description:"Publish a landing page. Optional name, slug, or content updates are saved before publishing.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before publishing."},content:{type:"object",description:D0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"unpublish_landing_page",description:"Unpublish a landing page and return it to draft status. Optional name, slug, or content updates are saved first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before unpublishing."},content:{type:"object",description:D0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"connect_landing_page_domain",description:"Connect a custom domain for published landing pages. Returns the DNS target and verification records.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Custom domain, for example pages.example.com."}},required:["domain"],additionalProperties:!1}},{name:"update_landing_page_domain_settings",description:"Update landing page domain settings. Provide domain to replace the custom domain, verify true to refresh verification, or both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Replacement custom domain."},verify:{type:"boolean",description:"Refresh domain verification after any domain update."}},additionalProperties:!1}}];var Dz=[{name:"list_products",description:"List synced products (Stripe, Shopify, WooCommerce) including any attached digital delivery file. Useful before attaching a file or building a purchase sequence for a specific product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list products for. If not provided, uses the currently selected company."},provider:{type:"string",description:"Filter by provider: stripe, shopify, woocommerce, or manual."},search:{type:"string",description:"Filter products by title."}}}},{name:"upsert_products",description:"Create or update products in the catalog (Commerce API, keyed by your productId, stored under the api provider). Use this to add products that are not synced from Stripe/Shopify/WooCommerce, then attach a deliverable file with attach_product_file and build a purchase sequence for them.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},products:{type:"array",description:"Products to create or update (max 100).",items:{type:"object",properties:{productId:{type:"string",description:"Your stable product identifier (used for upserts and order line items)."},title:{type:"string",description:"Product title."},description:{type:"string",description:"Product description."},imageUrl:{type:"string",description:"Product image URL."},url:{type:"string",description:"Product page URL."},priceCents:{type:"number",description:"Price in the smallest currency unit."},currency:{type:"string",description:"ISO currency code, e.g. USD."},inStock:{type:"boolean",description:"Whether the product is in stock."}},required:["productId","title"]}}},required:["products"]}},{name:"delete_product",description:"Delete a product previously pushed via upsert_products (Commerce API products only), identified by your productId.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Your productId used when upserting the product."}},required:["productId"]}},{name:"attach_product_file",description:"Attach a distributable file to a product, either by public URL or by uploading a local file (filePath, local MCP server only). After a purchase of the product, sequence emails can link to it with {{event.download.url}} and {{event.download.name}}.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."},url:{type:"string",description:"Public http(s) URL of the file to deliver. Provide url or filePath, not both."},filePath:{type:"string",description:"Local path of a file to upload and attach (PDF, ePub, ZIP, image, audio, video, or text, up to 100MB). Only available when the MCP server runs locally on this machine."},fileName:{type:"string",description:"Display name for the file (e.g. guide.pdf). Used as {{event.download.name}}."}},required:["productId"]}},{name:"remove_product_file",description:"Remove the attached distributable file from a product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."}},required:["productId"]}},{name:"sync_products",description:"Queue a sync of the Stripe product catalog into the products list. Requires an active Stripe integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}}];var Xz=[{name:"list_sequences",description:"List all email sequences (automations)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."}}}},{name:"get_sequence",description:"Get sequence details, editable step content, and graph topology. Each sequence.nodes item includes id, nodeType, current config, updatedAt, and updateHints with its editable/managed fields and ready-to-return expectedUpdatedAt token for update_sequence_node/update_sequence_nodes. The response also includes sequence.edges and graphRevision for safe edit_sequence_graph calls, plus sequence.emails with each email step's nodeId, linked emailId, subject, previewText, and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence",description:"Create and persist a disabled draft email sequence, follow-up series, drip campaign, nurture flow, or automation workflow. For natural-language content, provide goal and emailCount. Use explicit steps for finished caller-supplied content, exact workflows, or migrations. Configure trigger plus its relevant field, such as listId, tagName, segmentId, or eventName. Supports email and SMS steps, delays and date waits, actions that dynamically create a provider discount/code, subscriber updates, event filters, enrollment rules, sending windows, and stop conditions. The saved draft appears in list_sequences. Never call enable_sequence unless the user explicitly asks to activate it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inactivity","frequency"],description:"Trigger type: 'contact_added' (when added to a list), 'tag_added' (when tag is applied), 'segment_entered' (when a contact newly enters a saved segment), 'event_received' (when custom event fires), 'inactivity' (when subscriber hasn't performed an event for X days), 'frequency' (when subscriber performs event X times in Y days)"},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inactivity, and frequency triggers)"},propertyFilters:{type:"array",description:"Optional event property filters for event_received triggers. The sequence only starts when the triggering event's properties match ALL filters. Use a dot-path into the event properties; use [] to match inside arrays. Examples: scope a purchase sequence to one product with { path: 'lineItems[].providerProductId', operator: 'equals', value: 'prod_123' } (ecommerce.order_placed) or { path: 'productIds', operator: 'equals', value: 'prod_123' } (saas.purchase); to match any of several products use { path: 'lineItems[].providerProductId', operator: 'one_of', value: ['prod_123', 'prod_456'] }. Max 10 filters.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},emailStyle:{type:"string",enum:["visual","plain"],description:"Style for AI-generated emails: 'visual' (designed, with heroes/imagery/rich sections) or 'plain' (personal, text-first notes with a single button). Only applies to goal-based AI generation. Defaults to the company's saved preference when omitted."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:k$,stopCondition:{type:"object",description:"Optional explicit auto-stop condition. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'does_not_have_tag', value: 'trial' } when a tag is removed, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } when they leave a list, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. Use null or omit for type 'none'."}},required:["type"]},steps:{type:"array",description:"Explicit sequence steps. Omit type for email steps, use type: 'sms' for SMS, type: 'create_discount' for a dynamic discount, or type: 'update_subscriber' with nodeType: 'action_update_attributes' and config to copy trigger-event values such as {{event.plan}} into subscriber data.",items:{type:"object",properties:{type:{type:"string",enum:["email","sms","create_discount","discount","update_subscriber"],description:"Step type. Omit or use 'email' for email content. Use 'sms' to send a text message, 'create_discount' to generate a code, or 'update_subscriber' to copy trigger data into the subscriber."},nodeType:{type:"string",enum:["action_email","action_sms","action_create_discount","action_update_attributes"],description:"Internal step type. Use action_update_attributes with config for Update Subscriber steps."},config:X0,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:W1,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:G1,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:Q1,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.",properties:{label:{type:"string",description:"Builder label for the discount step."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use 'stripe' to dynamically create a Stripe coupon plus promotion code, or 'shopify' to dynamically create a Shopify Admin discount code. Defaults to 'stripe' when omitted."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional display name for each dynamically generated provider discount."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe","shopify"],description:"Legacy top-level discount provider. Prefer discount.provider. Supports 'stripe' and 'shopify'."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name","trigger"]}}];var Yz=[{name:"update_sequence",description:"Update an existing sequence. To target a specific existing step, use IDs returned by get_sequence. The emails/steps arrays edit email steps, smsSteps edits SMS steps, and subscriberUpdateSteps replaces the config of action_update_attributes steps. To insert new linear steps, use insertSteps with an afterNodeId from get_sequence; omit afterNodeId only to append to an unambiguous linear tail. For active sequences, structural changes such as insertSteps or branch require confirmStructuralChange:true after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},fromEmail:{type:"string",description:"Set the From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Set an existing reply profile. Mutually exclusive with replyTo."},enrollmentPaused:{type:"boolean",description:"Set true to stop new enrollments for an active sequence while current recipients continue. Set false to resume new enrollments. The sequence must already be active."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence. Required for insertSteps or branch when the sequence is active; not needed for content-only email edits."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. 'matching_field' is only valid for event-based sequence triggers."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},sendingWindow:k$,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses that receive a blind copy of every email this sequence sends, such as a customer support inbox (max 10). Omit to leave unchanged. Use clearBccEmails to remove them."},clearBccEmails:{type:"boolean",description:"Set true to remove the sequence BCC addresses. Do not provide this together with bccEmails."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'entered_segment', value: 'segment_123' } to stop when they enter a segment, { type: 'field_changed', value: 'plan' } to stop when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } to stop when they leave a list, or { type: 'none', value: null } to clear it.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"]},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition."}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. The branch is inserted after afterNodeId and creates an if path plus an else fallback path. Use get_sequence first to choose afterNodeId. Each branch condition should include steps, and elseSteps is required unless allowEmptyPaths is true. Conditions support tag presence/absence, lists, saved segments, events, clicked links, and field comparisons. Use activityScope for event_received and link_clicked checks.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert the branch after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails."},label:{type:"string",description:"Optional branch node label."},branches:{type:"array",description:"Conditional branches evaluated in order. An else fallback is created automatically.",items:{type:"object",properties:{id:{type:"string",description:"Optional stable branch ID. Defaults to branch-0, branch-1, etc."},label:{type:"string",description:"Display label, e.g. 'If has customer tag'."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"Condition type for this branch. has_phone (contact has a phone number) and sms_subscribed (contact opted in to SMS marketing) need no extra fields."},tagName:{type:"string",description:"Tag name for has_tag and does_not_have_tag conditions. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag and does_not_have_tag conditions."},listId:{type:"string",description:"List ID for in_list conditions."},segmentId:{type:"string",description:"Segment ID for in_segment conditions."},segmentName:{type:"string",description:"Optional display name for in_segment conditions."},eventName:{type:"string",description:"Event name for event_received conditions, such as project.invite.accepted."},linkUrl:{type:"string",description:"Optional URL substring for link_clicked conditions. Omit to match any clicked link."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"Scope for event_received and link_clicked conditions. Omit to check ever."},fieldName:{type:"string",description:"Subscriber attribute name for field conditions."},fieldValue:{type:"string",description:"Comparison value for field conditions."},steps:{type:"array",description:"Steps to create inside this branch path. Required by default so the branch is not an empty placeholder.",items:n$}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:n$},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating empty UI placeholders. Normal API/MCP use should omit this and provide branch steps plus elseSteps."}},required:["afterNodeId","branches"]},insertSteps:{type:"object",description:"Insert one or more new linear steps into an existing sequence. Use get_sequence first, then pass afterNodeId to insert after a specific node. If afterNodeId is omitted, the steps are appended only when the sequence has exactly one linear tail. Inserted email steps require subject plus blocks or html.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},steps:{type:"array",description:"New steps to insert. Supports emails, delays, create_discount actions, webhooks, and other supported sequence path node types.",items:n$}},required:["steps"]},emails:{type:"array",description:"Updated existing sequence emails. If you omit emailId/nodeId, items are matched by existing step order. This field does not create new steps; use insertSteps for insertion and include delay on inserted email steps when a timer is needed.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating imported provider HTML for a step."},blocks:{type:"array",description:Jw,items:{type:"object"}},...FW}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules, and only edits existing email steps. Use insertSteps to create new steps.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating HTML content for a step."},blocks:{type:"array",description:Jw,items:{type:"object"}},...FW}}},smsSteps:{type:"array",description:"Content updates for existing SMS steps, targeted by nodeId (an action_sms node from get_sequence.sequence.nodes). Content-only edits - use insertSteps to create new SMS steps.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_sms node ID. Required."},text:{type:"string",description:"Replacement plain-text message body. Merge tags like {{FIRST_NAME}} work. Provide text or blocks, not both."},blocks:{type:"array",items:{type:"object"},description:"Replacement SMS content blocks (text + image subset)."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable MMS image URLs. Only valid together with text."},label:{type:"string",description:"Updated display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"Updated behavior when the contact can't receive SMS."}},required:["nodeId"]}},subscriberUpdateSteps:{type:"array",description:"Full config replacements for existing Update Subscriber steps, targeted by action_update_attributes nodeId.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_update_attributes node ID."},config:X0},required:["nodeId","config"]}}},required:["sequenceId"]}},{name:"update_sequence_node",description:"Patch one existing sequence node in place. Call get_sequence first, select sequence.nodes[].id, inspect nodeType/config, and pass that node's updatedAt as expectedUpdatedAt. This supports every stored sequence node type, including delays, email/SMS content, actions, conditions, branches without topology changes, webhooks, and trigger settings. Delay example: changes:{ delay:{ days:7 } }. The update is type-aware and preserves fields you omit. It cannot change nodeType, managed linked-resource IDs, or graph topology; use edit_sequence_graph for structural work. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamp; the new delay applies when recipients reach the node in the future.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},nodeId:C$.properties.nodeId,changes:zW,expectedUpdatedAt:C$.properties.expectedUpdatedAt,confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing a node in an active sequence."}},required:["sequenceId","nodeId","changes","expectedUpdatedAt"],additionalProperties:!1}},{name:"update_sequence_nodes",description:"Atomically patch multiple existing sequence nodes. Call get_sequence first and include each node's id plus its updatedAt as expectedUpdatedAt. Every patch follows update_sequence_node's type-aware rules. Either every node update commits or none do, making this the preferred tool for changes such as replacing all 5-minute delays with 7-day delays. A node may appear only once. It cannot change node types or graph topology. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamps.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},updates:{type:"array",description:"Non-empty node patches. Each nodeId may appear only once.",items:C$},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing nodes in an active sequence."}},required:["sequenceId","updates"],additionalProperties:!1}},{name:"edit_sequence_graph",description:"Restructure an existing sequence graph using node IDs, edges, and graphRevision from get_sequence. move_node repositions one non-split step; beforeNodeId can place an A/B test or other step at the shared continuation below a branch. duplicate_node creates an independent copy and deep-copies linked email or A/B test content. delete_node safely splices a linear step; deleting a split node requires the complete replacement edges. replace_edges atomically replaces the complete topology for advanced reconnect or multi-node reorder work. Always call get_sequence immediately before this tool and pass its graphRevision. Active sequences require confirmStructuralChange:true after the user confirms live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},action:{type:"string",enum:["move_node","delete_node","duplicate_node","replace_edges"],description:"Graph operation. Use move_node for a single step reorder, duplicate_node for an independent copy, delete_node to remove a step/node, or replace_edges for an atomic reconnect/reorder of the whole topology."},graphRevision:{type:"string",description:"Exact graphRevision returned by the latest get_sequence call. The edit is rejected if the graph changed since then."},nodeId:{type:"string",description:"Existing node to move, duplicate, or delete. Required for those actions and unused by replace_edges."},afterNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately after this node. The target must have at most one outgoing path. Provide exactly one of afterNodeId or beforeNodeId."},beforeNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately before this node. All incoming paths converge through the moved/copied node, which is useful for placing a step below a branch. Provide exactly one of beforeNodeId or afterNodeId."},edges:{type:"array",description:"Complete replacement topology from get_sequence.sequence.edges. The returned edge array is already normalized for this input and can be reused directly. Required for replace_edges and when deleting a split node. Preserve each branch edge's condition.branchId. Do not include edges that reference a deleted node.",items:{type:"object",properties:{sourceNodeId:{type:"string"},targetNodeId:{type:"string"},condition:{type:"object",description:"Optional edge routing condition. Preserve condition.branchId on edges leaving logic_branch nodes."}},required:["sourceNodeId","targetNodeId"],additionalProperties:!1}},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."}},required:["sequenceId","action","graphRevision"],additionalProperties:!1}},{name:"insert_sequence_step",description:"Insert one new email or SMS step into an existing sequence. Prefer this over update_sequence.steps/emails when adding a step: it creates the step node (plus an email template for email steps) and, when delay or delayMs is provided, a logic_delay node immediately before it. For SMS steps set type:'sms' and provide 'text' (generate copy with generate_sms; check get_sms_settings first and warn the user if SMS is not enabled). Use get_sequence first, then pass afterNodeId from sequence.nodes or sequence.emails to choose the insertion point. If afterNodeId is omitted, the step is appended only when the sequence has exactly one linear tail. For active sequences, set confirmStructuralChange:true only after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},type:{type:"string",enum:["email","sms"],description:"Step type. Defaults to 'email'. Use 'sms' to insert an SMS step (requires 'text')."},afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."},name:{type:"string",description:"Optional email template and step name."},subject:{type:"string",description:"Email subject for the new step. Required for email steps; not used for SMS steps."},previewText:{type:"string",description:"Optional email preview text for the new step."},blocks:{type:"array",description:W1,items:{type:"object"}},html:{type:"string",description:"HTML content for the new step. Stored as one raw HTML block. Use this for imported provider HTML. Provide either html or blocks, not both."},senderProfileId:{type:"string",description:"Email steps only: sender profile for the new step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"Email steps only: From address for the new step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Email steps only: display name override for the new step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Email steps only: reply profile for the new step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Email steps only: Reply-To address for the new step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Email steps only: display name for a newly created reply profile. Requires replyTo."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},label:{type:"string",description:"SMS steps only: display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:G1,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:Q1},required:["sequenceId"],additionalProperties:!1}},{name:"enable_sequence",description:"Enable/activate a sequence. IMPORTANT: Only call this when the user EXPLICITLY asks to enable or activate a sequence. Never enable sequences automatically after creation - the user must review the content first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"disable_sequence",description:"Disable/freeze a sequence. This blocks new enrollments and holds current recipients until the sequence is enabled again. To only stop new enrollments while current recipients continue, use pause_sequence_enrollments.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"pause_sequence_enrollments",description:"Stop new enrollments for an active sequence while current recipients continue through the sequence. This matches the dashboard 'Stop new enrollments' control and does not freeze current recipients.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"resume_sequence_enrollments",description:"Resume new enrollments for an active sequence whose enrollment gate was paused. Use enable_sequence instead for a fully disabled/frozen sequence.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"enroll_subscribers_in_sequence",description:"Manually enroll subscribers in a sequence by email address or subscriber ID. Maximum 500 total targets per call across emails and subscriberIds. Only active subscribers are enrolled: unknown emails are returned in `notFound`, while inactive, unavailable, and already actively enrolled subscribers are counted in `skipped`. By default enrollment starts at the first step after the trigger; pass targetNodeId to start at a specific step.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to enroll subscribers in."},emails:{type:"array",items:{type:"string"},description:"Email addresses of subscribers to enroll. Combined with subscriberIds, maximum 500 total targets per call."},subscriberIds:{type:"array",items:{type:"string"},description:"Subscriber IDs to enroll. Combined with emails, maximum 500 total targets per call."},targetNodeId:{type:"string",description:"Optional node ID to start enrollment at. Use a non-trigger nodeId from get_sequence. Defaults to the first step after the trigger."}},required:["sequenceId"]}},{name:"cancel_sequence_enrollments",description:"Cancel active/waiting enrollments in one sequence. Provide sequenceId and exactly one target: subscriberId for one subscriber, or fieldValues to match stored entry event properties. For fieldValues, fieldPath is optional when the sequence has enrollmentFieldPath configured; otherwise provide a dot path such as order.id.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be cancelled."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide subscriberId or fieldValues, not both."},fieldPath:{type:"string",description:"Dot-path inside the token's stored entry event properties, such as order.id or event.id. Optional when the sequence has enrollmentFieldPath configured."},fieldValues:{type:"array",items:{type:"string"},description:"Entry field values to match. Cancels all active/waiting enrollments in the sequence whose entry field value is in this list. Provide fieldValues or subscriberId, not both."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. Field-value cancellation defaults to dryRun on the API unless explicitly false."},reason:{type:"string",description:"Optional cancellation reason stored on matched enrollment tokens."}},required:["sequenceId"],additionalProperties:!1}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}}];var Hz=[{name:"add_subscriber",description:"Add a new subscriber to your list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},attributes:{type:"object",description:"Custom attributes (name, plan, etc.)"},tags:{type:"array",items:{type:"string"},description:"Tags to apply to the subscriber"},listIds:{type:"array",items:{type:"string"},description:"List IDs to add subscriber to"},status:{type:"string",description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active."},optInMode:{type:"string",description:"Consent mode: confirmed creates active immediately when consent is verified, double_opt_in sends a confirmation email before activation, and default obeys company double opt-in settings."}},required:[]}},{name:"update_subscriber",description:"Update an existing subscriber's attributes or tags",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},attributes:{type:"object",description:"Attributes to update"},addTags:{type:"array",items:{type:"string"},description:"Tags to add"},removeTags:{type:"array",items:{type:"string"},description:"Tags to remove"}},required:[]}},{name:"remove_subscriber",description:"Unsubscribe or delete a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},hardDelete:{type:"boolean",description:"If true, permanently deletes. If false, just unsubscribes."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, notes, list memberships, sequence enrollments, email stats, and recent activity",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:lb},required:[]}},{name:"list_subscriber_notes",description:"List internal notes for a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"add_subscriber_note",description:"Add an internal note to a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},body:{type:"string",description:"Internal note body, up to 5000 characters."}},required:["body"]}},{name:"delete_subscriber_note",description:"Delete one internal subscriber note by note ID.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},noteId:{type:"string",description:"Subscriber note ID to delete."}},required:["noteId"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, or segment. If you omit limit, the tool fetches all pages and returns every match.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query (email or name)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},list:{type:"string",description:"Filter by subscriber list ID or exact list name. Prefer listId when known."},listId:{type:"string",description:"Filter by subscriber list ID."},listName:{type:"string",description:"Filter by exact subscriber list name when the list ID is not known."},segmentId:{type:"string",description:"Filter by segment ID"},status:{type:"string",description:"Filter by subscriber status: active, unsubscribed, or bounced."},limit:{type:"number",description:"Maximum results to return. If omitted, the tool returns all matches across pages."}}}}];var Jz={companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Exact recipient email address to inspect or clean up."},region:{type:"string",description:"Optional AWS SES region such as us-east-1. Omit to check every SES region currently used by the company."}},zz=[{name:"get_recipient_suppression",description:"Check whether one recipient is suppressed by Sequenzy's bounce/complaint safeguards or the regional Amazon SES account-level suppression list. This exact-address lookup never exposes other recipients from the shared SES account.",inputSchema:{type:"object",properties:Jz,required:["email"],additionalProperties:!1}},{name:"remove_recipient_suppression",description:"Remove stale bounce suppression for an exact recipient associated with the company. Clears matching Amazon SES bounce entries and Sequenzy's local bounce block, then reactivates bounced company subscribers. Complaint and unsubscribe protections are never removed.",inputSchema:{type:"object",properties:Jz,required:["email"],additionalProperties:!1}}];var Az=[{name:"list_tags",description:"List all tags in the account",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list tags for. If not provided, uses the currently selected company."}}}},{name:"create_tag",description:"Create a new tag definition. The name is normalized to lowercase with hyphens (e.g. 'VIP Customer' becomes 'vip-customer'). Color defaults to gray.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Tag name. Normalized to lowercase with hyphens."},color:{type:"string",enum:[...D1],description:"Tag color. Defaults to gray."}},required:["name"]}},{name:"update_tag",description:"Update a tag's color. System tags cannot be updated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."},color:{type:"string",enum:[...D1],description:"New tag color."}},required:["tagId","color"]}},{name:"delete_tag",description:"Permanently delete a tag and remove it from all subscribers. This cannot be undone. System tags and tags used by sequences cannot be deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."}},required:["tagId"]}},{name:"list_lists",description:"List all subscriber lists",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list lists for. If not provided, uses the currently selected company."}}}},{name:"create_list",description:"Create a new subscriber list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the list in. If not provided, uses the currently selected company."},name:{type:"string",description:"List name"},description:{type:"string",description:"List description"}},required:["name"]}},{name:"update_list",description:"Update a subscriber list's name, description, or privacy. Only the provided fields are changed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to update."},name:{type:"string",description:"New list name."},description:{type:["string","null"],description:"New list description. Pass null to clear it."},isPrivate:{type:"boolean",description:"Whether the list is private."}},required:["listId"]}},{name:"delete_list",description:"Permanently delete a subscriber list and remove all of its memberships. Subscribers themselves are kept. This cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to delete."}},required:["listId"]}},{name:"add_subscribers_to_list",description:"Bulk add existing or new subscribers to a subscriber list from an email array. Existing subscribers are added to the list without requiring a per-subscriber update call.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to add subscribers to."},emails:{type:"array",items:{type:"string"},description:"Email addresses to add to the list. Maximum 500 per call."},duplicateStrategy:{type:"string",description:"Duplicate strategy for existing subscribers: skip, merge, or overwrite. Defaults to skip."},enrollInSequences:{type:"boolean",description:"Whether newly created subscribers should enroll in matching sequences. Defaults to false."},optInMode:{type:"string",description:"Consent mode for newly created subscribers: default, confirmed, or double_opt_in. Defaults to default."}},required:["listId","emails"]}},{name:"remove_subscribers_from_list",description:"Remove subscribers from a list by email address. Maximum 500 emails per call. Subscribers stay in the account; only the list membership is removed. Returns the removed count plus a notFound array of emails that did not match a subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to remove subscribers from."},emails:{type:"array",items:{type:"string"},description:"Email addresses to remove from the list. Maximum 500 per call."}},required:["listId","emails"]}},{name:"list_segments",description:"List all segments",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list segments for. If not provided, uses the currently selected company."}}}},{name:"create_segment",description:'Create a new segment from explicit filter rules. Use `filters` plus `filterJoinOperator` for flat legacy rules, or `root` for nested AND/OR groups such as `{ "kind": "group", "joinOperator": "and", "children": [{ "kind": "filter", "field": "attribute", "operator": "gte", "value": "mrr:50" }, { "kind": "group", "joinOperator": "or", "children": [{ "kind": "filter", "field": "tag", "operator": "contains", "value": "vip" }, { "kind": "filter", "field": "event", "operator": "is_not", "value": "saas.purchase:30d" }] }] }`. Supports `event` and `segment` fields, Stripe product purchase/current/trial/date filters, and campaign-specific engagement filters.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the segment in. If not provided, uses the currently selected company."},name:{type:"string",description:"Segment name"},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:OW,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example commerce product purchase filter (value is provider:productId since product ids are provider-scoped): [{"id":"filter-1","field":"commerceProduct","operator":"is","value":"api:prod-starter-kit"}]. Example repeat-buyer filter: [{"id":"filter-1","field":"commerceProduct","operator":"at_least","value":"shopify:42:2"}]. Example trial cancellation filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:is_canceled"}]. Example trial end filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:end_at:2026-05-26"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{...qW,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"update_segment",description:"Update a segment's name and/or filter rules. Use the same `filters` plus `filterJoinOperator` or nested `root` shapes as create_segment; providing `filters` or `root` replaces the segment's existing rules.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to update."},name:{type:"string",description:"New segment name."},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:OW,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...qW,description:"Replacement nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["segmentId"]}},{name:"delete_segment",description:"Permanently delete a segment. This cannot be undone. Subscribers are not affected.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to delete."}},required:["segmentId"]}},{name:"get_segment_count",description:"Get the number of subscribers in a segment",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID"}},required:["segmentId"]}}];var Oz=[{name:"list_team_members",description:"List team members for the company, including the owner, members with their roles, and pending or expired invitations.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"invite_team_member",description:"Invite a team member by email with role admin, viewer, or restricted. Existing Sequenzy users are added to the team immediately; others receive an email invitation. Billing access (canManageBilling) can only be granted by the company owner and is not available for restricted members.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Email address of the person to invite."},role:{type:"string",enum:["admin","viewer","restricted"],description:"Team role. Admins can manage the workspace; viewers have read-only access; restricted members can open direct campaign links only."},canManageBilling:{type:"boolean",description:"Whether the member can manage billing. Only the company owner can grant billing access. Defaults to false."}},required:["email","role"]}},{name:"cancel_team_invitation",description:"Cancel a pending team invitation. Invitations that have already been accepted cannot be cancelled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},invitationId:{type:"string",description:"Invitation ID to cancel. Use list_team_members to find pending invitations."}},required:["invitationId"]}}];var qz=[{name:"list_templates",description:"List all email templates, including per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template. For net-new email content requested in natural language, use `prompt`; do not write HTML or construct blocks yourself. Use `blocks` only for finished caller-supplied Sequenzy content and `html` only for supplied or explicitly requested preserved HTML.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line. Optional with `prompt`."},previewText:{type:["string","null"],description:"Optional preview text override."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider templates; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Hw,items:{type:"object"}},prompt:{type:"string",description:"Natural-language request for Sequenzy to generate branded native template blocks."},style:{type:"string",description:"Generation style; valid only with `prompt`."},tone:{type:"string",description:"Generation tone; valid only with `prompt`."},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `html`, `blocks`, or `labels` is required, and only those update fields are accepted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider templates; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Hw,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"set_template_localization",description:"Create or replace one caller-supplied localized variant of a template. The locale must be enabled for the company and cannot be its primary locale. Provide exactly one of `html` or `blocks`.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locale:{type:"string",description:"Enabled non-primary locale code such as es, fr, or pt-BR."},subject:{type:"string",description:"Localized email subject line."},previewText:{type:["string","null"],description:"Optional localized inbox preview text."},html:{type:"string",description:"Localized email HTML. Mutually exclusive with `blocks`."},blocks:{type:"array",description:Hw,items:{type:"object"}}},required:["templateId","locale","subject"],additionalProperties:!1}},{name:"sync_template_localizations",description:"Queue AI translation for selected template locales. Omit `locales` to sync every enabled non-primary locale. This works even when automatic on-save localization is disabled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locales:{type:"array",description:"Optional enabled non-primary locale codes to sync. Omit to sync all enabled non-primary locales.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}}];var Lz=[{name:"list_transactional_emails",description:"List transactional email templates, including their API slugs and linked email IDs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Sequenzy stores it as one raw HTML block."},blocks:{type:"array",description:`${Hw} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Generated blocks include the company's branding (logo and a footer without an unsubscribe link). Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Prompt-created templates default to false; explicit HTML/blocks retain the compatibility default of true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Sequenzy stores it as one raw HTML block."},blocks:{type:"array",description:`${Jw} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Queue one transactional email using either a saved transactional email API slug (`templateId`) or direct `subject` and `html` content. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line. Required with `html` when `templateId` is omitted."},html:{type:"string",description:"Direct-send HTML body. Required with `subject` when `templateId` is omitted; the MCP server maps this to the transactional API `body` field."},templateId:{type:"string",description:"Saved transactional email API slug, for example `welcome-email`. The field name is retained for MCP compatibility and is mapped to the transactional API `slug` field."},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics/localization on single-recipient sends. Maximum length: 255 characters."}},required:["to"],additionalProperties:!1}}];var Uz=[{name:"list_webhooks",description:"List outbound webhook endpoints and their subscribed event types.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_webhook",description:"Create an outbound webhook endpoint. IMPORTANT: the response includes a signingSecret that is returned only once - show it to the user immediately so they can store it and verify webhook signatures. If events is omitted, a default set of event types is subscribed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Webhook endpoint name."},url:{type:"string",description:"HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...X1]},description:"Event types to subscribe to. If omitted, a default set is used."}},required:["name","url"]}},{name:"update_webhook",description:"Update an outbound webhook endpoint's name, URL, subscribed events, or status (enabled/disabled). Providing events replaces the existing event list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},name:{type:"string",description:"New webhook endpoint name."},url:{type:"string",description:"New HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...X1]},description:"Replacement event type subscriptions."},status:{type:"string",enum:["enabled","disabled"],description:"Enable or disable deliveries to this endpoint."}},required:["webhookId"]}},{name:"delete_webhook",description:"Permanently delete an outbound webhook endpoint along with its delivery history. This cannot be undone. To keep the endpoint but stop deliveries, use update_webhook with status disabled instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to delete."}},required:["webhookId"]}},{name:"test_webhook",description:"Send a test event to an outbound webhook endpoint to verify it is reachable and signatures can be validated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to test."}},required:["webhookId"]}},{name:"list_webhook_deliveries",description:"List recent delivery attempts for an outbound webhook endpoint, including status and response codes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},limit:{type:"number",description:"Maximum number of deliveries to return, from 1 to 100. Defaults to 20."}},required:["webhookId"]}},{name:"replay_webhook_delivery",description:"Replay a previous webhook delivery, re-sending the same event payload to the endpoint.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},deliveryId:{type:"string",description:"Delivery ID to replay. Use list_webhook_deliveries to find delivery IDs."}},required:["webhookId","deliveryId"]}}];var Bz=[...rJ,...Hz,...zz,...Dz,...Az,...aJ,...qz,...tJ,...bz,...$z,...Gz,...Wz,...Xz,...Yz,...Lz,...sJ,...Oz,...Qz,...Uz,...eJ,...wz];async function Pz(b,w){let $;switch(b){case"get_account":{let W=await A("GET","/api/v1/account"),Q=Ew();$={...W,selectedCompanyId:Q??W.currentCompanyId};break}case"select_company":{let W=w.companyId,Q=await A("GET","/api/v1/account"),G=Q.companies?.find((D)=>D.id===W);if(!G)throw Error(`Company not found. Available companies: ${Q.companies?.map((D)=>`${D.name} (${D.id})`).join(", ")??"none"}`);t$(W),$={success:!0,message:`Switched to company: ${G.name}`,companyId:G.id,companyName:G.name};break}case"get_app_urls":{let W=await m$(w);$={...Yw({companyId:W,campaignId:P(w,"campaignId"),landingPageId:P(w,"landingPageId"),sequenceId:P(w,"sequenceId"),emailId:P(w,"emailId")??P(w,"templateId"),transactionalId:P(w,"transactionalId"),emailSendId:P(w,"emailSendId"),domainId:P(w,"domainId"),status:P(w,"status"),settingsTab:P(w,"settingsTab")}),...W===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let W=await A("POST","/api/v1/companies",{name:w.name,domain:w.domain});if(!W.success)throw Error("Failed to create company");let Q=W.company.id,G=6,D=0,X=W.company.status;while(X==="processing"&&D<G){await new Promise((J)=>setTimeout(J,20000)),D++;let H=await A("GET",`/api/v1/companies/${Q}`);if(H.success)X=H.company.status}t$(Q);let Y=await A("GET",`/api/v1/companies/${Q}`);$={success:!0,company:Y.company,message:X==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${Y.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let W=w.companyId;$=await A("GET",`/api/v1/companies/${W}`);break}case"update_company":{let W=await cJ("update_company",w),Q=MJ(w);$=await A("PATCH",`/api/v1/companies/${W}`,Q);break}case"get_sync_rules":{let W=w.companyId;$=await A("GET","/api/v1/sync-rules",void 0,W);break}case"update_sync_rules":{let W=w.companyId;if(w.syncRules!==null&&!Array.isArray(w.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");$=await A("PUT","/api/v1/sync-rules",{syncRules:w.syncRules},W);break}case"get_shopify_automation_settings":{let W=w.companyId;$=await A("GET","/api/v1/shopify/automation-settings",void 0,W);break}case"update_shopify_automation_settings":{let W=w.companyId,Q={};if(w.browseAbandonment!==void 0)Q.browseAbandonment=w.browseAbandonment;if(w.priceDrop!==void 0)Q.priceDrop=w.priceDrop;if(Object.keys(Q).length===0)throw Error("Provide `browseAbandonment` and/or `priceDrop` when calling `update_shopify_automation_settings`.");$=await A("PUT","/api/v1/shopify/automation-settings",Q,W);break}case"create_api_key":{let W=w.companyId,Q={};if(typeof w.name==="string")Q.name=w.name;if(typeof w.preset==="string")Q.preset=w.preset;if(Array.isArray(w.scopes))Q.scopes=w.scopes;$=await A("POST","/api/v1/api-keys",Q,W);break}case"list_websites":{let W=w.companyId;$=await A("GET","/api/v1/websites",void 0,W);break}case"add_sending_domain":case"add_website":{let W=w.companyId;$=await A("POST","/api/v1/websites",{domain:w.domain},W);break}case"check_website":{let W=w.companyId;$=await A("GET",`/api/v1/websites/${encodeURIComponent(String(w.domain))}`,void 0,W);break}case"verify_sending_domain":{let W=w.companyId;$=await A("POST",`/api/v1/websites/${encodeURIComponent(String(w.domain))}/verify`,void 0,W);break}case"get_integration_guide":$=await A("POST","/api/v1/integration-guide",w);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Fz(b,w){let $;switch(b){case"generate_email":{let W=w.companyId;$=await A("POST","/api/v1/generate/email",w,W);break}case"generate_subject_lines":{let W=w.companyId;$=await A("POST","/api/v1/generate/subjects",w,W);break}case"generate_sms":{let W=w.companyId;$=await A("POST","/api/v1/generate/sms",w,W);break}case"get_sms_settings":{let W=w.companyId;$=await A("GET","/api/v1/sms/settings",void 0,W);break}case"send_test_sms":{let W=w.companyId,Q={to:Z("send_test_sms",w,"to")};for(let G of["text","imageUrls","blocks"])if(w[G]!==void 0)Q[G]=w[G];$=await A("POST","/api/v1/sms/test",Q,W);break}case"submit_feedback":{let W=w.companyId,Q={message:Z("submit_feedback",w,"message"),source:"mcp"};for(let G of["category","context"])if(w[G]!==void 0)Q[G]=w[G];$=await A("POST","/api/v1/feedback",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Kz(b,w){let $;switch(b){case"list_transactional_emails":{let W=w.companyId;$=await A("GET","/api/v1/transactional",void 0,W);break}case"get_transactional_email":{let W=w.companyId;$=await A("GET",`/api/v1/transactional/${w.idOrSlug}`,void 0,W);break}case"create_transactional_email":{let W=w.companyId,Q=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),G=Object.keys(w).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);CJ(w);let D=Object.fromEntries(Object.entries(w).filter(([X])=>X!=="companyId"));$=await A("POST","/api/v1/transactional",D,W);break}case"update_transactional_email":{let W=w.companyId,Q=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),G=Object.keys(w).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);if(_b("update_transactional_email",w),w.name===void 0&&w.enabled===void 0&&w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let D=Object.fromEntries(Object.entries(w).filter(([X])=>X!=="companyId"&&X!=="idOrSlug"));$=await A("PATCH",`/api/v1/transactional/${w.idOrSlug}`,D,W);break}case"send_email":{let W=w.companyId,Q=Z("send_email",w,"to"),G=w.templateId===void 0?void 0:Z("send_email",w,"templateId"),D=w.subject===void 0?void 0:Z("send_email",w,"subject"),X=w.html===void 0?void 0:Z("send_email",w,"html");if(G!==void 0&&(D!==void 0||X!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(G===void 0&&(D===void 0||X===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");let Y=Object.fromEntries(Object.entries({to:Q,slug:G,subject:D,body:X,variables:w.variables,subscriberExternalId:w.subscriberExternalId}).filter(([,H])=>H!==void 0));$=await A("POST","/api/v1/transactional/send",Y,W);break}case"get_stats":{let W=w.companyId,Q=w.period??"7d",G=new URLSearchParams({period:String(Q)});if(w.includeMachineEngagement===!0)G.set("includeMachineEngagement","true");$=await A("GET",`/api/v1/metrics?${G.toString()}`,void 0,W);break}case"get_campaign_stats":{let W=w.companyId,Q=new URLSearchParams;if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let G=Q.toString();$=await A("GET",`/api/v1/metrics/campaigns/${w.campaignId}${G?`?${G}`:""}`,void 0,W);break}case"get_sequence_stats":{let W=w.companyId,Q=new URLSearchParams;if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let G=Q.toString();$=await A("GET",`/api/v1/metrics/sequences/${w.sequenceId}${G?`?${G}`:""}`,void 0,W);break}case"list_campaign_events":{let W=w.companyId,Q=Z("list_campaign_events",w,"campaignId"),D=IW("list_campaign_events",w).toString();$=await A("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(Q)}/events${D?`?${D}`:""}`,void 0,W);break}case"list_sequence_events":{let W=w.companyId,Q=Z("list_sequence_events",w,"sequenceId"),D=IW("list_sequence_events",w).toString();$=await A("GET",`/api/v1/metrics/sequences/${encodeURIComponent(Q)}/events${D?`?${D}`:""}`,void 0,W);break}case"get_subscriber_activity":{let W=w.companyId,Q=Aw("get_subscriber_activity",w),G=await Y0(Q,W,{includeMachineEngagement:w.includeMachineEngagement===!0});$={success:G.success,email:G.subscriber.email,emailStats:G.subscriber.emailStats??null,activity:G.subscriber.activity??[],sequenceEnrollments:G.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Mz(b,w){let $;switch(b){case"list_tags":{let W=w.companyId;$=await A("GET","/api/v1/tags",void 0,W);break}case"create_tag":{let W=w.companyId,Q=Z("create_tag",w,"name"),G=Ub("create_tag",w,"color",D1);$=await A("POST","/api/v1/tags",{name:Q,...G!==void 0&&{color:G}},W);break}case"update_tag":{let W=w.companyId,Q=Z("update_tag",w,"tagId"),G=H0("update_tag",w,"color",D1);$=await A("PATCH",`/api/v1/tags/${encodeURIComponent(Q)}`,{color:G},W);break}case"delete_tag":{let W=w.companyId,Q=Z("delete_tag",w,"tagId");$=await A("DELETE",`/api/v1/tags/${encodeURIComponent(Q)}`,void 0,W);break}case"list_lists":{let W=w.companyId;$=await A("GET","/api/v1/lists",void 0,W);break}case"create_list":{let W=w.companyId;$=await A("POST","/api/v1/lists",w,W);break}case"update_list":{let W=w.companyId,Q=Z("update_list",w,"listId");if(w.name===void 0&&w.description===void 0&&w.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(w.name!==void 0&&P(w,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(w.description!==void 0&&w.description!==null&&typeof w.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(w.isPrivate!==void 0&&typeof w.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");$=await A("PATCH",`/api/v1/lists/${encodeURIComponent(Q)}`,{...w.name!==void 0&&{name:P(w,"name")},...w.description!==void 0&&{description:w.description},...w.isPrivate!==void 0&&{isPrivate:w.isPrivate}},W);break}case"delete_list":{let W=w.companyId,Q=Z("delete_list",w,"listId");$=await A("DELETE",`/api/v1/lists/${encodeURIComponent(Q)}`,void 0,W);break}case"add_subscribers_to_list":{let W=w.companyId,Q=Z("add_subscribers_to_list",w,"listId"),G=jW("add_subscribers_to_list",w),D=Ub("add_subscribers_to_list",w,"duplicateStrategy",["skip","merge","overwrite"])??"skip",X=Ub("add_subscribers_to_list",w,"optInMode",["default","confirmed","double_opt_in"])??"default";$=await A("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers`,{emails:G,duplicateStrategy:D,enrollInSequences:w.enrollInSequences===!0,optInMode:X},W);break}case"remove_subscribers_from_list":{let W=w.companyId,Q=Z("remove_subscribers_from_list",w,"listId"),G=jW("remove_subscribers_from_list",w);$=await A("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers/remove`,{emails:G},W);break}case"list_segments":{let W=w.companyId;$=await A("GET","/api/v1/segments",void 0,W);break}case"create_segment":{FJ(w);let W=w.companyId;$=await A("POST","/api/v1/segments",{...w,...w.filters!==void 0?{filters:u$(w.filters)}:{},...w.root!==void 0?{root:x$(w.root)}:{}},W);break}case"update_segment":{KJ(w);let W=w.companyId,Q=Z("update_segment",w,"segmentId"),G=P(w,"name"),D=Ub("update_segment",w,"filterJoinOperator",["and","or"]);$=await A("PATCH",`/api/v1/segments/${encodeURIComponent(Q)}`,{...G!==void 0&&{name:G},...D!==void 0&&{filterJoinOperator:D},...w.filters!==void 0?{filters:u$(w.filters)}:{},...w.root!==void 0?{root:x$(w.root)}:{}},W);break}case"delete_segment":{let W=w.companyId,Q=Z("delete_segment",w,"segmentId");$=await A("DELETE",`/api/v1/segments/${encodeURIComponent(Q)}`,void 0,W);break}case"get_segment_count":{let W=w.companyId;$=await A("GET",`/api/v1/segments/${w.segmentId}/count`,void 0,W);break}case"list_audience_syncs":{let W=w.companyId;$=await A("GET","/api/v1/audience-syncs",void 0,W);break}case"list_ad_accounts":{let W=w.companyId;$=await A("GET","/api/v1/ad-accounts",void 0,W);break}case"create_audience_sync":{let W=w.companyId,Q=P(w,"segmentId"),G=P(w,"predefinedSegmentId");if(Q&&G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!Q&&!G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");$=await A("POST","/api/v1/audience-syncs",{segmentId:Q,predefinedSegmentId:G,adAccountId:Z("create_audience_sync",w,"adAccountId"),audienceName:Z("create_audience_sync",w,"audienceName"),...w.frequency!==void 0?{frequency:w.frequency}:{}},W);break}case"update_audience_sync":{let W=w.companyId,Q=Z("update_audience_sync",w,"syncId");$=await A("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,{...w.frequency!==void 0?{frequency:w.frequency}:{},...w.isActive!==void 0?{isActive:w.isActive}:{}},W);break}case"delete_audience_sync":{let W=w.companyId,Q=Z("delete_audience_sync",w,"syncId");$=await A("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,void 0,W);break}case"sync_audience_now":{let W=w.companyId,Q=Z("sync_audience_now",w,"syncId");$=await A("POST",`/api/v1/audience-syncs/${encodeURIComponent(Q)}/sync`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Iz(b,w){let $;switch(b){case"list_templates":{let W=w.companyId,Q=new URLSearchParams,G=P(w,"label");if(G)Q.set("label",G);$=await A("GET",`/api/v1/templates${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_template":{let W=w.companyId;$=await A("GET",`/api/v1/templates/${w.templateId}`,void 0,W);break}case"create_template":{let W=w.companyId;RJ(w);let Q=Object.fromEntries(Object.entries(w).filter(([G])=>G!=="companyId"));$=await A("POST","/api/v1/templates",Q,W);break}case"update_template":{let W=w.companyId,Q=new Set(["companyId","templateId","name","subject","html","blocks","labels"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);if(_b("update_template",w),Y1("update_template",w),w.name===void 0&&w.subject===void 0&&w.html===void 0&&w.blocks===void 0&&w.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, `blocks`, or `labels` when calling `update_template`.");$=await A("PUT",`/api/v1/templates/${w.templateId}`,w,W);break}case"set_template_localization":{let W=w.companyId,Q=Z("set_template_localization",w,"templateId"),G=Z("set_template_localization",w,"locale"),D=Z("set_template_localization",w,"subject"),X=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),Y=Object.keys(w).filter((J)=>!X.has(J));if(Y.length>0)throw Error(`\`set_template_localization\` received unsupported field${Y.length===1?"":"s"}: ${Y.map((J)=>`\`${J}\``).join(", ")}.`);_b("set_template_localization",w,{requireContent:!0});let H={subject:D};if(w.previewText!==void 0)H.previewText=w.previewText;if(w.html!==void 0)H.html=w.html;if(w.blocks!==void 0)H.blocks=w.blocks;$=await A("PUT",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/${encodeURIComponent(G)}`,H,W);break}case"sync_template_localizations":{let W=w.companyId,Q=Z("sync_template_localizations",w,"templateId"),G=new Set(["companyId","templateId","locales"]),D=Object.keys(w).filter((Y)=>!G.has(Y));if(D.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${D.length===1?"":"s"}: ${D.map((Y)=>`\`${Y}\``).join(", ")}.`);let X;if(w.locales!==void 0){if(!Array.isArray(w.locales)||w.locales.length===0||w.locales.some((Y)=>typeof Y!=="string"||Y.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");X=w.locales.map((Y)=>Y.trim())}$=await A("POST",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/sync`,X===void 0?{}:{locales:X},W);break}case"delete_template":{let W=w.companyId;$=await A("DELETE",`/api/v1/templates/${w.templateId}`,void 0,W);break}case"list_ab_tests":{let W=w.companyId,Q=new URLSearchParams,G=P(w,"sequenceId");if(G)Q.set("sequenceId",G);$=await A("GET",`/api/v1/ab-tests${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_ab_test":{let W=w.companyId;$=await A("GET",`/api/v1/ab-tests/${w.abTestId}`,void 0,W);break}case"get_ab_test_stats":{let W=w.companyId,Q=new URLSearchParams,G=P(w,"period"),D=P(w,"start"),X=P(w,"end");if(G)Q.set("period",G);if(D)Q.set("start",D);if(X)Q.set("end",X);if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");$=await A("GET",`/api/v1/ab-tests/${w.abTestId}/stats${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"restart_ab_test":{let W=w.companyId,Q=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),G=Object.keys(w).filter((H)=>!Q.has(H));if(G.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${G.length===1?"":"s"}: ${G.map((H)=>`\`${H}\``).join(", ")}.`);let D=P(w,"testType");if(D!==void 0&&D!=="subject"&&D!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let X=w.winnerThreshold===void 0?void 0:Number(w.winnerThreshold);if(X!==void 0&&(!Number.isInteger(X)||X<10||X>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let Y=w.variantCount===void 0?void 0:Number(w.variantCount);if(Y!==void 0&&(!Number.isInteger(Y)||Y<2||Y>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");$=await A("POST",`/api/v1/ab-tests/${w.abTestId}/restart`,{sourceVariantId:P(w,"sourceVariantId"),testType:D,winnerThreshold:X,variantCount:Y},W);break}case"update_ab_test_variant":{let W=w.companyId,Q=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);if(_b("update_ab_test_variant",w),w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");$=await A("PATCH",`/api/v1/ab-tests/${w.abTestId}/variants/${w.variantId}`,w,W);break}case"create_ab_test":{let W=w.companyId,Q=Z("create_ab_test",w,"campaignId"),G=P(w,"name"),D=zw("create_ab_test",w,"testPercentage",5,50),X=zw("create_ab_test",w,"testDurationMinutes",15,1440),Y=Ub("create_ab_test",w,"winnerCriteria",["open_rate","click_rate"]);if(w.variants!==void 0){if(!Array.isArray(w.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");w.variants.forEach((H,J)=>{if(!y(H)||typeof H.subject!=="string"||H.subject.trim()==="")throw Error(`\`variants\` item ${J+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(H.blocks!==void 0&&!Array.isArray(H.blocks))throw Error(`\`variants\` item ${J+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}$=await A("POST","/api/v1/ab-tests",{campaignId:Q,...G!==void 0&&{name:G},...D!==void 0&&{testPercentage:D},...X!==void 0&&{testDurationMinutes:X},...Y!==void 0&&{winnerCriteria:Y},...w.variants!==void 0&&{variants:w.variants}},W);break}case"add_ab_test_variant":{let W=w.companyId,Q=Z("add_ab_test_variant",w,"abTestId"),G=Z("add_ab_test_variant",w,"subject"),D=P(w,"previewText");if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");$=await A("POST",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants`,{subject:G,...D!==void 0&&{previewText:D},...w.blocks!==void 0&&{blocks:w.blocks}},W);break}case"delete_ab_test_variant":{let W=w.companyId,Q=Z("delete_ab_test_variant",w,"abTestId"),G=Z("delete_ab_test_variant",w,"variantId");$=await A("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants/${encodeURIComponent(G)}`,void 0,W);break}case"delete_ab_test":{let W=w.companyId,Q=Z("delete_ab_test",w,"abTestId");$=await A("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}`,void 0,W);break}case"list_campaigns":{let W=w.companyId,Q=new URLSearchParams;if(w.status)Q.set("status",String(w.status));let G=P(w,"label");if(G)Q.set("label",G);$=await A("GET",`/api/v1/campaigns?${Q}`,void 0,W);break}case"get_campaign":{let W=w.companyId;$=await A("GET",`/api/v1/campaigns/${w.campaignId}`,void 0,W);break}case"get_email_send":{let W=w.companyId;$=await A("GET",`/api/v1/email-sends/${encodeURIComponent(String(w.emailSendId))}`,void 0,W);break}case"create_campaign":{let W=w.companyId;if(SJ(w),w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_campaign`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_campaign`.");let Q=Object.fromEntries(Object.entries(w).filter(([G])=>G!=="companyId"));$=await A("POST","/api/v1/campaigns",Q,W);break}case"update_campaign":{let W=w.companyId,Q=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","ccEmails","bccEmails","campaignData","computedLists","labels"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, and label update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);if(_b("update_campaign",w),Y1("update_campaign",w),w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_campaign`.");if(w.name===void 0&&w.subject===void 0&&w.trackingCode===void 0&&w.html===void 0&&w.blocks===void 0&&w.fromEmail===void 0&&w.senderProfileId===void 0&&w.replyTo===void 0&&w.replyProfileId===void 0&&w.ccEmails===void 0&&w.bccEmails===void 0&&w.campaignData===void 0&&w.computedLists===void 0&&w.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, or label field when calling `update_campaign`.");$=await A("PUT",`/api/v1/campaigns/${w.campaignId}`,w,W);break}case"schedule_campaign":{let W=w.companyId,Q=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);vJ(w),$=await A("POST",`/api/v1/campaigns/${w.campaignId}/schedule`,{scheduledAt:w.scheduledAt,...w.targetLists!==void 0&&{targetLists:w.targetLists},...w.sendTimeOptimization!==void 0&&{sendTimeOptimization:w.sendTimeOptimization},...w.spreadOverHours!==void 0&&{spreadOverHours:w.spreadOverHours},...w.recurringInterval!==void 0&&{recurringInterval:w.recurringInterval}},W);break}case"send_test_email":{let W=w.companyId;$=await A("POST",`/api/v1/campaigns/${w.campaignId}/test`,{to:w.to},W);break}case"cancel_campaign":{let W=w.companyId,Q=Z("cancel_campaign",w,"campaignId");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/cancel`,void 0,W);break}case"pause_campaign":{let W=w.companyId,Q=Z("pause_campaign",w,"campaignId");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/pause`,void 0,W);break}case"resume_campaign":{let W=w.companyId,Q=Z("resume_campaign",w,"campaignId"),G=zw("resume_campaign",w,"spreadOverHours",1,72);$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resume`,{...G!==void 0&&{spreadOverHours:G}},W);break}case"delete_campaign":{let W=w.companyId,Q=Z("delete_campaign",w,"campaignId");$=await A("DELETE",`/api/v1/campaigns/${encodeURIComponent(Q)}`,void 0,W);break}case"duplicate_campaign":{let W=w.companyId,Q=Z("duplicate_campaign",w,"campaignId"),G=Ub("duplicate_campaign",w,"mode",["campaign","ab_test","variant"]),D=P(w,"variantId");if(G==="variant"&&D===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/duplicate`,{...G!==void 0&&{mode:G},...D!==void 0&&{variantId:D}},W);break}case"resend_campaign_to_non_openers":{let W=w.companyId,Q=Z("resend_campaign_to_non_openers",w,"campaignId");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resend-to-non-openers`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Zz(b,w){let $;switch(b){case"list_forms":{let W=w.companyId;$=await A("GET","/api/v1/forms",void 0,W);break}case"create_form":{let W=w.companyId,Q=Z("create_form",w,"name"),G=Array.isArray(w.listIds)?w.listIds.filter((Y)=>typeof Y==="string").map((Y)=>Y.trim()).filter(Boolean):[];if(G.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let D=Ub("create_form",w,"duplicateStrategy",["skip","merge","overwrite"]),X={name:Q,listIds:G};for(let Y of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName"])if(w[Y]!==void 0)X[Y]=w[Y];if(D!==void 0)X.duplicateStrategy=D;$=await A("POST","/api/v1/forms",X,W);break}case"get_form_embed":{let W=w.companyId,Q=Z("get_form_embed",w,"formId");$=await A("GET",`/api/v1/forms/embed/${encodeURIComponent(Q)}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function i$(b,w,$,W,Q){let G=b[w];if(G===void 0)return;if(typeof G!=="number"||!Number.isFinite(G)||G<$||G>W||Q&&!Number.isInteger(G))throw Error(`\`${w}\` must be a ${Q?"integer":"number"} between ${$} and ${W} when calling \`upload_image_asset\`.`);return G}async function jz(b,w){if(b!=="upload_image_asset")return{handled:!1,result:void 0};let $=P(w,"filePath"),W=P(w,"imageBase64");if($===void 0===(W===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let Q=P(w,"filename");if(W!==void 0&&Q===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let G=i$(w,"sourceWidth",1,20000,!0),D=i$(w,"sourceHeight",1,20000,!0);if(G===void 0!==(D===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let X=i$(w,"displayWidthPercent",1,100,!1)??100,Y=i$(w,"cropHeight",1,2000,!0),H=P(w,"objectFit");if(H!==void 0&&H!=="cover"&&H!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(H!==void 0&&Y===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let J=P(w,"align");if(J!==void 0&&!["left","center","right"].includes(J))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let z=typeof w.altText==="string"?w.altText.trim():void 0;if(z!==void 0&&z.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let O=await pJ({companyId:P(w,"companyId"),filePath:$,imageBase64:W,filename:Q,contentType:P(w,"contentType"),altText:z,sourceWidth:G,sourceHeight:D}),q={type:"image",src:O.url,alt:O.altText??"",width:X,widthType:"percent",...Y!==void 0&&{height:Y,objectFit:H??"cover"},...J!==void 0&&{align:J}};return{handled:!0,result:{success:!0,asset:O,imageBlock:q,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function Vz(b,w){let $;switch(b){case"list_landing_pages":{let W=w.companyId;$=await A("GET","/api/v1/landing-pages",void 0,W);break}case"get_landing_page":{let W=w.companyId;$=await A("GET",`/api/v1/landing-pages/${w.landingPageId}`,void 0,W);break}case"create_landing_page":{let W=w.companyId,Q=new Set(["companyId","name","slug","template","content"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);$=await A("POST","/api/v1/landing-pages",{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.template!==void 0&&{template:w.template},...w.content!==void 0&&{content:w.content}},W);break}case"update_landing_page":{let W=w.companyId,Q=c$("update_landing_page",w,{requireUpdate:!0});$=await A("PUT",`/api/v1/landing-pages/${w.landingPageId}`,Q,W);break}case"publish_landing_page":{let W=w.companyId,Q=c$("publish_landing_page",w,{requireUpdate:!1});$=await A("POST",`/api/v1/landing-pages/${w.landingPageId}/publish`,Q,W);break}case"unpublish_landing_page":{let W=w.companyId,Q=c$("unpublish_landing_page",w,{requireUpdate:!1});$=await A("POST",`/api/v1/landing-pages/${w.landingPageId}/unpublish`,Q,W);break}case"delete_landing_page":{let W=w.companyId;$=await A("DELETE",`/api/v1/landing-pages/${w.landingPageId}`,void 0,W);break}case"connect_landing_page_domain":{let W=w.companyId;$=await A("POST","/api/v1/landing-pages/domain",{domain:w.domain},W);break}case"update_landing_page_domain_settings":{let W=w.companyId,Q=kJ(w);$=await A("PUT","/api/v1/landing-pages/domain",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Nz(b,w){let $;switch(b){case"list_products":{let W=w.companyId,Q=new URLSearchParams;if(typeof w.provider==="string"&&w.provider.trim())Q.set("provider",w.provider.trim());if(typeof w.search==="string"&&w.search.trim())Q.set("search",w.search.trim());let G=Q.size>0?`?${Q.toString()}`:"";$=await A("GET",`/api/v1/products${G}`,void 0,W);break}case"upsert_products":{let W=w.companyId;if(!Array.isArray(w.products)||w.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");$=await A("POST","/api/v1/products",{products:w.products},W);break}case"delete_product":{let W=w.companyId,Q=Z("delete_product",w,"productId");$=await A("DELETE",`/api/v1/products/${encodeURIComponent(Q)}`,void 0,W);break}case"attach_product_file":{let W=w.companyId,Q=Z("attach_product_file",w,"productId"),G=P(w,"url"),D=P(w,"filePath");if(G===void 0===(D===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let X;if(D!==void 0){let Y=await fJ(D,W);X={url:Y.url,source:"upload",fileName:P(w,"fileName")??Y.fileName,fileSizeBytes:Y.fileSizeBytes,mimeType:Y.mimeType}}else{X={url:G};let Y=P(w,"fileName");if(Y)X.fileName=Y}$=await A("PUT",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,X,W);break}case"remove_product_file":{let W=w.companyId,Q=Z("remove_product_file",w,"productId");$=await A("DELETE",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,void 0,W);break}case"sync_products":{let W=w.companyId;$=await A("POST","/api/v1/products/sync",void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var Tz=80;function ZM(b){let w=b.trim().replace(/\s+/g," ");if(w.length<=Tz)return w;return`${w.slice(0,Tz-3).trimEnd()}...`}async function EW(b,w){let $;switch(b){case"generate_sequence":{let W=Z("generate_sequence",w,"goal"),Q=typeof w.name==="string"&&w.name.trim().length>0?w.name.trim():void 0,D=(await EW("create_sequence",{...w,goal:W,name:Q??ZM(W),trigger:"contact_added",durationDays:w.durationDays??14})).result;return{handled:!0,result:typeof D==="object"&&D!==null?{...D,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:D}}case"list_sequences":{let W=w.companyId;$=await A("GET","/api/v1/sequences",void 0,W);break}case"get_sequence":{let W=w.companyId;$=await A("GET",`/api/v1/sequences/${w.sequenceId}`,void 0,W);break}case"create_sequence":{let W=w.companyId;if(w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_sequence`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_sequence`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_sequence`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_sequence`.");let Q=Array.isArray(w.steps)&&w.steps.length>0,G=await A("POST","/api/v1/sequences",w,W);if(!G.success){$=G;break}let D=G.sequence.id;if(Q){let z=await A("GET",`/api/v1/sequences/${D}`,void 0,W);if(z.success)$={...G,success:!0,sequence:z.sequence,message:`Sequence "${z.sequence.name}" created with explicit steps. Review it before enabling.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=z;break}let X=7,Y=0,H="pending";while(H!=="complete"&&Y<X){let z=await A("GET",`/api/v1/sequences/${D}`,void 0,W);if(z.success)H=z.sequence.enrichmentStatus;if(Y++,H!=="complete"&&Y<X)await new Promise((O)=>setTimeout(O,20000))}let J=await A("GET",`/api/v1/sequences/${D}`,void 0,W);if(J.success)$={...G,success:!0,sequence:J.sequence,message:J.sequence.enrichmentStatus==="complete"?`Sequence "${J.sequence.name}" created with ${J.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${J.sequence.name}" created. Email enrichment is still in progress (${J.sequence.enrichedCount}/${J.sequence.emailCount} emails generated). You can check status with get_sequence.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=J;break}case"update_sequence":{let W=w.companyId,Q=ZJ(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"update_sequence_node":{let W=w.companyId,Q=Z("update_sequence_node",w,"sequenceId"),G=VJ(w);$=await A("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"update_sequence_nodes":{let W=w.companyId,Q=Z("update_sequence_nodes",w,"sequenceId"),G=NJ(w);$=await A("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"edit_sequence_graph":{let W=w.companyId,Q=TJ(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"insert_sequence_step":{let W=w.companyId,Q=EJ(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"enable_sequence":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/enable`,void 0,W);break}case"disable_sequence":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/disable`,void 0,W);break}case"pause_sequence_enrollments":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/pause-enrollments`,void 0,W);break}case"resume_sequence_enrollments":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/resume-enrollments`,void 0,W);break}case"enroll_subscribers_in_sequence":{let W=w.companyId,Q=Z("enroll_subscribers_in_sequence",w,"sequenceId"),G=hJ(w);$=await A("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/enroll`,G,W);break}case"cancel_sequence_enrollments":{let W=w.companyId,Q=_J(w);$=await A("POST",`/api/v1/sequences/${w.sequenceId}/enrollments/cancel`,Q,W);break}case"delete_sequence":{let W=w.companyId;$=await A("DELETE",`/api/v1/sequences/${w.sequenceId}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Ez(b,w){let $;switch(b){case"add_subscriber":{let W=w.companyId,Q=Aw("add_subscriber",w);$=await A("POST","/api/v1/subscribers",{...Q,customAttributes:w.attributes,tags:w.tags,lists:w.listIds,...w.status!==void 0&&{status:w.status},...w.optInMode!==void 0&&{optInMode:w.optInMode}},W);break}case"update_subscriber":{let W=w.companyId,Q=Aw("update_subscriber",w),G=await Y0(Q,W),D=Array.isArray(G.subscriber.tags)?G.subscriber.tags.filter((z)=>typeof z==="string"):[],X=Array.isArray(w.addTags)?w.addTags.filter((z)=>typeof z==="string"&&z.trim()!=="").map(KW):[],Y=new Set(Array.isArray(w.removeTags)?w.removeTags.filter((z)=>typeof z==="string"&&z.trim()!=="").map(KW):[]),H=D.filter((z)=>!Y.has(z));for(let z of X)if(!H.includes(z))H.push(z);let J={};if(Q.email&&Q.externalId)J.externalId=Q.externalId;if(y(w.attributes))J.customAttributes={...y(G.subscriber.customAttributes)?G.subscriber.customAttributes:{},...w.attributes};if(w.addTags||w.removeTags)J.tags=H;$=await A("PATCH",g$(Q),J,W);break}case"remove_subscriber":{let W=w.companyId,Q=Aw("remove_subscriber",w),G=g$(Q);if(w.hardDelete===!0)$=await A("DELETE",G,void 0,W);else $=await A("PATCH",G,{status:"unsubscribed"},W);break}case"get_subscriber":{let W=w.companyId,Q=Aw("get_subscriber",w);$=await Y0(Q,W,{includeMachineEngagement:w.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let W=w.companyId,Q=Aw("list_subscriber_notes",w);$=await A("GET",MW(Q),void 0,W);break}case"add_subscriber_note":{let W=w.companyId,Q=Aw("add_subscriber_note",w),G=typeof w.body==="string"?w.body.trim():void 0;if(!G)throw Error("`body` is required when calling `add_subscriber_note`.");if(G.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");$=await A("POST",MW(Q),{body:G},W);break}case"delete_subscriber_note":{let W=w.companyId,Q=typeof w.noteId==="string"?w.noteId.trim():"";if(!Q)throw Error("`noteId` is required when calling `delete_subscriber_note`.");$=await A("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(Q)}`,void 0,W);break}case"search_subscribers":{let W=w.companyId;$=await yJ(w,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function _z(b,w){if(b!=="get_recipient_suppression"&&b!=="remove_recipient_suppression")return{handled:!1,result:void 0};let $=P(w,"companyId"),W=Z(b,w,"email"),Q=P(w,"region"),G=new URLSearchParams;if(Q)G.set("region",Q);let D=`/api/v1/suppressions/${encodeURIComponent(W)}${G.size>0?`?${G}`:""}`;return{handled:!0,result:await A(b==="get_recipient_suppression"?"GET":"DELETE",D,void 0,$)}}async function Sz(b,w){let $;switch(b){case"list_team_members":{let W=w.companyId;$=await A("GET","/api/v1/team",void 0,W);break}case"invite_team_member":{let W=w.companyId,Q=Z("invite_team_member",w,"email"),G=H0("invite_team_member",w,"role",["admin","viewer","restricted"]);if(w.canManageBilling!==void 0&&typeof w.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");$=await A("POST","/api/v1/team/invitations",{email:Q,role:G,...w.canManageBilling!==void 0&&{canManageBilling:w.canManageBilling}},W);break}case"cancel_team_invitation":{let W=w.companyId,Q=Z("cancel_team_invitation",w,"invitationId");$=await A("DELETE",`/api/v1/team/invitations/${encodeURIComponent(Q)}`,void 0,W);break}case"list_conversations":{let W=w.companyId,Q=new URLSearchParams,G=Ub("list_conversations",w,"status",["open","closed","all"]);if(G)Q.set("status",G);let D=P(w,"search");if(D)Q.set("search",D);if(w.unread!==void 0){if(typeof w.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(w.unread)Q.set("unread","true")}if(w.page!==void 0){if(typeof w.page!=="number"||!Number.isInteger(w.page)||w.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");Q.set("page",String(w.page))}let X=zw("list_conversations",w,"limit",1,100);if(X!==void 0)Q.set("limit",String(X));$=await A("GET",`/api/v1/conversations${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_conversation":{let W=w.companyId,Q=Z("get_conversation",w,"conversationId");$=await A("GET",`/api/v1/conversations/${encodeURIComponent(Q)}`,void 0,W);break}case"reply_to_conversation":{let W=w.companyId,Q=Z("reply_to_conversation",w,"conversationId"),G=Ub("reply_to_conversation",w,"type",["outbound","note"])??"outbound",D=P(w,"subject"),X=P(w,"bodyText"),Y=P(w,"bodyHtml");if(G==="outbound"&&X===void 0&&Y===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");$=await A("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/messages`,{type:G,...D!==void 0&&{subject:D},...X!==void 0&&{bodyText:X},...Y!==void 0&&{bodyHtml:Y}},W);break}case"update_conversation_status":{let W=w.companyId,Q=Z("update_conversation_status",w,"conversationId"),G=H0("update_conversation_status",w,"status",["open","closed"]);$=await A("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/status`,{status:G},W);break}case"mark_conversation_read":{let W=w.companyId,Q=Z("mark_conversation_read",w,"conversationId");$=await A("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/read`,void 0,W);break}case"list_webhooks":{let W=w.companyId;$=await A("GET","/api/v1/webhooks",void 0,W);break}case"create_webhook":{let W=w.companyId,Q=Z("create_webhook",w,"name"),G=Z("create_webhook",w,"url"),D=ZW("create_webhook",w);$=await A("POST","/api/v1/webhooks",{name:Q,url:G,...D!==void 0&&{events:D}},W);break}case"update_webhook":{let W=w.companyId,Q=Z("update_webhook",w,"webhookId"),G=P(w,"name"),D=P(w,"url"),X=ZW("update_webhook",w),Y=Ub("update_webhook",w,"status",["enabled","disabled"]);if(G===void 0&&D===void 0&&X===void 0&&Y===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");$=await A("PATCH",`/api/v1/webhooks/${encodeURIComponent(Q)}`,{...G!==void 0&&{name:G},...D!==void 0&&{url:D},...X!==void 0&&{events:X},...Y!==void 0&&{status:Y}},W);break}case"delete_webhook":{let W=w.companyId,Q=Z("delete_webhook",w,"webhookId");$=await A("DELETE",`/api/v1/webhooks/${encodeURIComponent(Q)}`,void 0,W);break}case"test_webhook":{let W=w.companyId,Q=Z("test_webhook",w,"webhookId");$=await A("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/test`,void 0,W);break}case"list_webhook_deliveries":{let W=w.companyId,Q=Z("list_webhook_deliveries",w,"webhookId"),G=zw("list_webhook_deliveries",w,"limit",1,100),D=new URLSearchParams;if(G!==void 0)D.set("limit",String(G));$=await A("GET",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries${D.size>0?`?${D}`:""}`,void 0,W);break}case"replay_webhook_delivery":{let W=w.companyId,Q=Z("replay_webhook_delivery",w,"webhookId"),G=Z("replay_webhook_delivery",w,"deliveryId");$=await A("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries/${encodeURIComponent(G)}/replay`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var Rz=[Pz,Ez,_z,Nz,Mz,Iz,Zz,Vz,jz,EW,Kz,Sz,Fz];var vz=Bz.map(oJ).map(LJ);async function kz(b,w){try{let $,W=!1;for(let G of Rz){let D=await G(b,w);if(D.handled){$=D.result,W=!0;break}}if(!W)throw Error(`Unknown tool: ${b}`);let Q=uJ($);if(Q)throw Q;return $=await gJ(b,w,$),{structuredContent:dJ($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:yw($)}]}}}async function Cz(b,w,$){let W=w.getRequestContext?.(b)??{};try{return await uW(W,$)}finally{await w.onRequestContextUpdated?.(W,b)}}function Mv(b={}){let w=new XW({name:"sequenzy",version:HJ.version},{capabilities:{tools:{},resources:{}},instructions:["Sequenzy email marketing MCP server: manage subscribers, campaigns, sequences, templates, and delivery stats.","If you have access to multiple companies, call get_account and then select_company (or pass companyId per call) before other tools.","IMPORTANT: whenever the user wanted to accomplish something and these tools did not expose functionality for it (missing tool, missing argument, unsupported workflow, or broken behavior), call submit_feedback describing the gap before finishing the task. The Sequenzy team reads every submission and uses it to decide what to build next."].join(`
51
+ `)});return w.setRequestHandler(d4,async()=>{return{tools:vz}}),w.setRequestHandler(C1,async($,W)=>{let{name:Q,arguments:G}=$.params;return Cz(W,b,()=>kz(Q,G??{}))}),w.setRequestHandler(n4,async()=>{return{resources:AJ}}),w.setRequestHandler(m4,async($,W)=>{let{uri:Q}=$.params;return Cz(W,b,()=>OJ(Q))}),w}export{Mv as createSequenzyMcpServer};